我的程序工作,但不应该打印它应该

时间:2016-08-03 06:08:44

标签: java loops printing while-loop

我是java编程的新手,正在测试我学到的一些东西,以便做一个小猜谜游戏。它可以工作,你可以通过它,但在你得到第二个数字错误后,不会提示你告诉你这个数字是低还是高。以下是问题的一个示例:

Guess a number, 1 through 100: 
50
Guess higher! 
75
75
Guess lower! 
65
65
Guess lower! 

以下是代码:

public static void main(String[] args) {
    Random num = new Random();
    Scanner scan = new Scanner(System.in);
    int rand;
    boolean test;
    int rand2;
    int guess = 0;

    rand = num.nextInt(100);
    System.out.println("Guess a number, 1 through 100: ");
    while(test = true){
        rand2 = scan.nextInt();
        if(rand == rand2){
            guess++;
            if(guess < 19){
                System.out.println("Thats the correct number! And it only took: " + guess + " tries");
            }else{
                System.out.println("It took you: " + guess + " tries to guess the number!");
            }

        }else if(rand < rand2){
            System.out.println("Guess lower! ");
            guess++;
            rand2 = scan.nextInt();
        }else if(rand > rand2){
            System.out.println("Guess higher! ");
            guess++;
            rand2 = scan.nextInt();
        }
    }
}

3 个答案:

答案 0 :(得分:0)

如果阻止,请在其他地方删除rand2 = scan.nextInt();并尝试运行它。你的逻辑就像是从用户那里得到两次输入,直到你得到正确答案。

答案 1 :(得分:0)

在下次检查更低或更高之前,您正在扫描另一个数字两次。一旦在if else语句中,另一个在while循环的顶部。尝试删除if / else语句中的scan.nextInt()静态方法调用,它应该像你想要的那样工作。

while(test = true){
        rand2 = scan.nextInt();
        guess++;
        if(rand == rand2){

            if(guess < 19){
                System.out.println("Thats the correct number! And it only took: " + guess + " tries");
                break;
            }else{
                System.out.println("It took you: " + guess + " tries to guess the number!");
            }
        }else if(rand < rand2){
            System.out.println("Guess lower! ");
        }else if(rand > rand2){
            System.out.println("Guess higher! ");
        }
    }

答案 2 :(得分:0)

我已经为您更正了,请参阅以下内容:

public static void main(String[] args) {

        Random num = new Random();
        Scanner scan = new Scanner(System.in);
        boolean isOK = false;
        int counter = 0;

        int randNum = num.nextInt(100);
        while(true) {
            counter++;

            int n = scan.nextInt();
            if(n == randNum) {
                System.out.println("OK in " + counter + " times");
                isOK = true;
            } else if(n > randNum) {
                System.out.println("Lower");
            } else {
                System.out.println("Higher");
            }
        }
    }