How do I generate random integers within a specific range in Java?
To generate a random integer within a specific range in Java, you can use the nextInt method of the Random class. This method returns a random integer from the Random object's sequence within the range specified by its arguments.
Here's an example of how you can use the nextInt method to generate a random integer between a lower and upper bound:
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Create a new Random object
Random random = new Random();
// Generate a random integer between 1 and 10
int randomInt = random.nextInt(10) + 1;
System.out.println("Random integer: " + randomInt);
}
}In this example, the nextInt method is called with an argument of 10, which specifies that the random integer should be generated from the range [0, 9]. The returned integer is then increased by 1, so that it is within the range [1, 10].
Note that the Random class uses a seed value to generate a sequence of random numbers, so if you want to generate a new sequence of random numbers, you should create a new Random object.