gpt4 book ai didi

java - For 循环仅在第一次工作

转载 作者:行者123 更新时间:2023-12-01 14:19:48 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来在 Java 中的单词搜索中查找单词。我知道以前有人做过,但我还在学习,如果我自己做的话会更酷。无论如何,我发现用于扫描网格的主 for 循环仅针对我想要查找的第一个单词执行。这是我的代码中查找单词的部分:

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 对使用两个单独的值(尽管技术上我仍然这样做)。

无论如何,如果您能找到它,感谢您的帮助。

最佳答案

您需要在循环的每次迭代时重置whole_word_found

while (!word.equalsIgnoreCase("/exit")) {
// ...
whole_word_found = false;
for (int x = 0; !whole_word_found && x<grid.length; x++) {
// ...

关于java - For 循环仅在第一次工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17707393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com