Lakshan
Lakshan

Reputation: 31

How to fix conversion errors in a switch statement?

conversion error float to int

public void priceMaker(float perc) {
    float distance = (float) dist.getValue();
    if (distance >= (float) 75.0) {
        switch (distance) {
            case 5.0:
                float f_5 = (float) (80.0 * 5.0 * perc);
                label_f_5_result.setText("Rs.80 * 5 * " + perc + "( risk factor % ) = " + f_5);
                label_apx_delv_fee_result.setText("Rs." + f_5);
        }
    }
}

I'm retrieving a distance value (like 1.5, 5, 4.3 in kilometers) from a jSpinner in my GUI. I have already changed the jSpinner model to [Number]>>(float). However I keep getting an IDE error even after I cast the calculations to float type:

possible lossy conversion from float to int error

I'm still a Java beginner and I couldn't find a solution. However, if I change distance from float to int the error disappears but I want float values because a distance won't be a roundup.

Upvotes: 1

Views: 128

Answers (1)

ClaudiaR
ClaudiaR

Reputation: 3424

As said in the comments you cannot switch on variables of type float. Have a look at the switch documentation. In particular the initial part goes:

Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types.

This is because the representation of float values is inaccurate by nature. If you are interested in knowing more about floating points and why this happens, have a look at this.

As for how you might solve your situation, yes, you should go for if-else statements. However keep in mind that you cannot use == for float comparison (see this for more info). Try something like this:

public void priceMaker(float perc) {
    float distance = (float) dist.getValue();
    if (Float.compare(distance, 5f) == 0) {
        // do something
    }
}

Go here for Float.compare() documentation.

Upvotes: 2

Related Questions