String index out of range: n

2019-03-06 14:37发布

问题:

Im having a bit of a problem with this code each time i execute it it gives me an error String index out of range: 'n' n - is the no. of characters that is entered in the textbox pertaining to this code... (that is textbox - t2.)it is stuck at that first textbox checking it does not go over to the next as mentioned in the array.

Object c1[] = { t2.getText(), t3.getText(), t4.getText() };    
String b;
String f;
int counter = 0;
int d;
for(int i =0;i<=2;i++)
{
    b = c1[i].toString();
    for(int j=0;j<=b.length();j++)
    {
        d = (int)b.charAt(j);
        if((d<65 || d>90)||(d<97 || d>122))
        {
            counter++;
        }
    }
}

it is basically a validation code that i am trying to do without exceptions and stuff(still in the process of learning :) )

any help would be appreciated thx very much.

回答1:

Use <, not <= when iterating over the string. With <=, you get an out of bounds error, when j equals the length of the string. Remember that characters in the string are indexed starting from zero.

for(int j = 0; j < b.length(); j++)


回答2:

In java string.charAt(string.length()) will be out of bounds since the string is 0 indexed and so the last character is at string.length() - 1.



回答3:

Strings are indexed starting at 0. Your second for loop is set to end at b.length, which will always be 1 greater than the highest index for that string., Change it to j < b.length instead.