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.
Sorry, I am only half awake. The correct code is int rand = new Random().nextInt((30 - 20) + 1) + 20;
.
Randomize negative integer numbers The formula =RANDBETWEEN(X,Y) also can insert negative integer numbers. (X and Y indicate any negative numbers, and X<Y), here, I type =RANDBETWEEN(-120,-20) into a blank cell and press Enter key, then if you need, you can drag the fill handle to fill a range.
No. Because the range formula subtracts the lowest number from the highest number, the range is always zero or a positive number.
The correct code is int rand = new Random(). nextInt((30 - 20) + 1) + 20; .
To get a random number between a set range with min
and max
:
int number = random.nextInt(max - min) + min;
It 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).
It also works with doubles.
You can use Random.nextBoolean() to determine if it's a random positive or negative integer.
int MAX = 30;
Random random = new Random(); // Optionally, you can specify a seed, e.g. timestamp.
int rand = random.nextInt(MAX) * (random .nextBoolean() ? -1 : 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With