Question

I have been sitting whole day with this problem:

I have a String array.After parsing String line

str3.split("\\n"));

Then I want to make it display with Next/Previous buttons.

String text = null;

    if (rotation){

        if (count < fullString.length) {

            for (int i = count; i <= fullString.length - 1; i++) {
                text = fullString[i];
                ++count;
                if (text.trim().length() > 0 & !text.isEmpty()){
                    return text;

                }
            }
        }
    }

    if (!rotation) {

        if (count > 0) {
            for (int i = count ; i >= 0; i--) {
                text = fullString[i - 1];
                --count;
                if (text.trim().length() > 0 & !text.isEmpty()){
                    return text;
                }
            }
        }
    }

It woks, but need to press button twise (If press "Next" after that I should press "Previous" twise). I know, this is the silly question, but I can't find out the problem.

Was it helpful?

Solution

The problem is you're not consistent with the meaning you give to count inside your loops.

Possible meanings for count

1. count represents the next item, the one that you want to return.

In this case your loops should start at count+1 and count-1, respectively, and should both use fullString[i].

2. count represents the current selected item, and you want the next.

In this case your loops should both start at count and you should reference fullString[i+1] (first loop) or fullString[i-1] (second loop). You'll also have to be careful to change the end condition of your loops, so that i+1 and i-1 are not out of bounds.

Current problem: mixed approaches

In the current state of your code, you mix both approaches:

  • In the first loop, you start at count but use fullString[i]. Making one press on the button useless because you don't increment count right away.

  • In the second loop, you use the second option without changing the end condition. This will trigger an ArrayIndexOutOfBoundException when count is 0 (or you don't find a non-empty string before index 0), as @Mifeet pointed out in a comment you decided to ignore.

Improvement

Also, since you increment/decrement count anyway, I would use it directly instead of adding an index i. This makes your loops cleaner, and you can also get rid of the if on count.

if (rotation) {
    for (count++; count <= fullString.length - 1; count++) {
        text = fullString[count];
        if (text.trim().length() > 0) {
            return text;
        }
    }
}

if (!rotation) {
    for (count--; count >= 0; count--) {
        text = fullString[count];
        if (text.trim().length() > 0) {
            return text;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top