Thursday, 22 June 2017

Generate Random Integer in specific range in Java ~ foundjava

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.RandomRangeIntegerdownload the java-utils framework (for using the class).

No comments:

Post a Comment