Create a FileReadPractice.java. You will read the following input: 99 87 88 76 9
ID: 3683572 • Letter: C
Question
Create a FileReadPractice.java. You will read the following input: 99 87 88 76 93 56 87 file Scores.txt. In the main: · Display the values after each read. The logic to this is similar to what you have done in the past with data coming from the keyboard, this time the data is from input file. · You will use try-catch block to handle error/exceptions. only create Scanner object in try block o display message “Error opening input file.” in catch block · Calculate the average at the end. Should display if there were values read. If no values are read (file empty), display message “File is empty.
Explanation / Answer
FileReadPractice.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class FileReadPractice {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
String fileName = "D:\Scores.txt";
File file = new File(fileName);
if(file.exists()){
BufferedReader br = new BufferedReader(new FileReader(file));
String sCurrentLine;
String values[] = null;
boolean status = false;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
values = sCurrentLine.split(" ");
status = true;
}
if(status){
int sum = 0;
for(int i=0; i<values.length; i++){
sum = sum + Integer.parseInt(values[i]);
}
System.out.println("The Average of all values : "+((double)sum/values.length));
}
else{
System.out.println("File is empty");
}
br.close();
}
else{
System.out.println("File does not exist");
}
}
catch(Exception e){
System.out.println("Error opening input file.");
}
}
}
Output:
99 87 88 76 93 56 87
The Average of all values : 83.71428571428571
Scores.txt
99 87 88 76 93 56 87