String index out of range: n

安稳与你 提交于 2020-01-22 02:49:08

问题


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.



来源:https://stackoverflow.com/questions/9020859/string-index-out-of-range-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!