gpt4 book ai didi

java - do-while 条件不会停止循环

转载 作者:行者123 更新时间:2023-12-01 08:07:32 25 4
gpt4 key购买 nike

我编写了一个 Hangman 游戏,其中包含一个 do-while 循环,不断向用户询问字母,直到他们解出单词或耗尽生命。奇怪的是,当条件满足时循环不会停止。

这是包含循环的游戏逻辑的实现:

String letter;
int result = 0;

do {
displayWord();

System.out.println("Please enter a letter: ");
letter = scan.next().toLowerCase();

if (letter.matches("[a-z]")) {
result = hg.process(letter);
displayResult(result);
} else {
System.out.println("Sorry, not a valid input.");
}
}
while(result != 2 || result != -2);

变量 result 正在从 process 方法获取返回值。这是实现。

public int process(String letter) {
boolean found = false;

//... some code here

if(!found) {
if(lifeLine == 0) {
return gameOver; // no lives left
} else {
lifeLine--;
return wrong; // wrong guess
}
} else if (found && this.answer.equals(this.rightAnswer)) {
return complete; // complete game
} else {
return right; // right answer, but incomplete game
}
}

是否是我返回值的方式导致循环继续循环?我已经这样声明了这些值:

public static final int right = 1;
public static final int wrong = -1;
public static final int complete = 2;
public static final int gameOver = -2;

最佳答案

从逻辑上讲,作者De Morgan's law ,

result != 2 || result != -2

相同
!(result == 2 && result == -2)

这始终是一个真实的表达。

<小时/>

条件大概应该是

!(result == complete || result == gameOver)

当应用与上述相同的定律时,是

result != complete && result != gameOver

(使用常量 - 尽管我更喜欢像 GAMEOVER 这样的大写符号 - 而不是魔数(Magic Number)也使代码更易于阅读。)

关于java - do-while 条件不会停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307689/

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