我试图跟踪每件商品的成本,并将其添加到所有商品的总成本中。当我运行程序时,最后一项成本和总成本将应用于每个项目。我觉得我应该有另一个循环,更动态地放置每个项目的成本和总成本。
public class GroceryListTester
{
public static void main(String[] args)
{
GroceryList get = new GroceryList();
get.start();
}
}
import chn.util.*;
import java.util.*;
public class GroceryList
{
//Instance variables
private int myNumItems;
private double myItemCost;
private double myTotalCost;
Scanner keyboard = new Scanner(System.in);
//Constructor
public GroceryList()
{
myNumItems = 0;
myTotalCost = 0;
}
//Methods
public void start()
{
System.out.print('\u000C');
getMyNumItems();
getMyItemPrices();
output();
}
public int getMyNumItems()
{
System.out.print("How many items would you like to purchase? => ");
myNumItems = keyboard.nextInt();
return myNumItems;
}
public double getMyItemPrices()
{
int n = 0; //Disp item number
while(n < myNumItems)
{
System.out.print("Please enter price of item #" +(n+1) +": ");
myItemCost = keyboard.nextDouble();
myTotalCost = myTotalCost + myItemCost;
++n;
}
return myTotalCost;
}
public void output()
{
for(int n = 0; n < myNumItems; ++n)
{
System.out.println();
System.out.printf("%8s %8s %8s", "Item #" +(n + 1) , "Cost: $" +myItemCost, "Total: $" +myTotalCost);
}
}
}
How many items would you like to purchase? => 3
Please enter price of item #1: 1.25
Please enter price of item #2: 1.75
Please enter price of item #3: 1.50
Item #1 Cost: $1.5 Total: $4.5
Item #2 Cost: $1.5 Total: $4.5
Item #3 Cost: $1.5 Total: $4.5
答案 0 :(得分:1)
问题是你没有存储任何项目价格的引用,而是最后一项。这需要一个ArrayList来跟踪已经订购的每个项目。
如果不是使用你的int myItemCost,而是使用了ArrayList&lt; INT&GT; myItemCosts,每当你添加一个新项目时,你都会在该列表中添加所述价格,你可以在最后打印这些项目。
以下是一个例子:
ArrayList<int> myItemCosts = new ArrayList<int>();
public double getMyItemPrices()
{
int n = 0;
while (n < myNumItems)
{
System.out.print("Please enter price of item #" + (n+1) + ": ");
myItemCosts.add(keyboard.nextDouble());
myTotalCost += myItemCost;
}
}
然后output()可以这样构造:
public void output()
{
for(int n = 0; n < myNumItems; ++n)
{
System.out.println();
System.out.printf("%8s %8s %8s", "Item #" + (n + 1) , "Cost: $" + myItemCosts[n], "Total: $" + myTotalCost);
}
}
如果您决定需要为任何给定的杂货商品添加更多功能,例如SKU,数量,折扣等,您应该创建自己的对象来封装这些属性:
class SampleGroceryItem
{
public SampleGroceryItem(double price, int quantity, string sku, double discount)
{
this.Price = price;
this.Quantity = quantity;
this.Sku = sku;
this.Discount = discount;
}
public double Price;
public int Quantity;
public string Sku;
public double Discount;
}
然后在每次用户输入所有必要信息时实例化一个新的SampleGroceryItem,并将该对象添加到List中。