2017-02-19 161 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; 
    } 
相关问题