【问题标题】:Using return values from methods on ArrayList使用 ArrayList 上方法的返回值
【发布时间】:2020-06-10 13:27:47
【问题描述】:

昨天我发布了一个关于 ArrayList 没有打印方法输出的问题,它恰好只是一个语法错误。然而,今天我遇到了一个类似的问题,该错误已修复。如果有人能告诉我这段代码有什么问题,我将不胜感激。

我的问题是 ArrayList 打印出 [0.0, 0.0, 2.75] 而不是我预期的价格列表。

    import java.util.ArrayList;

    public class TransitCalculatorTwo {
    int numberDays;
    int numberRides;
    int numberPlanSeven;
    int numberPlanThirty;
    double totalPriceSeven;
    double totalPriceThirty;
    double pricePerRideSeven;
    double pricePerRideThirty;
    double SinglePrice = 2.75;
    double sevenDayPrice = 33.0;
    double thirtyDayPrice = 127.00;


    public int numberPlanSeven(int numberDays) {
        int planSeven = (int) Math.ceil (numberDays / 7.0);
        return planSeven;
    }
    public int numberPlanThirty(int numberDays) {
        int planThirty = (int) Math.ceil (numberDays / 30.0);
        return planThirty;
    }

    public double totalPriceSeven (int numberPlanSeven, double sevenDayPrice) {
        double totalSeven = numberPlanSeven * sevenDayPrice;
        return totalSeven;
    }

    public double totalPriceThirty (int numberPlanThirty, double thirtyDayPrice) {
        double totalThirty = numberPlanThirty * thirtyDayPrice;
        return totalThirty;
    }

    public double pricePerRideSeven (double totalPriceSeven, int numberRides) {
        double ppRideSeven = totalPriceSeven / numberRides;
        return ppRideSeven;
    }
    public double pricePerRideThirty (double totalPriceThirty, int numberRides) {
        double ppRideThirty = totalPriceThirty / numberRides;
        return ppRideThirty;
    }

    public ArrayList<Double> comparePrice() {
        ArrayList<Double> prices = new ArrayList<Double>(); for (int i=0; i<1; i++) {
            prices.add(pricePerRideSeven);
            prices.add(pricePerRideThirty);
            prices.add(SinglePrice);
        }
        return prices;

    }

    public static void main (String[]args) {
        TransitCalculatorTwo customer = new TransitCalculatorTwo();

        customer.pricePerRideSeven(66.0, 50);
        customer.pricePerRideThirty(127.00, 50);

        System.out.println(customer.comparePrice());

    }
}

【问题讨论】:

    标签: java arraylist methods


    【解决方案1】:

    您没有在 main 中构造的对象中设置变量值。您正在为局部变量而不是对象参数设置值。您的代码必须如下所示:

    public double pricePerRideSeven (double totalPriceSeven, int numberRides) {
        this.pricePerRideSeven = totalPriceSeven / numberRides;
        return this.pricePerRideSeven;
    }
    
    public double pricePerRideThirty (double totalPriceThirty, int numberRides) {
        this.pricePerRideThirty = totalPriceThirty / numberRides;
        return pricePerRideThirty;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 2015-01-29
      • 2014-04-12
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多