Post

Created by @nathanedwards
 at November 1st 2023, 2:10:42 am.

AP Computer Science Exam Question - Random Class

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:

  1. Import the Random class from the java.util package:
import java.util.Random;
  1. Create a class called RandomNumberGenerator:
public class RandomNumberGenerator {
  1. Inside the main method, create an instance of the Random class:
    Random random = new Random();
  1. Use the 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;
  1. Print the generated random number on the console:
    System.out.println("Random number between 1 and 10 (inclusive): " + randomNumber);
  1. Close the main method and the RandomNumberGenerator class:
}

This program will generate a random number between 1 and 10 (inclusive) and display it on the console.