如何修复超出范围的字符串索引?

时间:2012-11-20 21:33:01

标签: java string

我的程序遇到了以下问题(仅在尝试运行它时,构建正常):

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 57
at java.lang.String.substring(String.java:1907)
at Question7.main(Question7.java:68)

我知道网站上有类似的问题,但我正在经历我的脑海中的步骤,无法弄清楚这出错的地方。 我不认为所提出的代码/问题的背景非常重要;我认为这个问题与以下几个方面有关:

else if (s1.substring(i,i+1).matches("[0-9]"))

if (counthyphen == 3 && countdigits == 9 && (s1.substring(i, i+1).matches("[0-9]") || s1.substring(i, i+1).matches("X")))

但是,请自己看看。非常感谢帮助!

public class Question7
{
public static void main(String args[])
{
    //Declare and initialize.
    String s1 = new String("0-471-34609-8");
    int counthyphen = 0, countdigits = 0;

    //Begin "for" loop.
    for (int i = 0; i < s1.length()-1; i++)
    {
        /////////////////////////////////
        // Check for missing hyphens //
        if (s1.charAt(1) != '-')
        {
            i = s1.length();
        }
        else if (s1.charAt(11) != '-')
        {
            i = s1.length();
        }

        // Now add to the count values //
        if (s1.charAt(i) == '-')
        {
            counthyphen++;
        }
        **else if (s1.substring(i,i+1).matches("[0-9]"))**
        {
            countdigits++;
        }
        /////////////////////////////////
    }

    int i = s1.charAt(s1.length()-1);
    //Check if it's an ISBN and print result.
    **if (counthyphen == 3 && countdigits == 9 && (s1.substring(i, i+1).matches("[0-9]") || s1.substring(i, i+1).matches("X")))**
    {
        System.out.print("This number is an ISBN.");
    }
    else
    {
        System.out.print("This number is NOT an ISBN.");
    }
}
}

2 个答案:

答案 0 :(得分:3)

int i = s1.charAt(s1.length()-1);

此代码将ASCII code的{​​{1}}存储在索引中: - characters1.length() - 1可以大于certainly可访问的字符串索引。

对于例如,当前字符串中的maximum字符为last,其8为: - ASCII code,这肯定会失败。

所以,在你之后的if条件中56会失败。

事实上,我根本不了解这条线的必要性。你为什么用它?


此外,您s1.substring(i, i+1)阻止对我来说if-else: -

buggy

为什么在这两个块中为 if (s1.charAt(1) != '-') { i = s1.length(); } else if (s1.charAt(11) != '-') { i = s1.length(); } 分配了相同的值?

可能你想要这样的东西: -

i

答案 1 :(得分:0)

您正在零索引处启动for循环。

for(int i = 0; i&lt; s1.length() - 1; i ++)

然而,你的子串在以下代码中超越了我,

.substring(i,i + 1)。

在优化注释中,您可以使用regexp检查索引1和11处的连字符。

相关问题