jorrebor
jorrebor

Reputation: 2232

Issue with simple calculation in Java

This for loop should sum all values contained in the treemap. This works, but after the inner loop the values up and down are used to calculate the accuracy. It seems that this is never executed.

What am I doing wrong?

            // for each row
        for (Entry<String, TreeMap<String, Integer>> table_row : table.entrySet()) {

            // write the label
            String row = table_row.getKey() + ",";

            int up = 0;
            int down = 0;
            float accu = 0;
                    // for each treemap in the row
            for (Entry<String, Integer> collumn : table_row.getValue().entrySet()) {
                row += collumn.getValue() + ",";
                down += collumn.getValue();//this works
                if (collumn.getKey() == table_row.getKey()) {
                    up = collumn.getValue();
                    }
            }

    --------->  accu = (up / down) * 100; //this is not executed?? 
            System.out.println("t: " + up + " n: " + down + " a: " +  accu);
            row = row + Float.toString(accu) + " %";
            writer.println(row);//this works too but output is always 0%
        }

Upvotes: 1

Views: 118

Answers (4)

Cratylus
Cratylus

Reputation: 54074

I assume that you are asking why accu is always 0 as in inline your comments.
accu = (up / down) * 100;
The literal 100 is an int as well as up and down. So the result probably rounds to 0

Just cast to float so that you don't lose precision.
accu = ((float)up / down) * 100;
This will work as the cast will precede the division and since if either operand if float the other also is converted to float even if integer

Upvotes: 3

Mike T
Mike T

Reputation: 1

The problem you're having is that both up and down are ints. When you divide an int by an int, the result is a int with any decimal truncated. It looks like you want a percent, so you should do something like:

accu = ((float) up / down) * 100;

Upvotes: 0

Rob Wagner
Rob Wagner

Reputation: 4421

Integer division!

Your down value is larger than your up and rounding down to zero, so each time you assign accu, you are effectively doing this accu = (0) * 100

If you are looking for precision, you should make up and down floats instead of ints, or make a cast right before you divide.

Upvotes: 1

cjstehno
cjstehno

Reputation: 13984

You probably don't want == in your if comparison, but rather equals()... unless you are expecting them to be the same instance of the string.

Upvotes: 3

Related Questions