Pathlessodin
Pathlessodin

Reputation: 29

Having trouble checking an array

I'm supposed to search through a character array for another character array. The problem that I'm having is that I am supposed to check if the words match as well. Also, I keep getting an out of bounds exception when the search term is longer than the original string.

The charArray is the array of the search term. The indexArray is the char array of the original string.

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;
}

Upvotes: 0

Views: 76

Answers (1)

Dabiuteef
Dabiuteef

Reputation: 475

Say if the indexArray is "grape" and charArray is "pineapple". At i = 3, indexArray[i] == charArray[0] returns true. Now you set j = 3 and check until j < 9, and obviously indexArray[j] will give you an ArrayIndexOutOfBoundsException.

You should change it to:

// 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]) {
                // ...
            }
        }
    }
}

Upvotes: 1

Related Questions