我正在编写一个程序,用户可以输入一个金额(作为销售),输入他们是否想用现金或卡支付,然后询问他们是否想输入另一个金额(只是为了练习 Java 编程)。每当我输入金额并选择现金时,它应该告诉我到目前为止已记录的现金销售数量。但是,每当我在添加第一个金额后添加另一个金额时,现金销售计数仍然保持不变 (1)。此外,每当用户不再希望输入任何更多交易时,也应显示现金/卡交易的总额。另一个问题是现金总量不会累加,只显示最后输入的值。任何解决这些问题的帮助将不胜感激。这是两个类的代码:SalesRegister.javapackage Week2;public class SalesRegister { private int numCashSales; private double valueCashSales; private int numCardSales; private double valueCardSales; private String transactions; public SalesRegister() { this.numCashSales = 0; this.valueCashSales = 0.0; this.numCardSales = 0; this.valueCardSales = 0.0; this.transactions = ""; } public int getNumCashSales() { return this.numCashSales; } private void addTransaction(boolean isCash, double amount) { if (isCash) { transactions += "CASH SALE\t"; } else { transactions += "CARD SALE\t"; } transactions += amount + "\n"; } public void cashSale(double saleValue) { if (saleValue > 0.0) { System.out.println("Cash sale recorded."); valueCashSales += saleValue; numCashSales++; System.out.println(numCashSales); addTransaction(true, saleValue); } } public void cardSale(double saleValue) { if (saleValue > 0.0) { numCardSales++; valueCardSales += saleValue; addTransaction(false, saleValue); } } public String getTransactions() { String result = ""; result += "Cash Sales: " + numCashSales + " Total: " + valueCashSales + "\n"; result += "Card Sales: " + numCardSales + " Total: " + valueCardSales + "\n"; result += "Transaction List \n"; result += "+--------------+ \n"; result += transactions + "\n"; return result; }}最后,这是控制台的输出窗口:
1 回答
森栏
TA贡献1810条经验 获得超5个赞
SalesRegister您将在循环的每次迭代中创建一个新对象,从而重置存储的值。
您需要将构造函数移到 do-while-loop 之前,即
Scanner in = new Scanner(System.in);
SalesRegister register = new SalesRegister();
i=0;
do {
i=0;
...
添加回答
举报
0/150
提交
取消