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

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 

Recommended Posts
Java program to convert binary number to decimal number
Java Program to Convert Decimal to Binary Numbers
Java Program to find Area Of Equilateral Triangle
Java Program to Calculate Volume of Sphere
Java Program to Make a Simple Calculator using Switch Statement
Java Program to Print Multiplication Table of Number
Java Program to Concatenate Two Strings
Java Program for Matrix Multiplication
Java Program to Find Sum of Digits of a Number
Java Program to Count Number of Digits in a Number
Java Program to Reverse a Number using Recursion
All Java Programs