我正在尝试制作一个程序,用Java搜索单词搜索中的单词。我知道它之前已经完成了,但我还在学习,如果我自己做的话会更酷。无论如何,我发现扫描网格的主要循环只执行我想要找到的第一个单词。这是我的代码中找到单词的部分:
while (!word.equalsIgnoreCase("/exit")) {
{ //Find word
Pair cursor = new Pair();
Pair direction = new Pair();
Pair location = new Pair();
for (int x = 0; !whole_word_found && x<grid.length; x++) { int y = 0;
for (y = 0; !whole_word_found && y<grid[x].length; y++) {
cursor = new Pair(x,y);
//Lots of word-finding code, including writing whole_word_found and using the three pairs listed above
}
}
//Print location of word
if (word.length() != 1) {
if (whole_word_found) {
System.out.printf("The word is located at %s going %s.%n",location.toString(0),direction.toString(0));
} else {
System.out.println("Sorry, word not found.");
}
}
} //Find word
//Get next word
System.out.println("Enter another word, or type \"/exit\" to exit.");
input = new Scanner(System.in);
word = input.nextLine().replaceAll(" ","");
}
所有变量都已正确初始化,而Pair是我用来保存有序对(x,y)值的类。我只是不喜欢为我必须做的每个x-y对都有两个单独的值(虽然我在技术上仍然这样做。)
无论如何,如果你能找到它,谢谢你的帮助。
答案 0 :(得分:1)
您需要在循环的每次迭代中重置whole_word_found
。
while (!word.equalsIgnoreCase("/exit")) {
// ...
whole_word_found = false;
for (int x = 0; !whole_word_found && x<grid.length; x++) {
// ...