SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
File Io
Exercise:
Programming Projects
Question:9 | ISBN:9780132830317 | Edition: 5

Question

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.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.