Ошибка StringIndexOutOfBoundsException

Рейтинг: 1Ответов: 2Опубликовано: 05.03.2015

Еще раз здравствуйте. Допер до того, что для начала нужно найти строку с цифрами. Делаю проверку и распечатываю, но вдруг падает на вот такой ошибке:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.String.charAt(Unknown Source)
    at TestingColor.fillCollection(TestingColor.java:61)
    at TestingColor.main(TestingColor.java:19)

Код:

for(int i= 0; i<stringList.size(); i++)
{
   if(Character.isDigit(stringList.get(i).charAt(i)))
     {
       System.out.println("Name" + " " + stringList.get(i));
     }else
     {
       System.out.println("Number" + " " + stringList.get(i));
     }
}

Подскажите, в чем проблема.

Ответы

▲ 1
public class StringIndexOutOfBoundsException
extends IndexOutOfBoundsException

Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.

Взято отсюда (первая ссылка в гугле)

▲ 1

Ошибка в этом куске кода charAt(i).
Так строка в i строке может быть короче, чем i. Символа с нужным индексом нет, вот и получаете. Скорее всего, там нужен ещё один цикл либо правильный код.