如果您希望这样做,而我会做一些小的更改,并假设您为诸如 actualNumber 和允许猜测的总数定义了常量:
// 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==actual number 分解为一个方法,但在这种情况下可能不需要它,因为它是一个简单的相等检查。
可以shouldStop
通过多种方式定义方法,但是...
早期我认为将这些逻辑块完全写出来并从那里浓缩是有帮助的,例如:
public boolean shouldStop(int guess) {
if(remainingGuesses <=0) {
return true;
} else if(guess == actualNumber) {
return true;
} else {
return false;
}
}