Write a program with string class that asks the user to enter the name of a file
ID: 3600248 • Letter: W
Question
Write a program with string class that asks the user to enter the name of a file that contains a set of integer values, and then asks the user to enter an integer number. The program should display the average of the numbers that are greater than the input number. User Notepad or another text editor to create a simple file that can be used to test the program.
First, the user enters the file name as below:
Enter the file name: myText.txt
and if, for example, the file ‘mytext.txt’ contains the following numbers:
30
44
23
56
43
2
32
35
90
12
and then, if the user enters an integer number, as:
The number to check: 40
the program should display the output as:
The average of the numbers that are greater than 40 is 58.25
Note that average of numbers 44, 56, 43 and 90 is 233/4 = 58.25. The average must be shown up to two decimal points. (Hint: DecimalFormat class can be used).
If the input file is not found, the user must be prompted to enter the filename again with the following message “File is not found, enter the filename again”.
• All programs that you submit must compile. A program will receive an automatic 0 if it does not compile.
• The programs must be well commented, properly indented, and clearly written.
• As needed, you can use either console I/O or graphical I/O statements in your programs.
Explanation / Answer
ReadNumbersFromFile.java
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadNumbersFromFile {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Enter the file name: ");
String fileName = scan.next();
File file = new File(fileName);
while(!file.exists()) {
System.out.println("File is not found. Please enter the file name again: ");
fileName = scan.next();
file = new File(fileName);
}
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner read = new Scanner(file);
while(read.hasNextInt()) {
list.add(read.nextInt());
}
System.out.println("Enter the number to check: ");
int n = scan.nextInt();
int total = 0;
int count = 0;
for(int i=0;i<list.size();i++) {
if(list.get(i)>n) {
count++;
total+=list.get(i);
}
}
double average = total/(double)count;
System.out.println("The average of the numbers that are greater than "+n+" is "+df.format(average));
}
}
Output:
Enter the file name:
D:\myText.txt
Enter the number to check:
40
The average of the numbers that are greater than 40 is 58.25
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.