codescracker


java

Java Program to Generate Random Numbers



« Previous Program Next Program »


Generate Random Numbers

To generate random numbers in Java programming, you have to create the object of Random class available in the java.util.Random package as shown in the following program.

Java Programming Code to Generate Random Numbers

Following Java program ask to the user to enter 'how many random numbers he/she want to generate ?', then the following program generates the required amount of random numbers between the range 0 to 999 :

/* Java Program Example - Generate Random Numbers */
		
import java.util.Scanner;
import java.util.Random;

public class JavaProgram
{
    public static void main(String[] input)
    {
        int len, i, randnum;
        Random rn = new Random();
        Scanner scan = new Scanner(System.in);
        
        System.out.print("How Many Random Numbers You want to Generate ? ");
        len = scan.nextInt();
        
        System.out.print("\nGenerating " + len + " Random Numbers in the range 0...999 \n");
        for(i=0; i<len; i++)
        {
            randnum = rn.nextInt(1000);
            System.out.print(randnum + "   ");
        }
    }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program generate random numbers

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test