为什么我的do-while循环不起作用?

时间:2018-03-31 02:51:10

标签: java

当我编译时,尝试输入(y)再次播放我的操作 - 虽然不起作用,但它会让我脱离循环。 import java.util.Scanner;

public class HiLo {

    public static void main(String[] args) {
        // Creating a play again variable
        String playAgain = "";
        // Create Scanner object
        Scanner scan = new Scanner(System.in);
        // Create a random number for the user to guess
        int theNumber = (int)(Math.random() * 100 + 1);
        int guessNumber = 0;
        do
        {
            System.out.println("Guess a number between 1 - 100: ");
            while (guessNumber != theNumber) 
            {
                guessNumber = scan.nextInt();
                if (guessNumber > theNumber)
                {
                    System.out.println("Sorry, try again too high!");
                }
                else if (guessNumber < theNumber)
                {
                    System.out.println("Sorry, try again too low!");
                }
                else
                {
                    System.out.println("Congrats, you got it!");
                }
            }
            System.out.println("Would you like to play again (y/n)?");
            playAgain = scan.next();
        } while (playAgain.equalsIgnoreCase("y"));
        System.out.println("Thank you for playing! Goodbye.");
        scan.close();
    }

}

2 个答案:

答案 0 :(得分:0)

更改代码如下:(您只需更新循环内的变量)

public static void main(String[] args) {
    // Creating a play again variable
    String playAgain = "";
    // Create Scanner object
    Scanner scan = new Scanner(System.in);
    // Create a random number for the user to guess
    int theNumber = 0;
    int guessNumber = 0;
    do
    {
    // new lines to be added
    theNumber = (int)(Math.random() * 100 + 1);
    guessNumber = 0;
        System.out.println("Guess a number between 1 - 100: ");
        while (guessNumber != theNumber) 
        {
            guessNumber = scan.nextInt();
            if (guessNumber > theNumber)
            {
                System.out.println("Sorry, try again too high!");
            }
            else if (guessNumber < theNumber)
            {
                System.out.println("Sorry, try again too low!");
            }
            else
            {
                System.out.println("Congrats, you got it!");
            }
        }
        System.out.println("Would you like to play again (y/n)?");
        playAgain = scan.next();
    } while (playAgain.equalsIgnoreCase("y"));
    System.out.println("Thank you for playing! Goodbye.");
    scan.close();
}

这是在Jshell上执行代码:

enter image description here

答案 1 :(得分:0)

程序不工作的原因是因为do-while循环在到达“while”部分之前进行了一次迭代。在您的情况下,程序在用户正确猜出数字后成功完成循环。您的程序会中断,因为之后您要求用户输入“y”以便无休止地继续,而不会让他们猜出一个数字。如果他们猜数字,程序就会终止。