Jump to content

  • Log In with Google      Sign In   
  • Create Account

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.

  • You cannot reply to this topic
5 replies to this topic

#1 Jason Feinstein   Members   -  Reputation: 122

Like
Likes
Like

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.

Sponsor:

#2 CaptainJester   Members   -  Reputation: 523

Like
Likes
Like

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.

#3 Dobbs   Members   -  Reputation: 164

Like
Likes
Like

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.

#4 Jason Feinstein   Members   -  Reputation: 122

Like
Likes
Like

Posted 14 December 2001 - 05:13 AM

Thanks!

#5 Bravolino   Members   -  Reputation: 122

Like
Likes
Like

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

#6 Fruny   Moderators   -  Reputation: 1653

Like
Likes
Like

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.



PARTNERS