美好的一天,如何生成-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)'。 –