0

新手程序员在这里。我正在使用 Java 尝试创建一个猜数游戏。我希望我的 do while 循环继续循环,直到用户输入正确的数字或​​者他们用完了猜测。这就是我所拥有的,我无法弄清楚如何在我的一生中使用 2 个布尔控制器。

do
    {System.out.println("Enter guess #1");
    userGuess = keyboard.nextInt();

    } while ((userGuess != actualNumber) || (remainingGuesses = guesses;       remainingGuesses >= 1; remainingGuesses--)); 

任何帮助表示赞赏!

4

3 回答 3

2

我认为你想要更接近这种效果的东西:

remainingGuess = guesses;
do {
   System.out.println("Enter guess #1");
   userGuess = keyboard.nextInt();
} while ( userGuess != actualNumber || remainingGuesses-- > 0 )

逐行:

remainingGuesses = guesses;

分配guessesremainingGuesses 一次,如果你要在循环的每次迭代中都这样做,它永远不会结束

userGuess != actualNumber || remainingGuesses-- > 0 

在用户猜错 remainingGuesses大于时继续迭代0

remainingGuesses--

计算变量 的当前值remainingGuesses,然后在表达式之后将其减 1。

于 2013-09-30T16:57:37.213 回答
0

如果您希望这样做,而我会做一些小的更改,并假设您为诸如 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;
}

}

于 2014-06-09T18:09:59.993 回答
0

在进入循环之前初始化剩余的猜测。仅检查 while 括号“()”中的条件

reaminingGuesses = guesses;
do
    {System.out.println("Enter guess #1");
    userGuess = keyboard.nextInt();
    remainingGuess--;
    } while ((userGuess != actualNumber) || (remainingGuesses >= 1)); 
于 2013-09-30T16:58:54.967 回答