如何生成一个随机数并让用户猜测一个数字是偶数还是奇数,直到它们正确为止?

时间:2018-02-03 12:50:36

标签: java loops if-statement random while-loop

int userInput;

Random randomNumbers = new Random();

numberOne = randomNumbers.nextInt(100);

System.out.print("Enter 0 for even or 1 for odd: ");
userInput = keyboard.nextInt();
label:
while (userInput == 0)
{
    if (userInput % 2 == 0)
        if (numberOne % 2 == 0)
        {
            System.out.println("Congratulations!");
            userInput--;
        }
}
while (userInput == 1)
{
    if (userInput % 2 != 0)
        if (numberOne % 2 != 0)
        {
            System.out.println("Congratulations!");
            userInput--;
        }
}

当输入等于它表示祝贺的数字时,但当输入不正确时,它不会要求用户提供另一个号码。

1 个答案:

答案 0 :(得分:0)

这也可以。

    Random randomNumbers = new Random();
    int numberOne = randomNumbers.nextInt(100);

    Scanner keyboard = new Scanner(System.in);
    int userInput;

    do {
        // You can generate a new number if you want.
        // numberOne = randomNumbers.nextInt(100);
        System.out.println("Enter 0 for even or 1 for odd: ");
        userInput = keyboard.nextInt();
    } while((numberOne % 2) != (userInput % 2));

    System.out.println("Congratulations!");