gpt4 book ai didi

java - 跟踪价格和总成本

转载 作者:行者123 更新时间:2023-12-01 12:21:23 25 4
gpt4 key购买 nike

我正在尝试跟踪每个项目的成本,并将其添加到所有项目的总成本中。当我运行程序时,最后一个项目成本和总成本将应用于每个项目。我觉得我应该有另一个循环更动态地放置每个项目的成本和总成本。

驱动程序类别:

    public class GroceryListTester
{
public static void main(String[] args)
{
GroceryList get = new GroceryList();
get.start();
}
}

CheckMail 类:

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

最佳答案

问题是您没有存储除最后一项以外的任何商品价格的任何引用。这需要一个 ArrayList 来跟踪已订购的每个项目。

如果您没有使用 int myItemCost,而是使用了 ArrayList< int> 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,并将该对象添加到列表中。

关于java - 跟踪价格和总成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26646164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com