How to specify the range for random in Java?
In Java, you can use the Random class to generate random numbers. To specify a range, you can use the nextInt method along with calculations for the range.
Here is an example code that generates a random number within a specified range:
import java.util.Random;
public class RandomRangeExample {
public static void main(String[] args) {
Random rand = new Random();
// 指定范围为1到100
int min = 1;
int max = 100;
int randomNumber = rand.nextInt(max - min + 1) + min;
System.out.println("随机数: " + randomNumber);
}
}
In this example, we are using nextInt(max – min + 1) + min to generate a random number between 1 and 100. The random number generated by nextInt(max – min + 1) falls between 0 and 99, and adding the offset of min gives us the random number within the specified range.