如何更新此方法,它允许用户只猜测5次?

时间:2013-12-02 11:48:19

标签: java counter do-while

是一个带有递增计数器的do..while循环,你怎么只允许用户猜5次?尝试这样做,但似乎没有工作...

或者for循环是最好的方法吗?

public static void guessRandomNumber() {

        // declare var for user guess and default to zero
        int userGuess = 0;
        // declare boolean relating to if number is valid
        boolean validNumber = false;
        // declare boolean relating to if guess is correct
        boolean correctGuess = false;
        // declaring int equal to return value from generateRandomNumber();
        int secretNumber = generateRandomNumber();

        //Do while loop that runs until user guesses correctly
        do {

            //Do while loop that runs until a valid entry is given (i.e. an integer)
            do {

                try {
                    //do while loop ensuring that user guess is between 1 and 10
                    do {

                        // Get user guess (between 1 and 10)
                        System.out.println("Please enter a number between 1 and 10...");
                        userGuess = scanner.nextInt();

                        if (userGuess < 1 || userGuess > 10) {
                            validNumber = false;
                            System.out.println("Please Ensure number is between 1 and 10");
                        }else {
                            validNumber=true;
                        }
                    } while (!validNumber);
                } catch (Exception ex) {
                    //Print error message
                    System.out.println("Sorry invalid entry...");
                    // Flush scanner
                    scanner.next();
                    validNumber = false;
                }
            } while (!validNumber);

            //If else statement that outputs a message informing user if guess correct
            if (userGuess == secretNumber) {

                System.out.println("Guess correct, well done!");
                correctGuess = true;

            } else {

                System.out.println("Sorry guess Incorrect please try again!");
                correctGuess = false;

            }

        } while (!correctGuess);

    }// end ofGuessRandomNumber

3 个答案:

答案 0 :(得分:2)

只需添加一个计数器numberOfGuesses并像这样更改while循环:

do {
   // do stuff and increment numberOfGuesses

} while (!correctGuess && numberOfGuesses < 5);

此外,我不明白为什么你需要3个while循环来执行此任务。一个就够了,你可以在一个中检查所有条件。

答案 1 :(得分:0)

您可以按如下方式使用计数器,然后您可以继续使用5并在此之后休息。

int counter=1;

while(counter<=5){ // while loop will runs 5 times.
  // do your task
  counter++; // up your counter value.

}

你可以从中得到一些想法。

答案 2 :(得分:0)

有一个计数器,你在每个validNumber递减,并在外循环中检查这是非零。