Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

please use comments i will be tested on something similar Write a Java program n

ID: 3676307 • Letter: P

Question

please use comments i will be tested on something similar

Write a Java program named "average.java" to calculate the average score of a mid term exam. The scores are stored in a file named "score.txt" , and the format score is as below:

Armstrong   88
Brown       90
Crippen       75
Russell       97
…       …

There are two columns in the "score.txt". The first column shows the names of students who took the exam. Each name consist of one word (no space). The second column stores the scores of stdents. The two columns are separated by a tab character.

- the score average should be double

- score.txt contains an arbitrary number of lines

- use try catch, and arrays for name and grade.

Explanation / Answer

import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;

/**
* @author Srinivas Palli
*
*/
public class Average {

   /**
   * @param args
   */
   public static void main(String[] args) {
       Scanner scanner = null;
       try {

           File file = new File("score.txt");
           scanner = new Scanner(new FileInputStream(file));
           int noOfRecs = 0;
           // counting no of lines in the file
           while (scanner.hasNext()) {
               noOfRecs++;
               scanner.nextLine();

           }
           scanner.close();

           scanner = new Scanner(new FileInputStream(file));
           // declaring arrays with size noofRecs
           String studentNames[] = new String[noOfRecs];
           double studentScores[] = new double[noOfRecs];
           double sum = 0;
           int i = 0;
           // assinging values to array by reading data from file
           while (scanner.hasNext()) {
               studentNames[i] = scanner.next();
               double studentScore = scanner.nextDouble();
               studentScores[i] = studentScore;
               sum += studentScore;

               i++;

           }
           // calculating average
           double average = sum / (double) noOfRecs;
           // printing data
           System.out.println("Name Score");
           for (i = 0; i < noOfRecs; i++) {
               System.out.println(studentNames[i] + " " + studentScores[i]);

           }
           // printin average
           System.out.println(" Average Score is :" + average);

       } catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
       } finally {

           scanner.close();
       }
   }
}

score.txt
Armstrong   88
Brown   90
Crippen   75
Russell   97

OUTPUT:
Name   Score
Armstrong   88.0
Brown   90.0
Crippen   75.0
Russell   97.0

Average Score is :87.5