繁体   English   中英

在Java中,如何添加每个循环的结果?

[英]In Java, how do I add the results from each loop?

我得到了这个程序,除了

if (more == JOptionPane.NO_OPTION)       
{
    System.out.print("\nTotal profit/loss: $");      
    System.out.print(profitandloss);
}

部分,在程序结束时,它只显示最终循环的结果,而不是累加所有循环。 例如,如果每个循环的利润为8,如果有4个循环,则总数应为32,但它只显示8.有关如何解决此问题的任何想法?

String productcode = null, purchased, cost, sold, salesprice, numberproducts = null;

double number = 1;
double profitandloss = 0;
int more;

System.out.println("Product code    units purchased  unit cost   units sold   units available   sales price  profit/loss");

double money;

for (int index = 1; index <= number; index++)
{
    productcode = JOptionPane.showInputDialog("Please enter the product code");
    int code = Integer.parseInt(productcode);

    purchased = JOptionPane.showInputDialog("Please enter the amount purchased");
    double unitspurchased = Double.parseDouble(purchased);

    cost = JOptionPane.showInputDialog("Please enter the cost of this item");
    double unitcost = Double.parseDouble(cost);

    sold = JOptionPane.showInputDialog("Please enter how many these items were sold");
    double unitssold = Double.parseDouble(sold);

    salesprice = JOptionPane.showInputDialog("Please enter the sales price for this item");
    double price = Double.parseDouble(salesprice);

    double available = unitspurchased - unitssold;
    profitandloss = unitssold*(price - unitcost);

    System.out.printf("P %2d %18.2f %18.2f %12.2f %12.2f %15.2f %15.2f", code, unitspurchased, unitcost, unitssold, available, price, profitandloss);
    System.out.println("");
    more= JOptionPane.showConfirmDialog(null, "Do you wish to enter any more products?", numberproducts, JOptionPane.YES_NO_OPTION);

    if (more == JOptionPane.YES_OPTION)
    {
        number++;
    }
    if (more == JOptionPane.NO_OPTION)
    {
        System.out.print("\nTotal profit/loss: $");
        System.out.print(profitandloss);
    }
}

更改

profitandloss = unitssold*(price - unitcost);

profitandloss = profitandloss + unitssold *(price - unitcost);

或者等价的

profitandloss += unitssold*(price - unitcost);

您所遇到的问题的原因是,而不是通过增加积累了最终的答案profitandloss每一次,你覆盖profitandloss与当前结果每一次,所以在最后你最终只打印最近的结果。

Yous应该替换

profitandloss = unitssold*(price - unitcost);

profitandloss += unitssold*(price - unitcost);

您在每次迭代时都会覆盖profitandloss

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM