To generate random integers within a specific range in Java, you can use the nextInt
method of the Random
class. Here’s an example of how you can do this:
int min = 10; int max = 20; Random random = new Random(); int randomInt = random.nextInt((max - min) + 1) + min;
This generates a random integer between min
and max
, inclusive. The nextInt
method returns a random integer between 0
and the specified value (in this case, (max - min)
), so we add min
to the result to get the desired range.
For example, if min
is 10
and max
is 20
, this will generate a random integer between 10
and 20
, inclusive.