Home > DeveloperSection > Forums > Generate random numbers between two numbers
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    May-07-2013 1:12 AM

 Java Java 
Ratings:


 1 Reply(s)
 957  View(s)
Rate this:
Hi Guys!

public class TestSample {
    public static void main(String[] args) { 

        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);

        double ran = Math.random();
    }
}
I don't want to use Random r = new Random(); class. Is there any other way to generate random numbers. I am just struck with what logic could be applied to generate random numbers between two numbers.

Thanks in advance!


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-07-2013 7:54 AM

Hi Jeet!

Consider using this code:

int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double ran = Math.random();
double random;

if(a < b)
    random = (b-a)*ran + a;
else
    random = (a-b)*ran + b;
This will work for a >= 0 and b >= 0 if yo consider using negative number the logic sligtly changes

Don't want to miss updates? Please click the below button!

Follow MindStick