I am doing java programming practice from a website. I have to display this out put using arrays.
Enter the number of students: 3
Enter the grade for student 1: 55
Enter the grade for student 2: 108
Invalid grade, try again...
Enter the grade for student 2: 56
Enter the grade for student 3: 57
The average is 56.0
This is my source code so far. It is showing results but not working properly. It takes number of students & grade for 1st student. But then it halts, if I press any number & press enter, it asks for next grade & so on. And this way it prints average at the end. If I enter not allowed input, it catches that.
What is wrong in this code.
package array;
import java.util.Scanner;
public class GradesAverage {
public static void main(String[] args) {
int numStudents, sum=0;
int[] grades;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students : ");
numStudents = in.nextInt();
grades = new int[numStudents];
//System.out.println(grades.length);
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter grade of student "+i+" :");
grades[i] = Integer.parseInt(in.next());
if(grades[i]>100 || grades[i]<0)
{
System.out.println("It is not a valid number!");
i--;
continue;
}
//grades[i] = Integer.parseInt(in.next());
sum+=grades[i];
}
System.out.print("Average grades are: "+sum/numStudents);
in.close();
}
}
Instead of using your temp variable, create a variable like this:
int grade = in.nextInt()Then check
if(grade > 100 || grade < 0) // error messageDon’t use
in.next()twice, because it then asks the user for another number.