Author 
Message 
SilverSprite

Posted: Thu Jul 10, 2003 10:09 pm Post subject: Random numbers 


how do i generate a random number in java? 





Sponsor Sponsor



rizzix

Posted: Fri Jul 11, 2003 8:02 am Post subject: (No 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 =) 





poseidon

Posted: Wed Jul 23, 2003 10:41 pm Post subject: random ints 


As a followup 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

Posted: Thu Jul 24, 2003 11:39 am Post subject: (No subject) 


Yes.. heres an example.
code: 
import java.util.Random;
public class RandomGen
{
public RandomGen()
{
System.out.println(Random.nextInt(10)+1);
}
}







BlAcK TuRtLe

Posted: Tue Oct 07, 2003 7:29 pm Post subject: (No 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? 





Tony

Posted: Tue Oct 07, 2003 8:21 pm Post subject: (No subject) 


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 
Tony's programming blog. DWITE  a programming contest. 




BlAcK TuRtLe

Posted: Tue Oct 07, 2003 8:33 pm Post subject: (No 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. 





Dan

Posted: Tue Oct 07, 2003 8:42 pm Post subject: (No subject) 


dan all ways dos thing difrent so heres dans way
code: 
(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 
Computer Science Canada
Help with programming in C, C++, Java, PHP, Ruby, Turing, VB and more! 




Sponsor Sponsor



Tony

Posted: Tue Oct 07, 2003 10:34 pm Post subject: (No 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 
Tony's programming blog. DWITE  a programming contest. 




BlAcK TuRtLe

Posted: Wed Oct 08, 2003 9:27 am Post subject: (No subject) 


ya thats the one. Thx. 





