为什么这段代码会打印出无限量的“您的猜测是什么?”

时间:2018-06-25 08:19:26

标签: java netbeans

我正在尝试制作一个介于1到100之间的数字猜谜游戏。如果用户猜对了正确的数字,该程序将停止。

我当前的代码:

import java.util.Scanner;
import java.util.Random;

public class GuessingGame {
    public static void main(String[] args) {
        Random randomNumber = new Random();
        Scanner reader = new Scanner(System.in);
        System.out.println("What's your guess? ");
        int n = reader.nextInt();
        reader.close();

    int Number = randomNumber.nextInt(100 + 1);
    int guess = n;
     while (guess != Number) {
        System.out.println("What's your guess? ");
        new Scanner(System.in);
    }

    if (guess == Number) {
        System.out.println("Your have guessed the correct number! ");
    }

    else if (guess < Number) {
        System.out.println("Your number is too low! ");
    }

    else if (guess > Number) {
        System.out.println("Your number is too high! ");
    }
}   
}            

3 个答案:

答案 0 :(得分:1)

这是在IDE中使用格式化程序的地方。您将能够看到,循环后的if条件应该在循环内,并且您应该正在读取来自输入的猜测。

顺便说一句,除非明确不想再次读取任何内容,否则切勿关闭输入。

尝试

 Random randomNumber = new Random();
 Scanner reader = new Scanner(System.in);
 int number = randomNumber.nextInt(100 + 1);
 while(true) {
    System.out.println("What's your guess? ");
    int guess = reader.nextInt();

    if (guess == Number) {
        System.out.println("You have guessed the correct number! ");
        break; // no need to guess more

    } else if (guess < Number) {
        System.out.println("Your number is too low! ");

    } else if (guess > Number) {
        System.out.println("Your number is too high! ");
    }
}   

答案 1 :(得分:0)

将while循环更改为

while (guess != Number) {
    if (guess == Number) {
     System.out.println("Your have guessed the correct number! ");
     break;
    }

    else if (guess < Number) {
     System.out.println("Your number is too low! ");
    }

    else if (guess > Number) {
     System.out.println("Your number is too high! ");
    }

    System.out.println("Guess Again?");
    guess = reader.nextInt();
}

答案 2 :(得分:0)

while循环是无限循环。另外,您应该避免使用'Number'作为变量名,因为Java中有一个同名java.lang.Number的类。您还可以使用Scanner类的单个对象来使用任意数量的变量。因此,更简洁的代码如下所示:

while (guess != number) {
        System.out.println("What's your guess? ");
        guess = reader.nextInt();
    }

现在,如果您解决了上述问题,您的代码将永远不会进入两个else-if块,因为到while循环中断时,您的“猜测”将始终等于“ number”。我认为您要在这里实现的目标是:

while (guess != number) {
    System.out.println("What's your guess? ");
    guess = reader.nextInt();

    if (guess == number) {
        System.out.println("Your have guessed the correct number! ");
    }

    else if (guess < number) {
        System.out.println("Your number is too low! ");
    }

    else if (guess > number) {
        System.out.println("Your number is too high! ");
    }
}