Question:
Write a Java program that uses the Random class to generate a random number between 1 and 10 (inclusive) and displays it on the console.
Answer:
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
Random random = new Random();
int randomNumber = random.nextInt(10) + 1;
System.out.println("Random number between 1 and 10 (inclusive): " + randomNumber);
}
}
Step-by-Step Explanation:
Random
class from the java.util
package:import java.util.Random;
RandomNumberGenerator
:public class RandomNumberGenerator {
main
method, create an instance of the Random
class: Random random = new Random();
nextInt()
method of the Random
class to generate a random number between 0 and 9 (inclusive). Add 1 to the generated number to get a random number between 1 and 10 (inclusive): int randomNumber = random.nextInt(10) + 1;
System.out.println("Random number between 1 and 10 (inclusive): " + randomNumber);
main
method and the RandomNumberGenerator
class:}
This program will generate a random number between 1 and 10 (inclusive) and display it on the console.