需要我的循环不仅在三次猜测后结束,而且显示正确的数字

e4eetjau  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(251)

我试着让我的循环只出现三次。因此,如果用户在第三次猜测之后没有猜到正确的数字,那么循环就结束了,我已经猜到了,但它不会显示数字是什么。我需要的数字显示后,第三次猜测,但不知道为什么它没有显示正确的数字。

import java.util.Scanner;

public class GuessNumberDoWhileA {
public static void main(String[] args) {

    //Generate random number from 1-10
    int number = (int) (Math.random()*9 + 1);
    int count = 0;
    //Auto Generated Method stub
    Scanner Input = new Scanner(System.in);

    //Tell the user to guess a number
    System.out.println("Guess a number between 1 and 10");

    //int guess = -1;

    //while (guess != number) {
      while (count < 3) {   
        count++;

        System.out.print("\nEnter your guess: ");
        int guess = Input.nextInt();

        if (guess == number)
            System.out.println("Correct the number was " + number);
        else if (guess > number)
            System.out.println("Your guess is to high try again!");
        else if (guess < number)
            System.out.println("Your guess is to low try again!");
        else 
            System.out.println("The correct number is " + number);
    }
            System.out.println("The number was " + number);

}

}

hrysbysz

hrysbysz1#

你需要一个 boolean 变量,可用于检查用户是否能够正确猜出数字。此布尔变量的初始值应为 false .
你不需要最后一个 else 循环中的语句。如果用户猜对了数字,请设置 boolean 变量到 true 打破循环。循环后,检查 boolean 变量为 false 不管怎样。如果是的话 false ,这意味着用户无法猜出数字,因此请向用户显示正确的数字。
如果用户能够猜出数字,那么第一个 if 循环中的语句将在控制台上打印正确的数字并中断循环。它还将布尔变量设置为 true ,所以正确的号码只会在控制台上打印一次。

boolean guessed = false;

while (count < 3) {   
    count++;

    System.out.print("\nEnter your guess: ");
    int guess = Input.nextInt();

    if (guess == number) {
        System.out.println("Correct the number was " + number);
        guessed = true;
        break;
    }
    else if (guess > number)
        System.out.println("Your guess is to high try again!");
    else if (guess < number)
        System.out.println("Your guess is to low try again!");
}

if (!guessed) System.out.println("Number was: " + number);

相关问题