Write a program that takes its input from a binary file of numbers of type double and outputs the average of the numbers in the file to the screen. The file contains nothing but numbers of type double written to the file with writeDouble.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TestDemo
{
public static void main(String args[])
{
try
{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("writeIntFile.dat"));
System.out.println("Random integer numbers are: ");
for (int i = 0; i < 10; i++)
{
double number = (Math.random() * 20 + 1);
System.out.println(" " + number);
os.writeDouble(number);
}
os.close();
ObjectInputStream is = new ObjectInputStream(new FileInputStream("writeIntFile.dat"));
double total = 0;
int num = 10;
try
{
while (true)
{
total += is.readDouble();
}
} catch (IOException e) {
System.out.println("\nAverage: " + total / num);
}
} catch (IOException e)
{
System.out.println("Error occured in output file.");
}
}
}
OUTPUT:
Random integer numbers are:
12.232332853166644
3.782221279440613
12.070135554532076
9.691511951132489
14.04607784749599
6.088144708416447
8.380123326381707
7.6415304709136835
19.406012851267814
16.78591090488965
Average: 11.01240017476371