检查阵列时遇到问题

时间:2017-11-12 23:37:01

标签: java arrays string char indexoutofboundsexception

我应该在字符数组中搜索另一个字符数组。我遇到的问题是我应该检查单词是否匹配。此外,当搜索项长于原始字符串时,我不断收到越界异常。

charArray是搜索字词的数组。 indexArray是原始字符串的char数组。

public int indexOf(String parameter) { //does same thing as previous method but with a String instead
    int index = -1;
    char charArray[] = parameter.toCharArray();
    int counter = 0;

    for (int i = 0; i < indexArray.length; i++) { //goes through the array and find which array element is = to the char

        if (indexArray[i] == charArray[0]) { //checks if the index is equal to the first AND second letter of the word

            for (int j = i; j < charArray.length; j++) {
                if (indexArray[j] == charArray[j]) {// this is where the Exception java.lang.ArrayIndexOutOfBoundsException: 14 error happens
                    counter++;
                }

                if (counter == charArray.length) {
                    index = i;
                    return index;
                }

            }
        }


    }
    return index;
}

1 个答案:

答案 0 :(得分:1)

假设indexArray是“葡萄”而charArray是“菠萝”。在i = 3indexArray[i] == charArray[0]返回true。现在设置j = 3并检查j < 9,显然indexArray[j]将为您提供ArrayIndexOutOfBoundsException

您应将其更改为:

// There is no point to check indices that the subsequent string is shorter than the search string.
for (int i = 0; i < indexArray.length - charArray.length; i++) { 
    if (indexArray[i] == charArray[0]) {
        for (int j = 0; j < charArray.length; j++) {
            if (indexArray[i + j] == charArray[j]) {
                // ...
            }
        }
    }
}