It's not a secret anymore!
The moose likes Beginning Java and the fly likes Question on java.util.Random Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question on java.util.Random" Watch "Question on java.util.Random" New topic

Question on java.util.Random

Bob Beerbower
Ranch Hand

Joined: Jun 06, 2001
Posts: 32
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.

Regards Bob Beerbower
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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.

"I'm not back." - Bill Harding, Twister
Bob Beerbower
Ranch Hand

Joined: Jun 06, 2001
Posts: 32
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 ]
I agree. Here's the link:
subject: Question on java.util.Random
It's not a secret anymore!