IndexOutOfBounds异常,原因不明显

时间:2018-02-14 15:43:37

标签: java

我无法弄清楚导致此代码抛出IndexOutOfBounds异常的原因。我想我可能只是遗漏了一些东西。

如果我的输入字符串是$15,导致异常的原因是什么以及我需要更改什么来阻止异常发生?

if(token.contains("$"))
{
    System.out.println("$ found");
    int symbolPosition = token.indexOf("$");
    int currentPosition = symbolPosition;
    String afterSymbol = ""; //the string succeeding the $ character, up until the end of the string or a , or ) is met
    char nextChar = '\0';

    for(; currentPosition < token.length(); currentPosition++)
    {
        if(token.charAt(currentPosition) != ',' || token.charAt(currentPosition) != ')')
        {
            char nChar = token.charAt(currentPosition+1);
            afterSymbol = afterSymbol.concat(Character.toString(nextChar));
        }
    }

控制台输出:

$15
Token $15 is of type 3
$ found
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3

1 个答案:

答案 0 :(得分:0)

您的问题在于

的nChar行
 for(; currentPosition < token.length(); currentPosition++)
        {
            System.out.println(currentPosition);
            if(token.charAt(currentPosition) != ',' || token.charAt(currentPosition) != ')')
            {
                char nChar = token.charAt(currentPosition+1);
                afterSymbol = afterSymbol.concat(Character.toString(nextChar));
            }
        }

在for循环的第一次迭代中,Variable currentPosition的值为2。当它尝试创建nChar变量时,代码会尝试访问输入的current position +1或第3个位置。在这种特定情况下,令牌$也是字符串中的最后一个字符,因此当$是最后一个字符时,执行for循环将始终导致越界异常。要解决此问题,我建议将for循环更改为

for(; currentPosition < token.length()-1; currentPosition++)

因此,当for循环执行时,token.charAt(currentPosition+1);处将始终存在一个字符。

询问您是否有任何问题。

相关问题