To generate a random number within a specific range in Java, you can use the Random
class from the java.util
package and the nextInt()
method.
Here's an example of how to generate a random number within a specific range in Java:
// Create a Random object Random random = new Random(); // Generate a random integer between 10 and 20 (inclusive) int min = 10; int max = 20; int randomInt = random.nextInt(max - min + 1) + min;
In the above example, a Random
object is created using the default constructor. The nextInt()
method is used to generate a random integer between 0 and max - min
(inclusive), and the result is added to min
to get a random integer between min
and max
(inclusive).
For example, if min
is 10 and max
is 20, the randomInt
variable will contain a random integer between 10 and 20 (inclusive).
You can also use the nextInt()
method to generate a random integer within a specific range, by passing the minimum and maximum values as arguments:
// Generate a random integer between 10 and 20 (inclusive) int randomInt = random.nextInt(10, 20);
In this case, the nextInt()
method generates a random integer between 10 and 20 (inclusive).
For more information on generating random numbers in Java, you can refer to the documentation for the Random
class in the Java API.