Write a program called GradesAverage, which prompts user for the number of stude
ID: 3554856 • Letter: W
Question
Write a program called GradesAverage, which prompts user for the number of students, reads it from the keyboard, and saves it in an int variable called numStudents. It then prompts user for the grades of each of the students and saves them in an int array called grades.
Your program must:
1. Make sure you store the grades entered in an array.
2. Compute the average in a separate method from the main().
3. Check the numStudents is a number, otherwise continue to prompt until they do.
4. Check the grade is between 0 and 100, otherwise continue to prompt until they do.
5. Have the user's entry from the console stay on the same line. (see example below)
Explanation / Answer
Here is the solution with commnets..plzz rate
import java.util.Scanner;
public class chegg {
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
String numStr ="";
int num=0;
Scanner sc = new Scanner(System.in);
//taking the user input
while (true) {
System.out.println("PLease enter the number of students");
//error handling the code if aynything other is entered
try{
numStr = sc.next();
num=Integer.parseInt(numStr);
}catch(Exception e){
continue;
}
if (num > 0) {
break;
}
}
int stud_marks[] = new int[num];
System.out.println("Enter the students marks now");
int i = 0;
//taking the grades as input
while (true) {
int enter = sc.nextInt();
if (stud_marks[i] > 100 && stud_marks[i] < 0)
continue;
else {
if (i == stud_marks.length) {
break;
}
stud_marks[i] = sc.nextInt();
i += 1;
}
}
// computing the average
computeAverage(stud_marks);
}
//average computing function
public static void computeAverage(int[] marks) {
int total = 0;
for (int i = 0; i < marks.length; i++) {
total += marks[i];
}
double average = total / marks.length;
System.out.println("Average:" + average);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.