do-while条件不会停止循环Java
所以我有一个名为ConsoleHangmanGame
的对象, ConsoleHangmanGame
包含玩游戏和显示结果的方法。 我在ConsoleHangman
类中实例化了一个Hangman
对象。 Hangman
对象执行游戏的所有准备和处理。 奇怪的是我在ConsoleHangmanGame
有一个while循环用于playGame()
方法,但是当条件满足时它不会停止循环。
这是我的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("[az]"); 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,但它不会让我的循环停止。 我将继续调试,希望有人可以分享他们的想法。 谢谢。
逻辑上,根据德摩根定律 ,
result != 2 || result != -2
是相同的
!(result == 2 && result == -2)
这总是一个真实的表达。
条件应该是
!(result == complete || result == gameOver)
在应用上述相同法律时,是
result != complete && result != gameOver
(使用常量 – 虽然我更喜欢像GAMEOVER这样的大写符号 – 而不是魔术数字也使代码更容易阅读。)
while(result != 2 || result != -2);
让我们暂时考虑一下。 如果结果为2,那么OR的右边部分为真(结果不等于-2)。 如果结果是-2,则OR的左侧为真(结果不等于2)。