如何将两个对象一起添加

时间:2017-05-02 12:21:12

标签: java

我试图将两个对象添加到一起,将数据放入标签中,但我无法搞清楚

public void calculateprice(ArrayList rprice){

    Object totalPrice = 0;

    for(int x = 0; x < rprice.size(); x++) {

        Object price = rprice.get(x);

        Object numResult = add(totalPrice, price);

        pricelbl.setText(price);

    }

3 个答案:

答案 0 :(得分:1)

您应该使用数值数据类型进行算术运算(不是Object)。看不到add()中的代码,我的建议是将总价格存储在double原语中。

     double price =0;

     for(int x = 0; x < rprice.size(); x++) {
    //you may need to cast/convert  here
        price += (double)rprice.get(x);

    //what does this do????
        Object numResult = add(totalPrice, price);

        pricelbl.setText(price);

    }

答案 1 :(得分:1)

根据您的代码,您绝对不应该使用Object。只需使用基本的JAVA类型,如int,float ...

这样:float totalPrice = 0;

然后,如果你的get方法发送回一个对象,只需投射它,但你应该改变它,所以它返回一个浮动......

您还需要更改add(Object,Object)方法,如果您知道正在使用的变量的类型,请不要使用Object。

答案 2 :(得分:1)

尝试这样的事情:

public void calculateprice(ArrayList rprice){

    Object totalPrice = 0;

    for(int x = 0; x < rprice.size(); x++) {

        Object price = rprice.get(x);
        totalPrice = add(totalPrice, price);
    }
    pricelbl.setText(totalPrice);
}

但这种方式很糟糕(你的代码味道)。使用数字类型进行计算。 好多了:

public void calculateprice(ArrayList<Integer> rprice){

        Integer totalPrice = 0;

        for(int x = 0; x < rprice.size(); x++) {

            Integer price = rprice.get(x);
            totalPrice += price;
        }
        pricelbl.setText(totalPrice);
    }
实际上,这段代码也不完美。最佳变体将是:

public Integer calculateprice(List<Integer> prices){

    Integer totalPrice = 0;

    for(int x = 0; x < prices.size(); x++) {
        Integer price = prices.get(x);
        totalPrice += price;
    }
    return totalPrice;
}