Reputation: 21
I am trying to pass a word to my findWord
method which checks a 2d array of stype String[][] "a" for said word. Row and column are the dimensions of "a". I am not checking diagonal or reverse, only forwards. I believe that nearly if not all of my logic is correct, but I think I'm getting a bounds error. No error is being thrown, but the code just isn't working properly by returning false in random cases that it should return true. Code compiles and runs fine. (i.e it checking past the amount of columns that exist).
public boolean findWord(String word) {
int cL = column;
for(int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
if(a[i][j].equals(word.substring(0,1))) {
int c = 1;
int parameter = j + word.length();
if(parameter <= cL) {
for(int k = j; k < parameter; k++) {
if(!a[i][k].equals(word.substring(c,c+1)))
return false;
c++;
}
return true;
}
} else {
return false;
}
}
}
return true;
}
Upvotes: 0
Views: 67
Reputation: 86296
I have run a few test cases. I have not yet found a case where your method returns true
despite the word being in the array.
The flaws I have seen in your code are:
You start looking in a[0][0]
. If the string found here isn’t equal to the first letter of your word, you immediately return false
without looking any further.
Say that the first letter of the word does match a[0][0]
. Now you set c
to 1, but since i
and k
are 0, you now compare the second letter of the word to a[0][0]
. That is unlikely to match. It only does of the word begins with the same letter twice.
Finally, I did manage to get a StringIndexOutOfBoundsException
, namely by searching for aa
in a row containing a
, b
, c
. Second time through the innermost loop c
is 2, and you therefore try to take out the substring between indices 2 and 3 of a word that has length 2.
You’ve got some fixing to do. Enjoy your work.
Upvotes: 1