# Generate random numbers between two numbers

Posted by  Jeet Verma
1822  View(s)
Ratings:
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.

1. ##### Re: Generate random numbers between two numbers

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

10-B Taskand Marg, Near Patrika Chauraha, Civil Lines, Prayagraj, UP, India-211001.
contact@mindstick.com
91-532-2400505

969-G Edgewater Blvd,Suite
793 Foster City-94404, CA (USA)
+1-650-242-0133