Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

random numbers

 
raghuram gannavarapu
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks ravi,
that works well...
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic