The Java program opens a file, reads grades within it, and uses a method to calculate and display:
1) The grades with their letter values (A, B, C, etc.)
2) The sum of all grades in the file
3) The average of all grades in the file
Write a Java program that opens the file, reads all the Grade from t.pdf
1. Write a Java program that opens the file, reads all the Grade from the file, and using a method
calculates and displays the following A) Displays the grades with their letter values (80 - B) B)
the sum of the Grades in the file C) the average of the Grades in the file
Solution
GradeRead.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class GradeRead {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan1 = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = scan1.next();
File file = new File(fileName);
if(file.exists()){
Scanner scan = new Scanner(file);
calculateGradeDetail(scan);
}
else{
System.out.println("Input does not exist");
}
}
public static void calculateGradeDetail(Scanner scan){
int sum = 0;
int count = 0;
char gradeLetter = '0';
while(scan.hasNextInt()){
count++;
int n = scan.nextInt();
sum = sum + n;
if(n >=90 && n<=100){
gradeLetter = 'A';
2. }
else if(n >=80 && n<90){
gradeLetter = 'B';
}
else if(n >=70 && n<80){
gradeLetter = 'C';
}
else if(n >=60 && n<=70){
gradeLetter = 'D';
}
else {
gradeLetter = 'E';
}
System.out.println("Grade: "+gradeLetter+" - "+n);
}
System.out.println("The sum of the Grades in the file: "+sum);
double average = sum/(double)count;
System.out.println("the average of the Grades in the file: "+average);
System.out.println();
}
}
Output:
Enter the file name: D:grade.txt
Grade: D - 60
Grade: C - 70
Grade: B - 80
Grade: A - 90
Grade: A - 100
Grade: E - 40
Grade: E - 50
Grade: D - 60
The sum of the Grades in the file: 550
the average of the Grades in the file: 68.75
Grade.txt
60
70