Archived

This topic is now archived and is closed to further replies.

Jason Feinstein

Random Numbers in Java

Recommended Posts

I''ve started writing my first game *looks all excited*, a Minesweeper clone (in Java). I was wondering if anybody knew off-hand how you go about generating a random number? I need to do this to determine weather or not the tile needs to have a mine. Also, I was wondering if there are any good articles/books out there about Game development with Java.

Share this post


Link to post
Share on other sites
Dobbs    164
That''s something easily found in the API documentation. The Math class in the java.lang package includes methods for all sorts of operations, including random number generation. For more control (ie choosing a seed) there''s also the Random class in the java.util package.

Share this post


Link to post
Share on other sites
Bravolino    122
In order to make random numbers in Java, you use the Math.random method. What you do is you make a statement such as:
int i=(int)(Math.random());

This gives you a random numebr between 0 and 1. If you want to extend the range (ie. 1-50),such as for a dice game, you do:
int i=(int) (Math.random()*6+1);
This should give you a random number between 1 and 6 and then cast it as an integer so that it doesn''t keep the decimals. Just change 6 to another number to increase the range. You can also cast it any other integer value (ie. byte,short,long,int) by defining the type of the variable as the specific integer type and then casting the random value into that type

ex:
long i=(long) (Math.random()*6+1)

there ya go. that''s how u do it. Next time post this in the Java forum though, please!
Mike

Share this post


Link to post
Share on other sites