Advertisement

Random Numbers in Java

Started by December 13, 2001 07:23 PM
4 comments, last by Jason Feinstein 22 years, 11 months ago
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.
Jason Feinstein- [email=opensrc@jymail.net]opensrc@jymail.net[/email]- The Junkyard
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.
"None of us learn in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!" - Michael Abrash[JavaGaming.org][The Java Tutorial][Slick][LWJGL][LWJGL Tutorials for NeHe][LWJGL Wiki][jMonkey Engine]
Advertisement
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.
Thanks!
Jason Feinstein- [email=opensrc@jymail.net]opensrc@jymail.net[/email]- The Junkyard
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
Go there and read chapter 7.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement