如果你想把它當作一個做,而我會做一些小的改動,並假設你有東西像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;
}
如果你真的想追隨整個事情的經過,你可以打破猜測==實際人數進入的方法爲好,但它可能不是因爲它的簡單的等同性檢查這種情況下需要。
的methos shouldStop
可以定義一些但方式...
早期我認爲這是有幫助的出完全寫這些邏輯塊,並從那裏凝結,例如:
public boolean shouldStop(int guess) {
if(remainingGuesses <=0) {
return true;
} else if(guess == actualNumber) {
return true;
} else {
return false;
}
}
看起來像一個for-loop會更合適。 – Dukeling