How to Generate random number in java Program

import java.util.*;

class RandomNumbers {
  public static void main(String[] args) {
    int c;
    Random t = new Random();

    // random integers in [0, 100]
    for (c = 1; c <= 10; c++) {
      System.out.println(t.nextInt(100));
    }
  }
}

Step-by-Step Explanation:

1. Importing Random class:

import java.util.*;

The Random class is in the java.util package, so we import it to use it in our program.

2. Class Definition:

We define a class named RandomNumbers. The class contains the main method, which is the entry point for the program.

3. Main Method:

public static void main(String[] args) {

The main method is the entry point of the program. It will be executed when the program runs.

4. Random Object Creation:

Random t = new Random();

A Random object, called t, is created using the Random constructor. This object will serve the purpose of producing random numbers.

5. For Loop to Produce Random Numbers:

for (c = 1; c <= 10; c++) {

      System.out.println(t.nextInt(100));

  }

  •  The for loop runs for 10 times that is from c = 1 to c = 10.
  • Inside the loop, the nextInt(100) method of the Random object t is called.
  • nextInt(100) generates a random integer between 0 and 99 (inclusive of 0 but exclusive of 100).
  • System.out.println(.) prints each random number generated in each iteration of the loop.

Program Flow:

Expected Output:

The output will be 10 random integers between 0 and 99, one on each line. Because the random numbers are generated dynamically each time you run the program, the actual output will vary each time you run the program. Here is an example of what the output might look like:

12

84

37

56

28

65

99

11

23

4

  • The random number you see each time you run your program is different because all the numbers are generated randomly.
  • Every number is printed to a new line.

Summary

  • The Random class shows how to generate random integers. The value of the random number will be within the range of [0, 100), so numbers can go from 0 to 99.
  • It prints a total of 10 random numbers, one per line.

Leave a Comment

Your email address will not be published. Required fields are marked *