GENERATE RANDOM NUMBERS BETWEEN TWO NUMBERS

Jeet Verma

Total Post:110

Points:776
Posted by  Jeet Verma
Java 
 1228  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.

Thanks in advance!
  1. AVADHESH PATEL

    Post:604

    Points:4228
    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!