aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes random numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "random numbers" Watch "random numbers" New topic
Author

random numbers

raghuram gannavarapu
Greenhorn

Joined: Dec 19, 2003
Posts: 6
hi all,
i have tried to generate a set of random numbers using the following code.
but when i run this code i obtained the same random number until the loop is terminated.
can anyone pls tell me how can i get different random numbers at a time.
pls tell me how cwn my code be modified for the purpose?
code:
import java.util.Random;
public class Randomint
{
public static void main(String [] args)
{ int i=5;
while(i!=0)
{
Random rand=new Random();
int prob=(int)(100*rand.nextDouble());
System.out.print(" "+prob);
i--;
}
}
}
thanks
raghu
Ravi Srinivas
Greenhorn

Joined: Sep 04, 2003
Posts: 26
Try moving the new Random() line out of the loop. You need generate a new Random object only once. Every time you want a random no., just use that object to generate another no. by saying random.nextDouble()
So I think your code could be-
import java.util.Random;
public class Randomint
{
public static void main(String [] args)
{
Random rand=new Random();
int i=5;
while(i!=0)
{
int prob=(int)(100*rand.nextDouble());
System.out.print(" "+prob);
i--;
}
}
}

Originally posted by raghuram gannavarapu:
hi all,
i have tried to generate a set of random numbers using the following code.
but when i run this code i obtained the same random number until the loop is terminated.
can anyone pls tell me how can i get different random numbers at a time.
pls tell me how cwn my code be modified for the purpose?
code:
import java.util.Random;
public class Randomint
{
public static void main(String [] args)
{ int i=5;
while(i!=0)
{
Random rand=new Random();
int prob=(int)(100*rand.nextDouble());
System.out.print(" "+prob);
i--;
}
}
}
thanks
raghu

Ravi Srinivas
Greenhorn

Joined: Sep 04, 2003
Posts: 26
oops, sorry abt all the extra tags in the previous posting.. it was my first posting, so I was just horsing around!
raghuram gannavarapu
Greenhorn

Joined: Dec 19, 2003
Posts: 6
thanks ravi,
that works well...
Alfred Kemety
Ranch Hand

Joined: Aug 14, 2002
Posts: 279
Well it should actually work with the first code, even with the new operator inside the loop.
This raises the question about how "random" random numbers generated by the JVM are :roll:


Alfred Raouf - Egypt - SCJP 1.4<br />Kemety.equals(Egyptian) // returns true
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: random numbers