杂货清单麻烦

时间:2015-03-14 03:24:23

标签: java class oop

尝试为总计每件商品价格的作业完成一个Grocery列表程序并返回总成本。这就是我到目前为止所做的:

主要:

public class Grocery {

public static void main(String[] args) {
    GroceryList list = new GroceryList();  
    list.add ("carrots", 5, 0.40);  
    list.add ("apples", 4, 0.15);  
    list.add ("rice", 1, 1.10);  
    list.add ("tortillas", 10, .05);  
    list.add ("strawberries", 1, 4.99);  
    list.add ("chicken", 1, 5.99);  
    list.add ("lettuce", 1, 0.99);  
    list.add ("milk", 2, 2.39);  
    list.add ("yogurt", 3, 0.60);  
    list.add ("chocolate", 1, 3.99);  

GroceryList Test = new GroceryList();
System.out.println(Test.getTotalCost());
}
}

GroceryList类:

import java.util.*;

public class GroceryList {

    public double itemcost = 0;

    private String nameList[];
    private int quantityList[];
    private double priceList[];

    private GroceryItemOrder[] list = null;

    public int num;

    public GroceryList() {

        list = new GroceryItemOrder[10];
        this.num = 0;

}

public void add(String name, int quantity, double price) {
    if (num < 10) {
        nameList[num] = name;
        quantityList[num] = quantity;
        priceList[num] = price;
        num++;

    }

}

public double getTotalCost() {
    double totalcost = 0;
    for (int i = 0; i < 9; i++) {
        totalcost = totalcost + quantityList[i] + priceList[i]; 
    }
    System.out.println(totalcost);
    return totalcost;
}

}

GroceryItemOrder类:

public class GroceryItemOrder {
private String name;
private double pricePerUnit;
private int quantity;

public GroceryItemOrder(String name, int quantity, double pricePerUnit) {

    this.name = name;
    this.pricePerUnit = pricePerUnit;
    this.quantity = quantity;

}

public double getCost() {

    return (this.quantity * this.pricePerUnit);
}

public void setQuantity(int quantity) {

    this.quantity = quantity;

}

}

当我尝试将println添加到add函数以进行测试时,我一直得到输出0.0(类似20次),因此我猜测它不是出于任何原因将信息传递到数组中,或者从他们那里读书有困难,但我不能为我的生活找出原因。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你打印出GroceryList TEST的费用,而不是GroceryList LIST!因为你没有在TEST列表中添加任何内容,所以它返回0

我想你想要的是

    list.getTotalCost ();