This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on java.util.Random

 
Bob Beerbower
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to use the Random class for generating random numbers. If I use the following import statement

the code complies. However if I use,

I get an error message

This is the code I'm running;


My understanding is that util.Random is a subset of util.*. If so why won't my code using util.* compile. The sample I copied off the web used util.*, but I couldn't get that to compile either.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My guess is that you've got another class called Random lying around in the current directory. (Or in some other directory which is on your classpath.) When you explicitly name java.util.Random it finds that class first, but when you say java.util.* it finds the other class first. This is one reason why it's often recommended to prefer specific imports to wildcards. Also it's advisable to avoid using class names which duplicate standaard library class names, such as Random.

Incidentally that "rand" method is needlessly complex, and has some subtle bugs which are probably not suitable for discussion in the beginner forum. (See Effective Java p. 145-6 for an explanation.) There's an overload of the nextInt() method, nextInt(int), which can be used here to make a rand() method which is both simpler and more effective.
 
Bob Beerbower
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I thought I got rid of that other Random class, I'll check again. I'll look at the rand mathod as well.
[ January 01, 2006: Message edited by: Bob Beerbower ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic