How do I generate a range of random Numbers in Java
- 2020-04-01 02:17:02
- OfStack
To generate a random integer between [min, Max],
package edu.sjtu.erplab.io;
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
int max=20;
int min=10;
Random random = new Random();
int s = random.nextInt(max)%(max-min+1) + min;
System.out.println(s);
}
}
Random. NextInt (Max) represents generating random Numbers between [0, Max], and then taking the modulus of (max-min+1).
Take the generation of [10,20] random Numbers as an example, first generate a random number of 0-20, and then take the modulus of (20-10+1) to get the random number between [0-10], then add min=10, and finally generate a random number of 10-20
Generate random Numbers between 0 and 2, including 2
Random rand = new Random();
int randNum = rand.nextInt(3);
Generate random Numbers between 5 and 26, including 26
int randNum = rand.nextInt(22)+5;
Many places in the workplace will encounter a need to get a random number within a specified range. The function in the API that directly utilizes Java to give cannot satisfy, need to make some change.
Example: generates 10 random Numbers in a specified range.
public class RandomTest {
public static void main(String[] args) {
int max = 10;
int min = 2;
//Generates 10 random Numbers in the specified range
Random random = new Random();
for(int i=0; i<10; i++){
int n = random.nextInt(max-min+1)+min;
System.out.print(n+" ");
}
System.out.println();
for(int i=0; i<10; i++){
int n = (int)(Math.random()*(max-min+1)+min);
System.out.print(n+" ");
}
}
}
To generate a random integer between [min, Max]
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
int min=10;
int max=20;
Random random = new Random();
//int s = random.nextInt(max)%(max-min+1) + min;
int s = random.nextInt(max-min+1) + min;
System.out.println(s);
}
}