Generate Random Integer in specific range in Java

Ranging random integers not found in java.util.Random


An example on generating random integers between a specified range.


Example


import java.util.*;
class RandomRangeInt
{
public static void main(String args[])
{

// Create Random object
Random r=new Random();

// Specify start, end
int start=10;
int end=100;

// Create a 1 time loop
for(int i=0;i<1;i++)
{

// Generate random int below 100
int k=r.nextInt(end);

// If random integer below 100 is greater than start (10)
                        if(k>start)

// Then print
System.out.println(k);

                        // Else loop again, till if is true!, you may also write while loop
else i--;

}
}
}

Output

77

If you want to include start i.e. you want to allow even value of start (here 10) to come, then you must change if(k>start) to if(k>=start)

If you don't wish to write the logic, you can see my example on my class gowtham.gutha.util.RandomRangeInteger, download the java-utils framework (for using the class).

If you don't have already seen generating random integers in Java, you can see my post of Generating random values in Java (for all datatypes int,float,long,double..) and for generating random strings from first and last names, there is also a post.


Posted by at on

Tags: Java Utilities,