0

I'm trying to check if the integers in an array are increasing. But I'm getting ArrayOutOfBounds exception, and I do not understand why. I'm new to programming.

for (int i =0; i > newArray.length ; i++){
    if (newArray[i] > newArray[i+1]){
        System.out.println("Not increasing");
    }
}

Thank you for your help.

phwt
  • 1,356
  • 1
  • 22
  • 42
Akchene_ye
  • 13
  • 3

2 Answers2

0

Let’s say your array length is 8 so the positions are from 0 to 7 In the last run of the for loop i=7 and i+1 =8 You don’t have newArray[i+1] You should put the first if inside a new if

if(i<(newArray.length - 1)){
if (newArray[i] > newArray[i+1]){
System.out.println("Not increasing");
}
}
JaceB41
  • 16
  • 2
0

the ArrayOutOfBounds exception happens when you are trying to access a non-existent position in the array.

The problem in your case is the newArray[i+1] which tries to access a position non-existent in your array. I recommend editing the condition i < newArray.length-1 : There are, of course, other ways to fix this but this is the easiest.

N_Craft
  • 70
  • 7