How do I generate random integers within a specific range in Java?

 

To generate random integers within a specific range in Java, you can use the java.util.Random class. Here's an example of how you can do it:

java
import java.util.Random; public class RandomIntegersExample { public static void main(String[] args) { int min = 1; int max = 10; Random random = new Random(); // Generate a random integer between min (inclusive) and max (exclusive) int randomNumber = random.nextInt(max - min) + min; System.out.println("Random Number: " + randomNumber); } }

In this example, the nextInt method of the Random class is used to generate a random integer within the specified range [min, max). The nextInt(max - min) generates a random integer between 0 (inclusive) and max - min (exclusive), and then we add min to shift the range to [min, max).

By changing the values of min and max, you can generate random integers within different ranges.

Comments