天天看點

java 範圍内随機數 負數,如何獲得範圍内為負數的随機數?

java 範圍内随機數 負數,如何獲得範圍内為負數的随機數?

Consider the following code:

int rand = new Random().nextInt((30 - 20) + 1) + 20

It will return a random number between 30 and 20. However, I need its range to include negative numbers. How would I include negative numbers in the generation? I have tried using math that would be negative, but that resulted in an error. Simply subtracting or adding the negative numbers would not yield the desired value.

EDIT: Sorry, I am only half awake. The correct code is int rand = new Random().nextInt((30 - 20) + 1) + 20;.

解決方案

To get random number between a set range with min and max:

int number = random.nextInt(max - min) + min;

Also works with negative numbers

So:

random.nextInt(30 + 10) - 10;

// max = 30; min = -10;

Will yield a random int between -10 and 30.(exclusive)

Also works with doubles