如何生成-1000到1000之间的随机数?

时间:2017-02-19 08:28:31

标签: java

美好的一天,

我正在编写java中的“猜数字”游戏,我正在尝试让程序生成-1000到1000之间的数字但由于某种原因,它现在只生成1以上的数字。

我到底做错了什么? 有人可以帮帮我吗?

    Random rand = new Random();
    int numberToGuess = rand.nextInt((1000 - (-1000) + 1) + (-1000));
    int numberOfTries = 0;
    Scanner input = new Scanner(System.in);
    int guess;
    boolean win = false;

    System.out.println("Lets begin.");

    while (win == false && numberOfTries < 11) {

        System.out.println("Insert a number:");
        guess = input.nextInt();
        numberOfTries++;


        if (guess == numberToGuess) {
            win = true;
        }

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

        else if (guess > numberToGuess) {
        System.out.println("Your guess it too high.");
        }


    }

    if (win == true)
    System.out.println("You won with " + numberOfTries + " attempts. The hidden number was " + numberToGuess + ".");

    else if (numberOfTries == 11) {
        System.out.println("You lost. The number was " + numberToGuess + ".");
    }



}


}

4 个答案:

答案 0 :(得分:2)

int numberToGuess = rand.nextInt(2001) -1000;

将paranthesis中的#视为随机#可以达到的范围。在你的范围中加1,因为.nextInt上限是独占的。然后,您希望使用减法将该范围从0转换为2000到-1000到1000。

答案 1 :(得分:0)

   int numberToGuess = rand.nextInt((1000 - (-1000) + 1) + (-1000));

你有1000和-1000所以它将为零,使用rand.nextInt()

        rand.nextInt(2001) -1000;

使用Math.random()

       (int)(Math.random() *2001 +1) - 1001

答案 2 :(得分:0)

我正在使用

int numberToGuess  = rand.nextInt((1000 - (-1000)) + 1) + (-1000);

我的结果低于结果

-727
-971
-339
84
295
498
....

答案 3 :(得分:0)

使用另一个随机数来决定标志。

    int numberToGuess = rand.nextInt(1001);
    int sign = rand.nextInt(2);
    if(sign==0){
        numberToGuess*=-1;
    }