Computer Science Canada

Random numbers

Author:  SilverSprite [ Thu Jul 10, 2003 10:09 pm ]
Post subject:  Random numbers

how do i generate a random number in java?

Author:  rizzix [ Fri Jul 11, 2003 8:02 am ]
Post subject: 

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 =)

Author:  poseidon [ Wed Jul 23, 2003 10:41 pm ]
Post subject:  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?

Author:  SilverSprite [ Thu Jul 24, 2003 11:39 am ]
Post subject: 

Yes.. heres an example.


import java.util.Random;

public class RandomGen
   public RandomGen()

Author:  BlAcK TuRtLe [ Tue Oct 07, 2003 7:29 pm ]
Post subject: 

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?

Author:  Tony [ Tue Oct 07, 2003 8:21 pm ]
Post subject: 

I think so Confused

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

Author:  BlAcK TuRtLe [ Tue Oct 07, 2003 8:33 pm ]
Post subject: 

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.

Author:  Dan [ Tue Oct 07, 2003 8:42 pm ]
Post subject: 

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

Author:  Tony [ Tue Oct 07, 2003 10:34 pm ]
Post subject: 

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 Laughing

Author:  BlAcK TuRtLe [ Wed Oct 08, 2003 9:27 am ]
Post subject: 

ya thats the one. Thx.