2个字符串

时间:2015-06-13 14:58:35

标签: java string exception

我在Java中使用这个小程序时遇到问题,检查2个字符串是不是字谜。

我得到StringIndexOutOfBoundsException

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
    at java.lang.String.charAt(Unknown Source)
    at AreAnagrams.areAnagrams(AreAnagrams.java:9)
    at AreAnagrams.main(AreAnagrams.java:30)

这是我的代码:

public class AreAnagrams {
    public static boolean areAnagrams(String a, String b) {
        int j = 0;
        int i = 0;
        if (a.length() == b.length()) {
            while (i < a.length()) {
                if (a.charAt(i) == b.charAt(j)) {
                    j++;
                    i = 0;
                } else {
                    i++;
                    if (j > a.length()) {
                        return false;
                    }
                }
            }
        } else {
            return false;
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("momdad", "dadmom"));
    }
}

2 个答案:

答案 0 :(得分:2)

当您引用超出字符串长度的字符索引时,会发生

java.lang.StringIndexOutOfBoundsException

例如字符串&#34; dadmom&#34; - 当您调用charAt(6)时,它会抛出此异常,因为字符索引在范围内0 5

您可以使用以下代码识别字谜:

public static boolean areAnagrams(String a, String b) {
     char[] aChars = a.replaceAll("\\s", "").toCharArray();
     char[] bChars = b.replaceAll("\\s", "").toCharArray();
     Arrays.sort(aChars);
     Arrays.sort(bChars);
     System.out.println(aChars);
     System.out.println(bChars);

     return Arrays.equals(aChars, bChars);
}

public static void main(String[] args) {
     System.out.println(areAnagrams("momdad", "dadmom"));
}

答案 1 :(得分:1)

我觉得你这里有编程逻辑错误。对于字谜,标准应该是从第一个字符串的左到右开始,字符应该对于从右到左的第二个字符串相等。

我的代码中没有找到任何此类内容。我觉得你应该在if if ( a.length() == b.length())中尝试以下内容:

int length = a.length();
for(int i = 0; i < length; i++){
    if(a.charAt(i) != b.charAt(length-i-1)){
        return false;
    }
}
return true;

您还应该删除代码中ij变量的声明。

<强>校正

我真的对anagram和回文混淆了。对于回文,上述答案是正确的。我正在补充我为anagram工作的答案。

我建议您通过更改方法areAnagrams来递归检查字符串,如下所示:

public static boolean areAnagrams(String a, String b) {

//If the length of strings is unequal then return false.
    if(a.length() != b.length()){
        return false;
    } 

//Else if the length of strings equals 1 return the equality of the two strings
    if(a.length() == 1){
        return a.equals(b);
    }

//Else replace the first occurrence of the first character 
//of variable `a` with blank string in string variable b. 
//Here if the character is not present in string b then the
//variable b remains unchanged and the length of b would be 
//greater than that of variable `a` in the next recursion.
    b = b.replaceFirst(a.substring(0, 1), "");

//remove the first character in string `a`
    a = a.substring(1, a.length());

//make the recursive call
    return areAnagrams(a, b);
}