我有一个购物清单,根据用户给我的价值,我必须更新总数。例如:
您可能已经注意到每次更新总数,我该如何在我的代码中执行此操作?
这就是我所拥有的:
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),但有一种方法可以在不指定确切值的情况下执行此操作,因此例如每次添加我们拥有的所有当前值。
答案 0 :(得分:0)
Scanner in = new Scanner(System.in);
System.out.println("Enter price of first item:");
product = in.nextDouble();
System.out.println("Enter price of second item:");
product += in.nextDouble();
System.out.println("Enter price of third item:");
product += in.nextDouble();
System.out.println("Enter price of fourth item:");
product += in.nextDouble();
System.out.println("Enter price of fifth item:");
product += in.nextDouble();
有更好的方法,但只是让你现在拥有的更容易就是这样。
答案 1 :(得分:0)
您可以简单地创建一个变量来保存项目的总价值,每次用户向列表中添加值时,它都会使用 + = 运算符添加到总计中。例如:
private double total;
添加到总数:
System.out.println("Enter price of second item:");
productTwo = in.nextDouble();
total += productTwo;
//call a method here to print the values to the table
用于打印值:
System.out.printf("%10d %10.2f %10.2f", n++ ,productTwo, total);
答案 2 :(得分:0)
您可以使用ArrayList
ArrayList<Double> costArray = new ArrayList<Double>();
double cost;
System.out.println("Enter price of first item:");
cost = in.nextDouble();
costArray.add(cost);
System.out.println("Enter price of second item:");
cost = in.nextDouble();
costArray.add(cost);
System.out.println("Enter price of third item:");
cost = in.nextDouble();
costArray.add(cost);
System.out.println("Enter price of fourth item:");
cost = in.nextDouble()
costArray.add(cost);
System.out.println("Enter price of fifth item:");
product += in.nextDouble();
costArray.add(cost);
double total = 0;
for (int i = 1; i <= costArray.length; i++) {
total += costArray[i];
System.out.printf("%10s %10.2f %10.2f", "#" + i, costArray[i], total);
}
total += costArray[i]
与total = total + castArray[i]
相同。