为什么随机数总是0?

时间:2017-12-16 09:04:13

标签: java

这是一个简单的数字猜谜游戏。用户必须输入他们选择的数字。我尝试输入0 2到3次并且它正确。但它总是得到0作为随机数。什么可以解决这个问题?

class Main {

    static int random;
    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args) {
        int guessResult = 1;
        int randomGuess = 0;

        while (guessResult != -1) {
            System.out.println("Guess a number between 0 and 50 : ");

            randomGuess = userInput.nextInt();

            guessResult = checkGuess(randomGuess);
        }

        System.out.println("Yes the random number is " + randomGuess);
    }

    public static int getRandomNum() {
        random = (int) (Math.random() * 50);
        return random;

    }

    public static int checkGuess(int g) {
        if (g == random) {
            return -1;
        } else {
            return g;
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您没有调用getRandomNum方法。您尝试打印的值(randomGuess)是System.in的值。

答案 1 :(得分:0)

目前

static int random;

您的随机数未设置。

所以你需要打电话

Random rn = new Random();
random = rn.nextInt(51);

(随机的nextInt调用是独占的,所以你必须指望更多)

答案 2 :(得分:0)

public class Number_game 
{ 
static int random;
static Scanner userInput = new Scanner(System.in);

public static void main(String[] args)
{
    int guessResult = 1;
    int randomGuess = 0;

        System.out.println("Guess a number between 0 and 50 : ");
        randomGuess = userInput.nextInt();
        guessResult = checkGuess(randomGuess);
        System.out.println("The random number is "+guessResult );
}

public  static int checkGuess(int g)
{
    random = (int)(Math.random()*50);
    if(g==random)
    {
    return g;
    }
    else
    {
    return random;
    }
}  

}



Try This code