I am having trouble debugging the following code so that the input is 4 people and 4 separate grades with spaces in between that returns the student's grade based on the highest score, but I continuously get an error. Somebody please help. Thank You!
Output:
Enter the number of students: 4
Enter 4 scores: 55 48 70 58
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 4 out of bounds for length 4 at Ex7_1.main(Ex7_1.java:15)
import java.util.*;
public class Ex7_1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of students: ");
int num = Integer.parseInt(in.nextLine()) + 1;
System.out.printf("Enter %d scores: ", 4);
String input = in.nextLine();
String[] sArray = input.split(" ");
int[] array = new int[num];
for (int i = 0; i < num; i++) {
String sNum = sArray[i];
array[i] = Integer.parseInt(sNum);
}
int highest = 0;
for (int i = 0; i <= num; i++) {
if (array[i] >= highest) {
highest = array[i];
}
}
for (int i = 0; i <= num; i++) {
int score = array[i];
if (score >= (highest - 10)) {
System.out.printf("Student %d score is %d and grade is A", i, score);
} else if (score >= (highest - 20)) {
System.out.printf("Student %d score is %d and grade is B", i, score);
} else if (score >= (highest - 30)) {
System.out.printf("Student %d score is %d and grade is C", i, score);
} else if (score >= (highest - 40)) {
System.out.printf("Student %d score is %d and grade is D", i, score);
} else {
System.out.printf("Student %d score is %d and grade is F", i, score);
}
}
}
}
This code presents an error after making the <= to just < in both cases. I do not know how to solve that error. Please help. Thank You!