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) means generating a random number between [0,max], and then taking the modulo (max-min+1).
Taking the random number generation [10,20] as an example, first generate a random number from 0-20, then take the modulo (20-10+1) to get a random number between [0-10], and then add min=10 , the final generated random number is 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;
In many places at work, you will encounter the need to obtain random numbers within a specified range. Directly using the functions in the API provided by Java is not enough, and some changes are needed.
Example: Generate 10 random numbers within the specified range.
public class RandomTest { public static void main(String[] args) { int max = 10; int min = 2; //Generate 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); }}