Random Number Generator in Java
To generate a random number in Java, you can use the Random class provided by the java.util package. Here's a simple example to generate a random integer between 1 and 10, inclusive:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random(); // Create a Random object
int randomNum = rand.nextInt(10) + 1; // Generate a random number between 1 and 10
System.out.println("Random Number: " + randomNum);
}
}
In this code:
- Random rand = new Random(); creates a new instance of the Random class.
- rand.nextInt(10) generates a random integer between 0 (inclusive) and the specified value (10, exclusive), so it actually generates a number between 0 and 9.
- Adding 1 to the result (+ 1) shifts the range from 0–9 to 1–10, making the random number fall between 1 and 10, inclusive.
- System.out.println is used to print the random number to the console.