Java Program to generate a sequence of random numbers

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.

Java Program to generate a sequence of random numbers

  • Write a program in Java to print a sequence of N random numbers.
  • Java program to implement a random number generator.

This program takes “N”(number of random numbers to generates) and “maxRange” (maximum limit of random numbers) as input from user and then generates a sequence of N random numbers between 1 to maxRange. It uses java.util.Random class to generate a set of random numbers.

  • Random class : An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
  • Random.nextInt(int K) : This method returns a pseudorandom, uniformly distributed between 0 (inclusive) to K (exclusive), drawn from this random number generator’s sequence.

Java program to generate random numbers

Java program to generate random numbers

package com.tcc.java.programs;
 
import java.util.*;
 
public class RandomNumberGenerator {
    public static void main(String args[]) {
       int count, maxRange, i;
   
       Scanner in = new Scanner(System.in);
       System.out.println("Enter Maximum limit of Random Numbers");
       maxRange = in.nextInt();
       System.out.println("Enter number of Random Numbers to generate");
       count = in.nextInt();
       System.out.println("Random Numbers:");
       Random randomGenerator = new Random();
      
       for (i = 0; i < count; i++) {
          System.out.print(randomGenerator.nextInt(maxRange)+" ");
       }
    }
}

Output

Enter Maximum limit of Random Numbers
100
Enter number of Random Numbers to generate
6
17 6 31 36 77 54