In Java Write a program that reads a text file that contains
In Java:
Write a program that reads a text file that contains a grade (for instance, 87) on each line. Calculate and print the average of the grades.
Solution
import java.io.BufferedReader;
 import java.io.FileReader; // importing filereader
 import java.io.IOException; // importing file io exceptions
public class grade {
public static void main(String[] args) {
       BufferedReader br = null;
        double count=0;
        int noOfgrades=0;
try {
           String sLine;
       
            br = new BufferedReader(new FileReader(\"sample.txt\")); // reading file using buffer reader
           while ((sLine = br.readLine()) != null) { // rading line by line
                    noOfgrades=noOfgrades+1; // getting number of grades
                    int num=Integer.parseInt(sLine); // convert string into integer
                    count=count+num; // adding each grade to count
            }
            System.out.println(\"count:\\t\"+count);
            System.out.println(\"noOfgrades:\\t\"+noOfgrades);
            System.out.println(\"Average of the grades:\\t\"+(count/noOfgrades));
           
       } catch (IOException e) {
            e.printStackTrace(); // catch exception
        } finally {
            try {
                if (br != null)br.close(); // closing buffer
            } catch (IOException ex) {
                ex.printStackTrace();// printing exceptions
            }
        }
   }
 }
/********** out file******
 fileName:sample.txt
 file contains \"
 23
 34
 56
 7
 88
 89
 52
 34
 65
 \"
 */
 /************output*************
 count: 448.0
 noOfgrades: 9
 Average of the grades: 49.77
 */


