Appearance
Java Generate Random Number Between Two Given Values
To generate a random number between two given values in Java, you can use the nextInt method of the java.util.Random class. For example:
java
import java.util.Random;
public class Main {
public static void main(String[] args) {
int min = 10;
int max = 20;
// Generate a random number between min and max
Random r = new Random();
int randomNumber = r.nextInt((max - min) + 1) + min;
System.out.println("Random number: " + randomNumber);
}
}This will generate a random integer between 10 (inclusive) and 20 (inclusive). The nextInt(n) method returns a value from 0 to n-1, so adding (max - min) + 1 ensures the upper bound is included.
You can also use the nextDouble method to generate a random double between two values. For example:
java
import java.util.Random;
public class Main {
public static void main(String[] args) {
double min = 10.0;
double max = 20.0;
// Generate a random number between min and max
Random r = new Random();
double randomNumber = min + (max - min) * r.nextDouble();
System.out.println("Random number: " + randomNumber);
}
}This will generate a random double between 10.0 (inclusive) and 20.0 (exclusive).
For modern Java applications, ThreadLocalRandom is often preferred for its performance and simpler API: ThreadLocalRandom.current().nextInt(min, max + 1).