2012-10-21 85 views
1

我得到這個節目除了在Java中,如何添加每個循環的結果?

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); 
    } 
} 

回答

2

變化

profitandloss = unitssold*(price - unitcost); 

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

或等價

profitandloss += unitssold*(price - unitcost); 

原因您遇到的問題是因爲代替通過將積累最終答案到profitandloss每一次,你每次都用當前結果覆蓋profitandloss,所以最後你最終只打印最近的結果。

+0

甚至更​​好的使用StringBuilder :) – Pshemo

2

你要跟應該

profitandloss += unitssold*(price - unitcost); 

您在每次迭代覆蓋profitandloss更換

profitandloss = unitssold*(price - unitcost); 

相關問題