aspose file tools*
The moose likes Beginning Java and the fly likes random number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "random number" Watch "random number" New topic
Author

random number

tyhooke cologne
Greenhorn

Joined: Jan 11, 2005
Posts: 2
anyone know a slick way to create a random number between a negitive number and it's corosponding positive one?
i.e. gimme a random # between -5 and 5
thanks
-tyhooke
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

How about this?


Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
A more generic solution may be:



The output:



Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
tyhooke cologne
Greenhorn

Joined: Jan 11, 2005
Posts: 2
these help. thank you both!
-Tyhooke
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
You're welcome!
Patrick Joseph
Greenhorn

Joined: Jan 11, 2005
Posts: 11
How about:


This gives you a random index (range of 0 to [array length - 1]) that will then give you the random contents (-5 to 5).
[ January 12, 2005: Message edited by: PJ Chin ]
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
Sure, but what happens when the user comes back and says, "Oh, now we need -10 to 10"? The hard-coded values method would need to be rewritten, where the general method would not. I always try to think "Reusability" when I write code, and part of that is not having any hard-coded values (except perhaps in the testing/driver program)...
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Jeff Bosch:
int random = r.nextInt( 2 * number ) - number;
Keep in mind that Random.nextInt(number) returns a value in the range [0, number), meaning 0, 1 ... number - 1. It will not return number itself. Thus the general solution should be changed to
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
Ah, good point! I'd whipped that solution up in haste and something about it just didn't feel right, but I didn't really have time to go back to it.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
To add more flexibility, you may want to write a method with the following signature:


This would return a random integer between min and max. I'll leave the implementation as the proverbial exercise for the reader. However, it shouldn't be difficult to modify Jeff's program above for this purpose.

Layne


Java API Documentation
The Java Tutorial
 
Don't get me started about those stupid light bulbs.
 
subject: random number