我有一个购物清单,根据用户给我的值,我必须更新总数。例如:
您可能已经注意到总数每次都会更新,我该如何在我的代码中做到这一点?
这就是我所拥有的:
public class CalcGroceryList {
private double productOne;
private double productTwo;
private double productThree;
private double productFour;
private double productFive;
private int n++;
public CalcGroceryList(){
Scanner in = new Scanner(System.in);
System.out.println("Enter price of first item:");
productOne = in.nextDouble();
System.out.println("Enter price of second item:");
productTwo = in.nextDouble();
System.out.println("Enter price of third item:");
productThree = in.nextDouble();
System.out.println("Enter price of fourth item:");
productFour = in.nextDouble();
System.out.println("Enter price of fifth item:");
productFive = in.nextDouble();
}
public double calc(){
return productOne + productTwo + productThree + productFour + productFive;
}
public void printResults(){
System.out.printf("%10s %10s %10s \n", "Item:", "Cost:", "Price:");
System.out.printf("%10d %10.2f %10.2f \n", n++ ,productOne, productOne);
System.out.printf("%10d %10.2f %10.2f", n++ ,productTwo, productTwo + productOne);
}
}
System.out.printf("%10d %10.2f %10.2f", n++ ,productTwo, productTwo + productOne);
正如您在此处看到的,我只是添加了两个值(productTwo + productOne),但是有没有一种方法可以在不指定确切值的情况下执行此操作,例如,每次添加我们拥有的所有当前值。