Reputation: 13
Im a begginner and i was wondering if anyone could tell me what im doing wrong here with this word search ? im stuck on checking each row for a word specified in the formal argument, currently it doesnt do any checks of any sort its jst a basic boolean method which returns true if a word is found within a row of the array.assuming the word search array is rectangular
public boolean checkRow( char[][] puzzle, String w)
{
int counter = 0;
boolean match = true;
for ( int row = 0; row < puzzle.length; row++)
{
counter = 0;
for ( int col = 0; col < puzzle[row].length; col++)
{
if ( counter <= w.length() )
{
char word = puzzle[row][col];
if( w.charAt(counter) == word)
{
match = true;
counter++;
}
}
else if ((counter == w.length()) && (match == true))
{
return true;
}
else
{
match = false;
counter = 0;
}
}
}
return match;
}
Upvotes: 1
Views: 6767
Reputation: 4843
Here is your code corrected
public boolean checkRow(char[][] puzzle, String w) {
int counter = 0;
boolean match = true;
for (int row = 0; row < puzzle.length; row++) {
counter = 0;
match = false;
for (int col = 0; col < puzzle[row].length; col++) {
if (counter < w.length()) {
char word = puzzle[row][col];
if (w.charAt(counter) == word) {
match = true;
counter++;
} else {
match = false;
counter = 0;
}
if ((counter == w.length()) && (match == true)) {
return true;
}
}
}
}
return false;
}
but this is not the best way how to do your check, here is much smoother and even faster (about 5 times, i'd test it) code
public boolean checkRow2(char[][] puzzle, String w) {
String rowStr = null;
for(int row = 0; row < puzzle.length; row++) {
rowStr = new String(puzzle[row]);
if(rowStr.contains(w)) return true;
}
return false;
}
Upvotes: 2