View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# Random Numbers in Java

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

5 replies to this topic

### #1Jason Feinstein  Members

Posted 13 December 2001 - 01:23 PM

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.

### #2CaptainJester  Members

Posted 13 December 2001 - 02:30 PM

Here is a site with some tutorials: JGDC

Also you might want to check out The Java Tutorial

---
Make it work.
Make it right.
Make it fast.

### #3Dobbs  Members

Posted 13 December 2001 - 05:32 PM

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.

### #4Jason Feinstein  Members

Posted 14 December 2001 - 05:13 AM

Thanks!

### #5Bravolino  Members

Posted 14 December 2001 - 11:53 AM

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

### #6Fruny  Moderators

Posted 14 December 2001 - 11:55 AM

Go there and read chapter 7.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.