•Create a file that has the following numbers: 10, 90, 30, 70, 40, 80, 100. •Wri
ID: 3716792 • Letter: #
Question
•Create a file that has the following numbers: 10, 90, 30, 70, 40, 80, 100.
•Write a function fileToArray which creates an array, asks the user for a file name, opens the file and reads the numbers into the array. The function should return the array created.
•Copy the sequential search alg into your program
•Ask the user for a number to search for. The program should display whether the number was in the file or not. Keep asking the user for numbers to search for until they press ‘q’ to quit.
CODE IN JAVA
Explanation / Answer
import java.io.*;
class CreateFile{
// writing the desired functions
int[] fileToArray(String filename){
int [] a=int[];
int counter=0;
FileInputStream fis=null;
try{
fis=new FileInputStream(filename);}
catch(FileNotFoundException e){
System.out.println("File Not Found");
}
BufferedInputStream bis=new BufferedInputStream(fis);
int ch;
//reading the contents of file into an Array
while((ch=bis.read()) != -1){
A[counter]=ch;
counter++;}
bis.close();
return A;
}
void search(int num, int[] A){
int flag=0;
for(int i=0, i<A.length;i++){
if(A[i]==num){
System.out.println("Yes, the number"+num+" is in the file.");
flag=1;
break;}}
if(flag==0){
System.out.println("No, the number "+num+" doesn't belong to file.");
}
}
public static void main(String args[]) throws IOException{
//Creating a file with name myfile.txt having contents 10, 90, 30, 70, 40, 80, 100
FileOutputStream fos=new FileOutputStream("myfile.txt",true);
BufferedOutputStream bos=new BufferedOutputStream(fos,1024);
bos.write("10");
bos.write("90");
bos.write("30");
bos.write("70");
bos.write("40");
bos.write("80");
bos.write("100");
bos.close();
int [] A=fileToArray()
//Calling fileToArray in main
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the filename you want to open:");
String fname=br.readLine();
CreateFile cf=new CreateFile();
int A[]=cf.fileToArray(fname);
// Prompting the user for searching a number in File
System.out.println("Please enter a number to search in the file or Press q to quit");
ch c=br.readline;
if(ch==q)
exit;
else
cf.search(Interger.parseInt(ch),A);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.