• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question on java.util.Random

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic