This tutorial will show any Java developer (beginner or otherwise) how to generate a random number within an arbitrary range. You can use random numbers for many purposes, such as; artificial intelligence, game design and mathematical applications.

The code to create a simple random number generator that will continue to produce random numbers within an arbitrary range until the program is closed is below:

package randomnumbercreator;

/*
* Title: Random Number Creator
* @author Dillon Chaffey
* Website: https://chafflube.wordpress.com
* E-mail: chafflube@hotmail.com
*/

public class RandomNumberCreator {
    // Variable declarations
    static int randomNumberInt;
    static int maxRangeInt;
    static int minRangeInt;
   
    public static void main(String[] args) {
        minRangeInt = 0;    // This creates the base of the range
        maxRangeInt = 100;  // This creates the top of the range
       
        // Create infinite loop
        while(true) {
            // Update the value of randomNumberInt
            randomNumberInt = (minRangeInt + (int)(Math.random() * (maxRangeInt – minRangeInt)));
            // Print the updated value of randomNumberInt
            System.out.println(randomNumberInt);
        }
    }
}

The above code, if compiled “as is,” will provide you with an endless stream of random numbers within the range of 0 to 100. However, you can easily change this range by changing the value of minRangeInt to the lower end of the range you desire and changing the value of maxRangeInt to the higher end of the range you desire.

I hope that by teaching you how to generate random numbers within a range I can save you the time that I took to learn how to do so. Good luck with your future Java coding ventures!

Advertisements