I got this program to work except for the
if (more == JOptionPane.NO_OPTION)
{
System.out.print("\nTotal profit/loss: $");
System.out.print(profitandloss);
}
section, at the end of the program it will only display the result of the final loop, rather than adding up all of the loops. For example, if the profit from each loop is 8 and if there are 4 loops, the total should be 32, but it’ll only display 8. Any ideas on how to fix this?
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);
}
}
change
to
or equivalently
The reason you’re experiencing the problem is because instead of accumulating a final answer by adding to
profitandlosseach time, you’re overwriting theprofitandlosswith the current result each time, so at the end you end up only printing the most recent result.