Home > Tutorial > Java Random Number Sample Code

Java Random Number Sample Code

Java has a couple of options to generate random numbers. The first option is to combine the random() method with the floor() method of the Java Math class. The floor() method allows you to set the upper bounds of the random number.

The second option, which is a little simpler, is to use the Java Random class. The nextInt() method will return a random number between zero and the upper bounds that you set. I have included sample code below for both options.

Java Random Number Source Code:

package com.jcd.java.tutorials;

import java.util.Random;

public class JavaRandomNumberGenerator {
	

	public static void main(String[] args) {
		
		//How many random numbers to generate?
		int numberOfRandoms = 10;
		int upperBounds = 100;

		System.out.println("Generate Random Integers (Between 1-99) Using Java Math Class:");
		
		for(int x=0; x<numberOfRandoms; x++)
		{
			System.out.println("Random Integer: "+(int) Math.floor(Math.random() * upperBounds));
		}
		
		
		System.out.println("\nGenerate Random Integers (Between 1-99) Using Java Random Class:");
		
		Random random1 = new Random();
		
		for(int x=0; x<numberOfRandoms; x++)
		{
			System.out.println("Random Integer:"+random1.nextInt(upperBounds));
		}
		
		
		//If you need to generate random numbers in multiple classes, make it a method?
		System.out.println("\nRandom Generator Method Returned: "+generateRandomNumber(20));
		
	}
	
	
	//Method that will return a random generated integer between 0 and the upperBounds
	public static int generateRandomNumber(int upperBounds)
	{
		Random random = new Random();
		
		return(random.nextInt(upperBounds));
	}

}



Sample Java Random Number Output:

Generate Random Integers (Between 1-99) Using Java Math Class:
Random Integer: 44
Random Integer: 29
Random Integer: 15
Random Integer: 28
Random Integer: 34
Random Integer: 36
Random Integer: 94
Random Integer: 57
Random Integer: 94
Random Integer: 96

Generate Random Integers (Between 1-99) Using Java Random Class:
Random Integer:38
Random Integer:6
Random Integer:33
Random Integer:99
Random Integer:88
Random Integer:62
Random Integer:8
Random Integer:44
Random Integer:40
Random Integer:40

Random Generator Method Returned: 12



References:

Smedley
Posted by

Smedley

Smedley has been doing software development for years, which mainly docues on C and C++. In the past number of years, he has focused on Java programming.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot