新手程序员在这里。我正在使用Java来尝试创建一个数字猜谜游戏。我希望我的do while循环继续循环,直到用户输入正确的数字或者他们用完了猜测。这就是我所拥有的,我无法弄清楚如何在我的生命中使用2个布尔控制器。
do
{System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
} while ((userGuess != actualNumber) || (remainingGuesses = guesses; remainingGuesses >= 1; remainingGuesses--));
感谢任何帮助!
答案 0 :(得分:2)
我认为你想要更接近这种效果:
remainingGuess = guesses;
do {
System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
} while ( userGuess != actualNumber || remainingGuesses-- > 0 )
逐行:
remainingGuesses = guesses;
将guesses
分配给remainingGuesses
一次,如果您在循环的每次迭代中都这样做,它就永远不会结束
userGuess != actualNumber || remainingGuesses-- > 0
在用户猜错时继续进行迭代或 remainingGuesses
超过0
。
remainingGuesses--
计算变量remainingGuesses
的当前值,然后在表达式递减1之后。
答案 1 :(得分:0)
在进入循环之前初始化剩余的猜测。仅检查while“paranthesis”()中的条件
reaminingGuesses = guesses;
do
{System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
remainingGuess--;
} while ((userGuess != actualNumber) || (remainingGuesses >= 1));
答案 2 :(得分:0)
如果你想要它,我会做一些小的改动,并假设你有像regularNumber和允许的猜测总数定义的常量:
// break the calls into seperate methods, to make them easier to read in the long term and to
// seperate logical concerns into discrete elements.
do {
// get the user guess
guess = getGuess();
// if shouldStop returns true you would stop, if it returns false you should continue, thus the !..
} while (!shouldStop(guess)) {
// decrement the guesses.
--remainingGuesses;
}
/// define these methods somewhere..,
// get your guess
public int getGuess() {
System.out.println("Enter guess #1");
return keyboard.nextInt();
}
public boolean shouldStop(int guess) {
// condensed if statement syntax in java, very handy for this kind of thing
// do we have enough remaining guess to keep going? If so, compare the guess to the actual number
// otherwise return true (the stop signal
return remainingGuesses > 0 ? guess == actualNumber : true;
}
如果你真的想要完成整个过程,你可以将guess ==实际数字分解为一个方法,但在这种情况下可能不需要它,因为它是一个简单的相等检查。
可以通过多种方式定义方法shouldStop
......
在早期,我认为完全编写这些逻辑块并从那里压缩是有帮助的,例如:
public boolean shouldStop(int guess) {
if(remainingGuesses <=0) {
return true;
} else if(guess == actualNumber) {
return true;
} else {
return false;
}
}