java random number in range from negative code example
Example 1: How to add negative random numbers in java
//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.
Example 2: random number in range java
(int)(Math.random() * ((max - min) + 1)) + min
Copy