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

时间:2013-12-01 01:23:38

标签: java

所以我有一个名为ConsoleHangmanGame的对象,它只包含玩游戏和显示结果的方法。我在Hangman类中实例化了一个ConsoleHangman对象。 Hangman对象执行游戏的所有准备和处理。奇怪的是,我在playGame()内有ConsoleHangmanGame方法的while循环,但是当满足条件时它不会停止循环。

这是我的playGame方法

public boolean playGame()
{
    // Declaration
    String letter;
    int result = 0;
    boolean vali;

    // Statement
    try
    {
        hg.prepGame(); // call prepGame method

        do
        {
            displayWord();

            System.out.print("\nPlease enter a letter: ");
            letter = scan.next();
            letter = letter.toLowerCase();
            vali = letter.matches("[a-z]");

            if(vali == true)
            {
                result = hg.process(letter); // call process method
                displayResult(result);
            }
            else
            {
                System.out.println("Sorry, not a valid input.\n");
            }

        }
        while(result != 2 || result != -2); 
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
        System.out.println(e);
        return false;
    }

    return true;
}// end playGame method

变量result是从Hangman类获取process方法的返回值。

这是我的处理方法。

public int process(String letter)
{
    // Declaration
    int i;
    int stPos = 0;
    boolean found = false;
    String pS = this.ans;

    // Statement


/******* Some code here *******/

    if(found == false)
    {
        if(lifeLine == 0)
        {
            return gameOver; // no lives left
        }
        else
        {
            lifeLine--;
            return wrong; // wrong guess
        }
    }       
    else if(found == true && this.ans.compareTo(this.rightAns.toString()) == 0)
    {
            return complete; // complete game
    }
    else
    {
        return right; // right answer, but incomplete game
    }

}// end process method

这是否是我返回不使循环停止的值的方式?我的老师告诉我们使用public static final int作为回报。所以我在Hangman类声明了它们。

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

任何帮助将不胜感激,它尝试,调试,并看到当我赢得游戏时它确实返回值2,但它不会让我的循环停止。我会继续调试,希望有人可以分享他们的想法。感谢。

2 个答案:

答案 0 :(得分:3)

逻辑上,按De Morgan's law

result != 2 || result != -2

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

总是一个真实的表达。


条件应该是

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

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

result != complete && result != gameOver

(使用常量 - 虽然我更喜欢像GAMEOVER这样的大写符号 - 而不是魔术数字也使代码更容易阅读。)

答案 1 :(得分:1)

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

让我们暂时考虑一下。如果结果为2,则OR的右边部分为真(结果不等于-2)。如果结果为-2,那么OR的左侧为真(结果不等于2)。