mercredi 6 avril 2016

Creating an object of Random class or using Math.random() in order to generate random numbers

When you have imported java.util.Random, you can both generate random integers and random double two ways.

You could create an instance of the Random class

Random randomGenerator = new Random();

and then use it to generate a random integer or double that is greater than or equal to 0 but less than 10

int randomInteger = randomGenerator.nextInt(10);
double randomDouble = randomGenerator.nextDouble(10);

You can also use Math.random()

int randomInteger = (int)(Math.random() * 10)
double randomDouble = Math.random() * 10

I think both methods gives the exact same result. Is one of these two methods ever preferred rather than the other?




Aucun commentaire:

Enregistrer un commentaire