-1

I have to do a little calculating but something is not working well, can anybody tell what?

For example if i have one false and one true, it should be 50% but it gives me 0%, what is wrong here?

for (Verhuur verhuur : verhuur)
{
    if(verhuur.getSchade() == true)
    {
        welSchade = welSchade + 1;
    }
    if(verhuur.getSchade() == false)
    {
        geenSchade = geenSchade + 1;
    }
}
percentageSchade = (welSchade / (welSchade + geenSchade)) * 100;
System.out.println("Het percentage boten met schade is " + percentageSchade + " %." );
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • 5
    You haven't shown any of the types involved, but I strongly suspect they're all `int`, which means you're doing integer arithmetic... – Jon Skeet Nov 04 '15 at 16:16
  • Are you sure `getSchade()` is returning the correct values? – Bethany Louise Nov 04 '15 at 16:16
  • 4
    Possible duplicate of [Division of integers in Java](http://stackoverflow.com/questions/7220681/division-of-integers-in-java) - but that's only part of the problem, see @Pietervandeheyden 's answer. – fvu Nov 04 '15 at 16:17
  • What is this variables greenSchade, percentageSchade and welSchade? They are important to understand and solve your problem. – Túlio Castro Nov 04 '15 at 16:22

4 Answers4

2

You may want to convert this to double:

((double)welSchade / (welSchade + geenSchade)) * 100
ergonaut
  • 6,929
  • 1
  • 17
  • 47
2

Your problem is that you are dividing an integer by a larger integer, which returns 0, since integers don't have fractions.

You can either change the order of operations (multiply by 100 before the division, to ensure the result of the division is at least 1) or work with double or float variables, which would allow results between 0 and 1.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

If welSchade and geenSchade are integers, then, the result of their division will be an integer. Thus, 0.5 would be evaluated to 0, which is why you are getting 0.

npinti
  • 51,780
  • 5
  • 72
  • 96
1

The problem is in the first line:

for (Verhuur verhuur : verhuur)

The second verhuur should be the variable name to iterate on. So probably something like this:

for (Verhuur verhuur : verhuurItems)

EDIT:

Like the other answers are suggesting, you also have to make floats from the integers or evaluate the expression as a float, like this:

((float)welSchade/((float)geenSchade+welSchade))*100
fvu
  • 32,488
  • 6
  • 61
  • 79