
-----------------------------------
SilverSprite
Thu Jul 10, 2003 10:09 pm

Random numbers
-----------------------------------
how do i generate a random number in java?

-----------------------------------
rizzix
Fri Jul 11, 2003 8:02 am


-----------------------------------
one easy way of doing this is Math.random(); (returns a random num form 0.0 to 1.0)

another way of doing this is using java.util.Random class.
using this class u can set the seed ur self =)

-----------------------------------
poseidon
Wed Jul 23, 2003 10:41 pm

random ints
-----------------------------------
As a follow-up to this q

How would you use the Math.random(); to generate random integer values (say a integer between 1 and 10)?

if you cast Math.random() to become an integer it would have nor eal use because the value would jsut be 0.  

Is there another way to generate random integers other than using the two previously mentioned methods/class?

-----------------------------------
SilverSprite
Thu Jul 24, 2003 11:39 am


-----------------------------------
Yes.. heres an example.


import java.util.Random;

public class RandomGen
{
   public RandomGen()
   {
       System.out.println(Random.nextInt(10)+1);
   }
}


-----------------------------------
BlAcK TuRtLe
Tue Oct 07, 2003 7:29 pm


-----------------------------------
my teacher showed us another way to do it it was sumthing like
var=(int) math.random()(=sumthing i dunno)
does anyone know what im talkin bout?

-----------------------------------
Tony
Tue Oct 07, 2003 8:21 pm


-----------------------------------
I think so  :?

Math class also has a Random method that generates a double between 0 and 1. Then you assign that value to an integer.

java.util.Random; is better though. You have more control over your (pseudo)random number

-----------------------------------
BlAcK TuRtLe
Tue Oct 07, 2003 8:33 pm


-----------------------------------
The only problem is that we havent covered the method in this topic. Hmm I'll just ask somebody at school 2morrow. No rush. Thx anyway tho.

-----------------------------------
Dan
Tue Oct 07, 2003 8:42 pm


-----------------------------------
dan all ways dos thing difrent so heres dans way


(int)((Math.random() * 10) + 1)


the (int) type casts it to an int type rather then double and you times it by 10 to get 0 - 9 add 1 and you get 1 - 10

-----------------------------------
Tony
Tue Oct 07, 2003 10:34 pm


-----------------------------------
Tony (usually doing opposite of w/e Dan does)

creates RandGen object from java.util.Random; and uses .NextInt method to generate integers right away. No type casting  :lol:

-----------------------------------
BlAcK TuRtLe
Wed Oct 08, 2003 9:27 am


-----------------------------------
ya thats the one. Thx.
