Firefoxx Pwnass
Firefoxx Pwnass

Reputation: 135

StringIndexOutOfBoundsException in while loop

I have this code:

String input = JOptionPane.showInputDialog("Enter text");
StringBuilder forward = new StringBuilder("");
StringBuilder backward = new StringBuilder("");
int f = 0;
int b = input.length();


while(f < input.length()) {

    while(input.charAt(f) > 63) {

        forward.append(input.charAt(f));
        f++;

    }

    f++;
} 

System.out.println(forward);

although program is not finished, it already throws an exception here. It says:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5 ( Range depends on, how many character i enter ) at java.lang.String.charAt(Unknown Source)

Strange thing is that i yesterday worked on similar code and it worked perfectly, and it was practical the same.

I already searched stack forums and docs oracle but i only found that this exception is thrown when is index equal the size of the string ( for charAt method ).

So still it seems to be the problem right here but i can't find it.

while(input.charAt(f) > 63)

EDIT:

Why is that code not working? Again its throwing same exception as above?

while(b > 0) {

        if(input.charAt(b) > 63) {

            backward.append(input.charAt(b));

        }

        b--;
    }

Upvotes: 0

Views: 205

Answers (1)

Mark Byers
Mark Byers

Reputation: 837926

The value of f can exceed the length of the string here:

while (input.charAt(f) > 63) {
    forward.append(input.charAt(f));

    // This next line might increase f past the end of the string.
    f++;
}

Try this instead:

while (f < input.length()) {

    char c = input.charAt(f);
    if (c > 63) {
        forward.append(c);
    }

    f++;
} 

The second version always checks f < input.length() before attempting to access input.charAt(f).

Upvotes: 5

Related Questions