user181415 user181415 - 7 months ago 21
Java Question

Arrays Checking input

So I'm trying to check input and if the entered integer is not greater than the previous one it should ask again. My program already checks if integer is out of bounds and if it's not an integer that is entered but it just doesn't check if the entered one is greater than the previous one.

for (int i = 0; i < finalGrades.length; i++){
//check input is an integer
while(!input.hasNextInt()){
System.out.print("Please enter integers only: ");
input.next();
}

finalGrades[i] = input.nextInt();
if(finalGrades[i] > 100 || finalGrades[i] < 0){
System.out.print("Please enter integers between 0 and 100 only:");
finalGrades[i] = input.nextInt();
}
if(finalGrades[i] < finalGrades[i-1]){
System.out.print("Please enter integers in ascending order only: ");
finalGrades[i]= input.nextInt();
continue;
}

}

Answer

You are getting an array out of bounds error in both cases where you use

    for(int i = 0; i < list.length; i++){}

and

    for(int i = 1; i <= list.length; i++){}

because in case one, at the beginning of your loop you will try to access array[-1] when i=0 and in case two you will get an array out of bounds error when you reach the end of the for loop and i=list.length because the last index of your array is going to be list.length-1 due to arrays starting at index 0.

The easiest solution I can think for your situation is to just put in a check and only do your comparison if i > 0

if(i > 0){
    if(finalGrades[i] < finalGrades[i-1]){
        System.out.print("Please enter integers in ascending order only: ");
        finalGrades[i]= input.nextInt();
        continue;
    }
}