我是一个初学者,我想知道是否有人可以通过这个单词搜索告诉我这里做错了什么? 我坚持检查每一行在形式参数中指定的单词,目前它没有做任何类型的任何检查它的jst是一个基本的布尔方法,如果在数组的一行中找到一个单词,则返回true。假设单词搜索数组是矩形的
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;
}
答案 0 :(得分:2)
以下是您的代码更正
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;
}
但这不是检查的最佳方式,这里更顺畅,甚至更快(约5次,我会测试)代码
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;
}