need a java program that searches a binary file of numbers of type int and displ
ID: 3829291 • Letter: N
Question
need a java program that searches a binary file of numbers of type int and displays the numbers and the sum,
average, minimum, and maximum of the numbers to the console. The name of the binary number file is
"chapter10numbers.dat".
For reference, the contents of the dat file are these 5 numbers.
27
5
50
10
2
***specifications
use an InputStream to read the binary file and a loop to read each record in the file.
Import java.io.ObjectInputStream
Import java.io.FileInputStream
use a Try – Catch block to catch any errors.
The output must to look like this.
output Chap10Question9 (run) Number Numbers read from file 50 10 Grand Total: 94.0 Count: Statistics computed from file data Average: 18.8 Smallest number: 2 Largest number 50 BUILD SUCCESSFUL (total time: 0 seconds)Explanation / Answer
Please find my implementation.
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BinaryFileRead {
public static void main(String[] args) {
// create an ObjectInputStream for the file we created before
try {
// first writing binary file
FileOutputStream out = new FileOutputStream("chapter10numbers.dat");
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeInt(27);
oout.writeInt(5);
oout.writeInt(50);
oout.writeInt(10);
oout.writeInt(2);
oout.close();
out.close();
// now reading file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("chapter10numbers.dat"));
double total = 0;
int count = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int i = 0;
while(i < 5){
int num = ois.readInt();
count++;
total += num;
if(num > max)
max = num;
if(num< min)
min = num;
i++;
}
System.out.println("Grand total: "+total);
System.out.println("Count: "+count);
System.out.println("Average: "+(total/count));
System.out.println("Smallest number: "+min);
System.out.println("Largest number: "+max);
ois.close();
} catch(EOFException e){
}catch (IOException e) {
e.printStackTrace();
}
}
}
/*
Sample run:
Grand total: 94.0
Count: 5
Average: 18.8
Smallest number: 2
Largest number: 50
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.