Chloe Yoshino
Chloe Yoshino

Reputation: 43

Why does java.lang.ArrayIndexOutOfBoundsException occur?

I'm making an array that outputs a user's input in reverse order. My program works however I keep getting this message, "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at Reverse.main(Reverse.java:26)"

I'm looking at line 26 which is, "System.out.println(number[x]);" but I don't see what's the matter with this. Why is this occurring?

    for(int x= number.length -1; x<SIZE; x--) 
    System.out.println(number[x]); 
   }
 }

Upvotes: 0

Views: 885

Answers (3)

Razib
Razib

Reputation: 11163

The problem is in your for loop -

for(int x= number.length -1; x<SIZE; x--) 
    System.out.println(number[x]);  

After setting x to number.length-1 x indefinitely decrements. Once x become negative and the number[] array is trying to get value using negative index for example number[-1]. Then ArrayIndexOutOfBound exception occurred. Use the following code snippet instead -

for(int x= number.length -1; x>=0; x--) 
        System.out.println(number[x]);  

Your code perfectly showing output because the exception occurred after the output has been displayed. The code displays all element from number[] array and then the exception occurred.

Thanks a lot.

Upvotes: 1

rgettman
rgettman

Reputation: 178263

You are attempting to output the elements in reverse order, but your for loop condition is similar to the y for loop that enters integers into the array.

But counting x backwards, the condition x<SIZE will always be true, even if you run off the beginning of the array. This explains the ArrayIndexOutOfBoundsException.

You must stop the x for loop once x has passed 0.

for(int x = number.length - 1; x >= 0; x--) 

Upvotes: 3

dahui
dahui

Reputation: 2166

The loop is repeating whilst x is less than SIZE. SIZE is 10 so it keeps going beyond zero and checks for the location -1.

Change the check in the second for loop to be

x >= 0

Upvotes: 3

Related Questions