2017-02-19 129 views
-1

美好的一天,如何生成-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 + "."); 
    } 



} 


} 
+2

'新的隨機()nextInt(2000) - 。1000' – Jameson

+0

'rand.nextInt((1000 - (-1000)+ 1)+( - 1000))'相同'rand.nextInt (1001)'。 –

回答

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

認爲paranthesis爲跨度隨機#可達到內部#的。因爲.nextInt上限是獨佔的,所以將1加到您的範圍內。然後,您想使用減法將該跨度從0到2000轉換爲-1000到1000。

+0

非常感謝你!你設法向我解釋得很好,現在一切正常。再次感謝! – Lunarixx

+0

沒問題。感謝您的貢獻並請接受我的回答(: –

+0

['nextInt(int bound)'](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int - )是* upper-exclusive *,因此'nextInt(2000)'返回一個介於0到1999 *之間的數字*(包含)*。要得到-1000到1000 *之間的數字(包含)*,您需要'rand.nextInt 2001) - 1000' – Andreas

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 
0

我用下面

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

而我得到的結果低於

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

真的嗎?我嘗試了很多次,並且從未得到過0以下的結果。 – Lunarixx

+0

是的,我想爲什麼它不適合你是因爲循環只有11 ..做一件事,循環運行100次,然後註釋掉其餘的代碼一分鐘。 我相信你會看到負數。如果有的話,就像我的回答。 – DNAj

+0

這不是他以上所說的。 '由')「)。 –

0

使用另一個隨機數來決定符號。

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