Java Program to Generate Random Numbers Using Random() Method Full Example Project For Beginners

 

 

Welcome folks today in this blog post we will be generating random numbers using random() method in java. All the full source code of the application is shown below.

 

 

 

 

Get Started

 

 

 

In order to get started you need to make an app.java file and copy paste the following code

 

 

app.java

 

 

// Java program to demonstrate working
// of java.lang.Math.random() method
import java.lang.Math;

class Gfg1 {

    // driver code
    public static void main(String args[])
    {
        // Generate random number
        double rand = Math.random();

        // Output is different everytime this code is executed
        System.out.println("Random Number:" + rand);
    }
}

 

 

 

// Java program to demonstrate working
// of java.lang.Math.random() method
import java.lang.Math;

class Gfg2 {

    // driver code
    public static void main(String args[])
    {
        // define the range
        int max = 10;
        int min = 1;
        int range = max - min + 1;

        // generate random numbers within 1 to 10
        for (int i = 0; i < 10; i++) {
            int rand = (int)(Math.random() * range) + min;

            // Output is different everytime this code is executed
            System.out.println(rand);
        }
    }
}

Leave a Reply