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:
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 (exclusive).
You can also use the nextDouble
method to generate a random double between two values. For example:
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).
I hope this helps! Let me know if you have any questions.