How do I generate a random number between 0 and some integer n?

John Zukowski

While you can use Math.random() to generate random numbers, the Random class in the util package is actually a little easier to work with if you don't just want a number between 0 and 1.

First you would need to create an instance of Random somewhere, like your constructor or the init() method of an applet:

Random random = new Random();
Then, whenever you need a number, you ask it:
int pick = random.nextInt(maxvalue);

This would return a value from 0 (inclusive) to maxvalue (exclusive).
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact