• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

Question on java.util.Random  RSS feed

 
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.
 
Wanderer
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!