jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Random method returning zero all the time Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Random method returning zero all the time" Watch "Random method returning zero all the time" New topic

Random method returning zero all the time

Shamsudeen Akanbi
Ranch Hand

Joined: Dec 24, 2010
Posts: 83
Hi ranchers, i discovered this class ain't generating a random number for the face variable. Kindly help finding my bug. It's returning zero all the time it's called on.

Thanks in advance!
Tony Docherty

Joined: Aug 07, 2007
Posts: 2737
You aren't calling the method that generates the random number.
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

Also, you're better off using java.util.Random.nextInt(int n). What you have will work if you modify it slightly and actually call the method, but Random is the preferred approach. It gives slightly better distributions, is cleaner to use, and is what people expect to see when reading code.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11881

Whenever my code acts in what I think is a weird way, i stick in System.out.println statements EVERYWHERE. Print when you enter and exit a method. Print when you change a variable. print when you call a method.

I did that, and found that you never enter your roll() method. You never even enter your getFace() method. All you are doing is creating a new Die, and printing the value of its face variable - which is initialized to 0 for you.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
Also, if this is supposed to simulate a die: what's the lowest possible result on a die? And what's the highest? Are those the numbers you get from your method?
Shamsudeen Akanbi
Ranch Hand

Joined: Dec 24, 2010
Posts: 83
Thank you guys, i never called the method, it's now working well. @Mike, thanks for your observation I only extracted the important part to find the bug!
I agree. Here's the link: http://aspose.com/file-tools
subject: Random method returning zero all the time
It's not a secret anymore!