简体   繁体   English

同时执行条件不会停止循环

[英]do-while conditions don't stop the loop

I've programmed a Hangman game containing a do-while loop to keep asking the user for letters until they either solved the word or ran out of lives. 我已经编写了一个包含do-while循环的Hangman游戏,以不断询问用户字母,直到他们解决单词或耗尽生命为止。 The weird thing is that the loop doesn't stop when the conditions are met. 奇怪的是,当满足条件时循环不会停止。

Here's the implementation of the game logic containing the loop: 这是包含循环的游戏逻辑的实现:

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); 

The variable result is getting the return value from the process method. 可变结果是从process方法获取返回值。 Here's the implementation. 这是实现。

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
    }
}

Could it be the way how I'm returning the values that's causing the loop to keep looping? 难道是我返回导致循环不断循环的值的方式吗? I've declared these values like this: 我已经声明了这些值,如下所示:

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

Logically, by De Morgan's law , 逻辑上,根据德摩根定律

result != 2 || result != -2

is the same as 是相同的

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

which is always a true expression. 这永远是一个真实的表达。


The condition should probably be 条件可能应该是

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

which, when applying the same law as above, is 当应用与上述相同的法律时,

result != complete && result != gameOver

(Using the constants - although I would prefer uppercase symbols like GAMEOVER - instead of the magic numbers also makes the code easier to read.) (使用常量-尽管我更喜欢像GAMEOVER这样的大写字母-代替魔术数字也使代码更易于阅读。)

 while(result != 2 || result != -2); 

Lets think about this for a second. 让我们考虑一下。 If the result is 2 then the right part of the OR is true (result is not equal to -2). 如果结果为2,则OR的右边为true(结果不等于-2)。 And if the result is -2 then the left side of the OR is true (result is not equal to 2). 如果结果为-2,则OR的左侧为true(结果不等于2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM