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.
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