Find the average grade of 10 students and number of students

Find the average grade of 10 students and number of students with the grade greater than the average. Add a try/catch block to ensure that while entering grades, a negative value is not encountered. Allow the user to reenter the grade. Then test your program. Using java write this program, and use comments to explain the lines of code.

Solution

AverageGrade.jaava

import java.util.InputMismatchException;
import java.util.Scanner;


public class AverageGrade {

  
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       int grade[] = new int[10];
       for(int i=0; i<grade.length; i++){
           try{
               System.out.print(\"Enter student \"+(i+1)+\" grade: \");
               grade[i] = scan.nextInt();
               if(grade[i] < 0){
                   System.out.print(\"Invalid input. \");
                   i--;  
               }
           }catch(InputMismatchException e){
               System.out.print(\"Invalid input. \");
               scan.nextLine();
               i--;
           }
       }
       int sum = 0;
      
       for(int i=0; i<grade.length; i++){
           sum = sum + grade[i];
       }
       double average = sum/(double)grade.length;
       int aboveAverage = 0;
       for(int i=0; i<grade.length; i++){
           if(average < grade[i]){
               aboveAverage++;
           }
       }
       System.out.println(\"The average grade of 10 students: \"+average);
       System.out.println(\"The number of students with the grade greater than the average: \"+aboveAverage);
   }

}

Output:

Enter student 1 grade: 10
Enter student 2 grade: 20
Enter student 3 grade: 30
Enter student 4 grade: 40
Enter student 5 grade: -50
Invalid input. Enter student 5 grade: 50
Enter student 6 grade: 60
Enter student 7 grade: a
Invalid input. Enter student 7 grade: 70
Enter student 8 grade: 80
Enter student 9 grade: 90
Enter student 10 grade: 100
The average grade of 10 students: 55.0
The number of students with the grade greater than the average: 5

Find the average grade of 10 students and number of students with the grade greater than the average. Add a try/catch block to ensure that while entering grades
Find the average grade of 10 students and number of students with the grade greater than the average. Add a try/catch block to ensure that while entering grades

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site