Java provides support to either generate random numbers through java.lang.Math package or java.util.Random.
Using java.lang.Math
There exists a static method inside this class, Math.random. It is very convenient to use and returns a double between the range 0.0 and 1.0 i.e. it returns a floating point number between 0 and 1.
public static void main(String[] args){ double randNum = Math.random(); System.out.println(randNum); }
Random number within a range -
To generate a random number within a range we need to further process the number returned by Math.random()
This code produces a random double between the range 10 to 100.public static void main (String[] args){ double min = 10.0; double max = 100.0; double randNum = randRange(min, max); System.out.println(randNum); } public static double randRange(double min, double max){ double x = (Math.random()*((max-min)+1))+min; return x; }
With slight modification it can be made to return an integer.public static void main (String[] args){ int min = 10; int max = 100; int randNum = randRange(min, max); System.out.println(randNum); } public static int randRange(int min, int max){ int x = (int) (Math.random()*((max-min)+1))+min; return x; }Using java.util.Random
As java.util.Random is a class, we need to create an object before using it. This class has multiple methods likenextDouble(),nextInt()etc. which makes it easy to generate random numbers to our requirement.
The following snippet produces a random double between 0 and 1 similar to Math.random()
Usually, the constructor, i.e.public static void main (String[] args){ Random rand = new Random(System.currentTimeMillis()); System.out.println(rand.nextDouble()); }Random rand = new Random(System.currentTimeMillis());can also be used without theSystem.currentTimeMillis(). This is an optional argument and acts as a seed. It's fine if you just useRandom rand = new Random();but it's better to use with the seed. Theoretically, the seed could be any number.Generating a random integer -
public static void main (String[] args){ Random rand = new Random(System.currentTimeMillis()); int randNum = rand.nextInt(); System.out.println(randNum); }Random integer between 0 and another number -
public static void main (String[] args){ Random rand = new Random(System.currentTimeMillis()); int max = 1000; int randNum = rand.nextInt(max); System.out.println(randNum); }Random integer between a range -
public static void main (String[] args){ Random rand = new Random(System.currentTimeMillis()); int max = 1000; int min = 500; int randNum = r.nextInt((max - min) + 1) + min; System.out.println(randNum); }
Comments
Post a Comment