2. Write a program that asks the user to enter the name of a file that contains
ID: 3591380 • Letter: 2
Question
2. Write a program 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 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"Explanation / Answer
package com.learn.sample;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class MyFirstClass {
private static final String FILENAME = "D:\test\p.txt";
private static final String COMMA_SEPERATED = "###,###.00"; // For formatting of decimal average to be later used in the program
public static void main(String[] args) {
double sum = 0; // sum of all numbers greater than the specified number
double count = 0; // count of numbers which are greater than the specified number
File file = new File(FILENAME);
Scanner scanner ;
System.out.println("Tytpe the number to be checked");
scanner = new Scanner(System.in);
double number1 = scanner.nextDouble(); // getting the number from the user
//System.out.println(number1);
try {
scanner = new Scanner(file); // here i have used pre specified path of the file which contains the integers as you have
} catch (FileNotFoundException e) { // shown in the format.
// TODO Auto-generated catch block
e.printStackTrace();
}
while (scanner.hasNextInt()) {
double number2 = scanner.nextDouble();
if(number2 > number1){
sum = sum + number2; // summing the numbers which are greater than the specified number
count++; // counting the total occurences of the numbers which are greater than the specified number
}
}
double average = sum/count; // calculating the average
DecimalFormat decimalFormat = new DecimalFormat(COMMA_SEPERATED);
System.out.println(decimalFormat.format(average)); // showing the result in the
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.