这是一个单词搜索程序。它搜索的文本是输入并转换为另一个类中的二维数组。Java:即使条件为假,也执行循环执行
这是程序通过搜索文本:
10 //rows
15 //columns
fqexfecmxdvjlgu
cxomfslieyitqtz
nucatfakuxofegk
hfytpnsdlhcorey
pgrhdqsypyscped
ckadhyudtioapje
yerjodxnqzztfmf
hypmmgoronkzhuo
hdskymmpkzokaao
amuewqvtmrlglad
因为即使我终止字符串end
键入某些原因,它总是进入我的checkDown()
方法,并创建一个出界失误。如果我注释掉这种方法,只执行checkRight()
和checkDiagonal()
方法,一切似乎都可以正常工作。 这是我的代码:
import java.util.Scanner;
public class WordSearch
{
private char[][] array;
private String targetWord;
private int rowLocation;
private int colLocation;
public WordSearch(char[][] inArray)
{
array = inArray;
}
public void play()
{
do{
for (int row = 0; row < array.length; row++)
{
for (int col = 0; col < array[row].length; col++)
{
System.out.print(array[row][col]);
}
System.out.println();
}
System.out.println();
Scanner input = new Scanner(System.in);
System.out.println("What word would you like to search for? Type end to quit: ");
targetWord = input.nextLine();
System.out.println("Typed in: " + targetWord);
System.out.println();
compareFirst(targetWord);
} while (!targetWord.equals("end"));
}
public void compareFirst(String inWord)
{
for (int row = 0; row < array.length; row++)
{
for (int col = 0; col < array[row].length; col++)
{
if(array[row][col] == inWord.charAt(0))
{
rowLocation = row;
colLocation = col;
suspectAnalysis();
}
}
}
}
public void suspectAnalysis()
{
checkRight();
checkDown();
checkDiagonal();
}
public void checkRight()
{
for(int i = 1; i < (targetWord.length()); i++)
{
if(colLocation + i > array[0].length - 1)
{
return;
}
else if(array[rowLocation][colLocation + i] != targetWord.charAt(i))
{
return;
}
}
System.out.println(targetWord + " found horizontally at row " + rowLocation + " and column " + colLocation);
System.out.println();
return;
}
public void checkDown()
{
for(int i = 1; i < (targetWord.length()); i++)
{
if(rowLocation + i > array.length - 1 && colLocation + i > array[0].length - 1)
{
return;
}
else if(array[rowLocation + i][colLocation] != targetWord.charAt(i))
{
return;
}
}
System.out.println(targetWord + " found vertically at row " + rowLocation + " and column " + colLocation);
System.out.println();
}
public void checkDiagonal()
{
for(int i = 1; i < (targetWord.length()); i++)
{
if(colLocation + i > array[0].length - 1 || rowLocation + i > array.length - 1)
{
return;
}
else if(array[rowLocation + i][colLocation + i] != targetWord.charAt(i))
{
return;
}
}
System.out.println(targetWord + " found diagonally at row " + rowLocation + " and column " + colLocation);
System.out.println();
}
}
为什么没有这种情况发生的时候我注释掉checkDown()
方法?我该如何解决它?
我很感激任何帮助。谢谢!
检查您获得索引超出绑定例外的语句。这种类型的异常不难理解和修复! –
@Bluasul你可以添加你用来测试你的WordSearch的代码吗,你的WordSearch构造函数的示例参数是什么? – alainlompo
你的问题就像知道'do ... while'循环总是在测试while表达式中的条件之前执行循环体一样简单吗?也就是说,你是否真的想要使用'while'循环(在决定是否执行循环体之前测试条件)? – dave