Java数字猜测

时间:2019-06-07 18:10:37

标签: java

a。声明一个最终的int,并将值6分配为猜中的数字

    // b. create a Scanner to get user input

    // c. use a do {} while loop to prompt the user to enter an integer between 1 and 10,
    //    assign the user input to an int, and compare to the guessing number

    do{

    } while ();

    // d. if the number matches the guessed number,
    // print out a message that the number entered is correct.

我陷入了问题的do while循环部分

import java.util.Scanner;

public class Number {
    public static void main(String[] args) {
        int value = 6;
        int guess = 0;
        int num = 0;

        do {
            System.out.println("Please enter a number between 1 and 10: ");

            Scanner number = new Scanner(System.in);
            guess = number.nextInt();
        } while (num <= 10);

        if (guess == value);
        System.out.println("Congratulations you guessed the correct number!");
        if (guess != value);
        System.out.println("The number does not match.");
    }
}

这是我得到的结果。我不知道为什么它不会打印出消息,指出数字正确或数字不匹配。

Please enter a number between 1 and 10: 
4
Please enter a number between 1 and 10: 
5
Please enter a number between 1 and 10: 
6

3 个答案:

答案 0 :(得分:2)

if语句后的分号使它停止工作并且没有意义

if (guess == value);
                   ^ No no no

应该是

if (guess == value) {
    System.out.println("Congratulations you guessed the correct number!");

}

if (guess == value)
    System.out.println("Congratulations you guessed the correct number!");

您还应该增加numwhile毫无意义

答案 1 :(得分:2)

if声明后删除分号,我强烈建议您使用{}来包装所有语句。

或者,您应该在while循环内增加num,并在while循环内移动猜测部分。因此在每个循环中都会打印出正确的消息。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int value = 6;
        int guess = 0;
        int num = 0;


        do {
            System.out.println("Please enter a number between 1 and 10: ");

            Scanner number = new Scanner(System.in);
            guess = number.nextInt();
            num++;

            if (guess == value) {

                System.out.println("Congratulations you guessed the correct number!");
                break;
            }
            if (guess != value) {
                System.out.println("The number does not match.");
            }


        } while (num <= 10);

    }

}

答案 2 :(得分:1)

您的代码基本上如下所示:

ask user for a number from 1 to 10
and do this forever 

now check whether the number entered is the right guess

只要用户按照他的指示进行操作,您就会不断询问和询问。您再也不会“现在检查...”。

循环需要包含对正确猜测的检查,并且需要在正确猜测时终止。

(编辑)我稍微误读了原始代码,以为'num'是输入值。不,输入的数字称为“数字”。为了清楚起见,我建议将计数器重命名为“ guessCount”。当然,请记住在每次猜测时都要增加它。