简体   繁体   中英

java error:inconvertible types required int

what is wrong with this code??

int  amount= (int)  amountSpnr.getValue();  // 1
float total = (float) productData[3]*amount; // 2
total2pay+=total;
totalFld.setText(total2pay+"");
model.addRow(new Object[]{productData[0], productData[1],productData[2],productData[3], amount, total});`

says :

inconvertible types
(for the 1st line)- required int found Object
(for the 2nd line)- required float found Object

What can i do?

You cannot cast Objects in Java to primitive (except for their respective wrapper classes).

Try using this:

    Object obj1 = amountSpnr.getValue();
    Object obj2 = productData[3];

    if (obj1 instanceof Integer) {
        int amount = (Integer) obj1; // 1
    }

    if (obj2 instanceof Float) {
        float total = (Float) obj2; // 2
        total *= amount;
    }

In the above case, Object will be down-casted to Integer type, which will then be unboxed to primitive integer. Same is the case with Float .

Note: Be sure to add instanceof check before you perform downcasting just to make sure that you do not end up getting CastCastException .

If you need to tranform your Object into a int primitive you have to follow 2 steps :

First make sure your object has the good type. Cast it with (Integer) or (Float) . You can use instanceof if you're not sure of the type returned by getValue (case 1) or by you array (case 2)

Then use .intValue() or .floatValue() .

Example :

int amount=((Integer)amountSpnr.getValue()).intValue();

float total = ((Float) productData[3]*amount).floatValue();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM