I am a novice Java student and am trying to complete a program that uses the scanner to input 5 students\' names, and then a loop within to get 3 grades for each student. I am
Your problem is in line 20.
grades[studentNumber][courseNumber] = input.nextInt();
that means that in the input, it is expecting an int, but it founds another thing, like a double, a char array or anything else
There is also another problem, you declare your grades as:
grades = new int[5][3];
the last number means that you can access to grades from [0..4][0..2]
but your if statement:
if (courseNumber < 5)
means that you will access to a number higher than '2' in
grades[studentNumber][courseNumber] = input.nextInt();
which will raise an OutOfBoundsException
Yes, like others have suggested, your problem in in the line:
grades[studentNumber][courseNumber] = input.nextInt();
Because your input is not recognised as an integer.
You should also be aware that your code will not loop through five times, it will go through once and exit since if statements do not repeat.
To loop you should probably use a for loop, something along these lines:
for(int i = 0; i < 5; i++){
//You code should be the same in here
}
Or change your if
's to while
.
From the docs:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
From your stack trace:
Exception at thread "main" java.util.InputMismatchException
at java.util.Scanner.throwfor{Scanner.java:909}
at java.util.Scanner.next{Scanner.java:1530}
at java.util.Scanner.nextInt{Scanner.java:2160}
at java.util.Scanner.nextInt{Scanner.java:2119}
at StudentGrades.main{StudentGrades.java:20}
the Exception is being thrown by your call to nextInt
.
Thus, you're getting an exception because you're requesting an integer and the Scanner is finding something that's not an integer.