Strange String out of Bounds异常

时间:2014-11-06 23:36:55

标签: java string indexoutofboundsexception

我正在研究一种测试短语是否为回文的方法。该方法接受一个字符串并检查该字符串的第一个和最后一个字母是否相同。如果是这样,它会删除这些字母,然后再次检查字符串,直到使用递归函数只剩下一个(或零)字母。目前

String start = s.substring(0, 1);
String end = s.substring(s.length() - 1, s.length());

取每个字符串的第一个和最后一个字母;但是,如果我使用两个字母的字符串,我会得到一个字符串索引超出界限错误。我认为将索引更改为0会有所帮助但我后来意识到甚至没有抓住第一个字母。对于长度为1或超过2个字符的字符串没有问题。如果你们都需要它,我会把下面的方法放在下面,但是目前程序甚至没有用两个字母的字符串运行那么远。

public static boolean palindromeTester(String s){
       s = justLetters(s); //calls a method that removes all spaces, punctuation
       String start = s.substring(0, 1);
       String end = s.substring(s.length() - 2, s.length()-1);
       if(s.equals("") || s.length() == 1){
           return true;
        }
       else if(start.equalsIgnoreCase(end)){
           return palindromeTester(s.substring(1, s.length() - 1));
        }
       else{
           return false;
        }
    }

3 个答案:

答案 0 :(得分:3)

哇噢!找到了!在第一个示例中,该方法在每次递归调用之后创建子字符串,无论字符串是否为空,为每个空字符串生成indexoutofbounds异常。通过在检查空字符串后创建子字符串,如果字符串为空,程序将不会创建子字符串。

旧:

String start = s.substring(0, 1);
String end = s.substring(s.length() - 2, s.length() - 1);
if (s.equals("") || s.length() == 1) {
    return true;
}

新:

if (s.equals("") || s.length() == 1) {
    return true;
}
String start = s.substring(0, 1);
String end = s.substring(s.length() - 1);

很自在地想出自己的东西。

答案 1 :(得分:2)

我在代码中发现了两件让它再次运行的东西:

public static boolean palindromeTester(String s) {
     s = justLetters(s); //calls a method that removes all spaces, punctuation
    String start = s.substring(0, 1);

    // here: the last character in a string is at position 
    // s.length() - 1, s.length()) 
    // and not 
    // s.length() - 2, s.length()-1
    String end = s.substring(s.length() - 1, s.length()); 

     // secondly you need to test if the string has only 2 characters left and if those two characters are the same
    if (s.isEmpty() || s.length() == 1 || (s.length()==2 && s.charAt(0)==s.charAt(1))) {
        return true;
    } else if (start.equalsIgnoreCase(end)) {
        System.out.println("returning "+s.substring(1, s.length() - 1));
        return palindromeTester(s.substring(1, s.length() - 1));
    } else {
        return false;
    }
}

我意识到递归锚点现在不同了,但是当你的输入字符串有不等数量的字符时,你的OutOfBounds被抛出。

修改

差点忘了:我还将equals("")更改为s.isEmpty()。使用isEmpty检查字符串是否为空。

答案 2 :(得分:2)

很高兴您自己发现了自己的错误(:

然而,你的解决方案有点......很久......你不这么认为吗?

例如你的行:

if(s.equals("") || s.length() == 1)

可以改写为:

if( s.length() < 2 )

为什么不缩短它? 例如(如果你更喜欢递归来做魔术)这些行解决了整个问题:

public boolean sampleMethod(String str)
{
    if(str.length() < 2)
    {
        return true;
    }
    return str.charAt(0) == str.charAt(str.length()-1) && sampleMethod(str.substring(1,str.length()-1));
}