In: Computer Science
In java, Write a program that reads a data file containing final exam scores for a class and determines the number of passing scores (those greater than 60) and the number of failing scores (those less than 60). The average score as well as the range of scores should also be determined.
The program should request the name of the data file from the end user. The file may contain any number of scores. Using a loop, read and process each score until the end of file is encountered. Once all data has been processed, display the statistics.
The input file should consist of integer values between 1 and 100. We will assume that the data file contains only valid values. The data file can be created using jGrasp by using File | New | Plain Text. The file should be stored in the same folder as the .java file.
Hint: The smallest and largest values can be determined as the data is read if the variables are initialized to opposite values. For example, the variable holding the largest score is initialized to 0, and then reset as needed after each data item is read.
The Scanner class should be used to read the file. End user input/output may be accomplished using either a) Scanner & print methods, OR (b) JOptionPane methods. All end user input and output must use the same I/O technique.
The throws clause should be added to the main method header:
public static void main(String[] args) throws IOException
Example run 1:
Enter the file name to be read: scores1.dat
15 scores were read:
14 passing scores
1 failing scores
The score ranges from 50 to 100
The average is 79.80
Example run 2:
Enter the file name to be read: scores2.dat
20 scores were read:
17 passing scores
3 failing scores
The scores ranges from 52 to 99
//Java code
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the file name to be read: "); String fileName = input.nextLine(); //Open the file try { int max=0,min=0,counter =0,passingCounter=0,failingCounter=0; double sum=0,avg=0; Scanner scanFile = new Scanner(new File(fileName)); while (scanFile.hasNextLine()) { int num = scanFile.nextInt(); if(counter==0) { min =num; max=num; } else { if(min>num) min = num; if(max<num) max = num; } if(num<60) { failingCounter++; } else { passingCounter++; } sum+=num; counter++; } //find average avg = sum/counter; //Print statics System.out.print(counter+" scores were read.\n"+passingCounter+" passing scores\n"+failingCounter+" failing scores\nthe score ranges from "+min+" to "+max+"\nThe average is "+String.format("%.2f",avg)+"\n"); } catch (FileNotFoundException e) { System.err.println("ERROR!! file not found."); } } }
//file
//Output
//If you need any help regarding this solution ......... please leave a comment ....... thanks