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:3 | ISBN:9780132830317 | Edition: 5

Question

Write a program that takes its input from a text file of strings representing numbers of type double and outputs the average of the numbers in the file to the screen. The file contains nothing but strings representing numbers of type double, one per line.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.util.*;
import java.io.*;
public class Typeconversion 
{
	public static void main(String args[])
	{
		Scanner input = null;
		try
		{
			input = new Scanner(new FileInputStream("input.txt"));
		}
		catch(FileNotFoundException e)
		{
			System.out.println("file was not found.");
		}
		double sum = 0;
		int number = 0;
		while(input.hasNextDouble())
		{
			sum += input.nextDouble();
			number++;	
		}
		System.out.println("The Average of numbers: " + sum /number);
		input.close();
	}
}

Sample Run:

Date in input text file:
2.5
3.45
0.54
7.8
5.53
4.45
2.09
6.78
9.45
3.56
7.49

Output at console:
The Average of numbers: 4.876363636
0 0

Discussions

Post the discussion to improve the above solution.