I need help. Had similar quesiton to this but this time its under \"Arrays Homew
ID: 3741446 • Letter: I
Question
I need help. Had similar quesiton to this but this time its under "Arrays Homework". This is for JAVA ECLIPSE
Write a program that asks the user for the name of a file. The program should read all the numbers from the given file and display the total and average of all numbers in the following format (three decimal digits):
Total: nnnnn.nnn
Average: nnnnn.nnn
Class name: FileTotalAndAverage
Test Case 1
double_input1.txt
double_input2.txt
Test Case 2
double_input1.txt
double_input2.txt
Test Case 3
double_input1.txt
double_input2.txt
The code is suppose to be able to get these kind of test cases. Please help
Standard Input Files in the same directorydouble_input1.txt
double_input1.txt
double_input2.txt
Explanation / Answer
ReadFileNumbersAndSum.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileNumbersAndSum {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the file name: ");
String fileName = scan.next();
File file = new File(fileName);
while(!file.exists()) {
System.out.println("File '"+fileName+"' does not exist.");
System.out.println("Please enter the file name again: ");
fileName = scan.next();
file = new File(fileName);
}
Scanner read = new Scanner(file);
int count =0;
double sum = 0;
while(read.hasNextDouble()){
sum+=read.nextDouble();
count++;
}
System.out.printf("Total: %.3f ",sum);
System.out.printf("Average: %.3f ",sum/count);
}
}
Output:
Please enter the file name:
test.txt
File 'test.txt' does not exist.
Please enter the file name again:
D: umbers.txt
Total: 297925.000
Average: 5841.667