How to generate Random numbers (JAVA) within a given number range


Here is the code example for generating random integers within a given number range;

GeneratingRandomNumbers.java

package javaapps;

/**
 *
 * @author tunatore
 */
public class GeneratingRandomNumbers {
    public static void main(String[] args) {

        //Generating random numbers within a given number range
        //setting min and max number borders

        int min = 0; //included
        int max = 10; //included
        System.out.println(“generating 5 random numbers between ” + min + ” and ” + max );
        for (int i = 0; i < 5; i++) {
            System.out.println(“number generated is –> ” + ((int) (Math.random() * (max – min + 1) ) + min ));
        }
        min = 50; //included
        max = 150; //included
        System.out.println(“generating 5 random numbers between ” + min + ” and ” + max );
        for (int i = 0; i < 5; i++) {
            System.out.println(“number generated is –> ” + ((int) (Math.random() * (max – min + 1) ) + min ));
        }
    }
}

The output(sample) of the program;

run:
generating 5 random numbers between 0 and 10
number generated is –> 5
number generated is –> 0
number generated is –> 4
number generated is –> 7
number generated is –> 4
generating 5 random numbers between 50 and 150
number generated is –> 134
number generated is –> 70
number generated is –> 125
number generated is –> 100
number generated is –> 117
BUILD SUCCESSFUL (total time: 0 seconds)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s