15

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;.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CaffeineToCode
  • 830
  • 3
  • 13
  • 25

4 Answers4

32

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
EDToaster
  • 3,160
  • 3
  • 16
  • 25
15

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KennyC
  • 921
  • 7
  • 16
1

Okay. First, try to only create the Random instance once, but for an example,

int rand = -15 + new Random().nextInt(31);

is the range -15 to 15.

The Random.nextInt(int) JavaDoc says (in part) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive). Note that your provided example of (30 - 20) + 1 is the range 0 to 10 (inclusive).

As a further example, to get the range 20 to 30 you would use:

int rand = 20 + new Random().nextInt(11);

Remember, the bounds of the result of is 0 to n.

30 - -10. I'm trying to make a survival simulator. That will be my temperature.

Ok. Let's write that range as -10 to 30. nextInt(n) will return a value between 0 and n, so if you want the range below 0 you must subtract 10 from the result and add 10 to the n. That's

Random random = new Random();
int rand = random.nextInt(41) - 10;

Now let's examine how we can determine those numbers. Remember, nextInt() will return between 0 and n (exclusive) and we want -10 to 30 (inclusive); so 41 is n and we subtract 10. If the result is 0 (the min) we get -10, if the result is 40 (the max) we get 30.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0
int randomNumber=(random.nextInt(DOUBLE_MAX)-MAX);

Alternatively, create a random positive or negative 1 and multiply it.

jnd
  • 754
  • 9
  • 20