同时执行条件不会停止循环 [英] do-while conditions don't stop the loop

查看:67
本文介绍了同时执行条件不会停止循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

变量结果正在从process方法获取返回值. 这是实现.

The variable result is getting the return value from the process method. 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;

推荐答案

从逻辑上讲,由迪摩根定律

result != 2 || result != -2

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

这始终是一个真实的表达式.

which is always a true expression.

条件可能应该是

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

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

which, when applying the same law as above, is

result != complete && result != gameOver

(使用常量-尽管我更喜欢像GAMEOVER这样的大写符号-代替魔术数字也使代码更易于阅读.)

(Using the constants - although I would prefer uppercase symbols like GAMEOVER - instead of the magic numbers also makes the code easier to read.)

这篇关于同时执行条件不会停止循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆