美好的一天,如何生成-1000到1000之间的随机数字?
我在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 + ".");
}
}
}
'新的随机()nextInt(2000) - 。1000' – Jameson
'rand.nextInt((1000 - (-1000)+ 1)+( - 1000))'相同'rand.nextInt (1001)'。 –