0

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--;
    }
4

1 回答 1

5

这里的值f可以超过字符串的长度:

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

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

试试这个:

while (f < input.length()) {

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

    f++;
} 

第二个版本总是f < input.length()在尝试访问之前进行检查input.charAt(f)

于 2012-08-04T12:58:47.913 回答