Nikki Kulyk
Nikki Kulyk

Reputation: 31

Array not looping correctly - Java

I have an array with 60 values, and when I click the next button, it will cycle through all of the values of my array in ascending order until the number 60, then it starts at number one again.

I also have a previous button, so I can go down values instead of going up. When I hit the previous button on the first array value [0], my app crashes and I am not sure why.

Here is my code:

public String nextFact() {
    i++;
    if(i >= facts.length) {
        i = 0;
    }
    return facts[i];
}

public String previousFact() {
    i--;
    if(i < 0) {
        i = facts.length;
    }
    return facts[i];
}

Upvotes: 0

Views: 72

Answers (2)

Denis
Denis

Reputation: 1229

Your array is of size array.length. So the last index will be array.length-1. In your previous function, you assign array.length to i. This is larger index than max index for array and therefore it crashes down. You must be getting am indexoutofbound error too.

You should replace that line with this:

i = facts.length - 1;

Upvotes: 0

rgettman
rgettman

Reputation: 178333

You are getting an ArrayIndexOutOfBoundsException when you change i to facts.length, because valid array indexes range from 0 through facts.length - 1. Set i to facts.length - 1.

if(i < 0) {
    i = facts.length - 1;
}

Your wrapping-around code for greater than or equal to the length should be working fine.

Upvotes: 2

Related Questions