The moose likes Beginning Java and the fly likes Algorithm not working? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Algorithm not working?" Watch "Algorithm not working?" New topic

Algorithm not working?

Ashley Kin
Ranch Hand

Joined: Oct 18, 2011
Posts: 36
Hi, my algorithm (wins/numberOfGames)*100 is not working; it's printing out 0 every time, even though all four other variables are working fine.
Is my algorithm itself not correct?
I just assumed win% means the percentage of games won.
Thanks as always!

Hebert Coelho
Ranch Hand

Joined: Jul 14, 2010
Posts: 754

Is there any other values like 0?

[] [Full WebApplication JSF EJB JPA JAAS with source code to download] One Table Per SubClass [Web/JSF]
Bob Bilfred

Joined: Nov 01, 2011
Posts: 7
There isn't really a problem with the code since it does what was typed. Since both "wins" and "numberOfGames" are integers, when you divide them, you also get an integer. This calculation will also result in a decimal number, not an integer. Therefore, dividing two integers, say 6 and 10, will not be 0.60, it will be 0 since integers remove the numbers after the decimal point. Therefore, we need to cast "wins/numberOfGames" to a double. In order to do this, write the following instead...

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46360
Welcome to the Ranch Bob Bilfred

Another way to do it is to move the 100 * to the beginning of the formula. () unnecessary, and can actually cause errors, so no (). Beware: you can get overflow problems with large numbers, and 100 * 999 / 1000 will come out as 99%, not 99.9%.
I agree. Here's the link:
subject: Algorithm not working?
It's not a secret anymore!