循环后不记录变量?

时间:2014-10-08 02:57:03

标签: java variables if-statement reset

我正在编写一套简单的程序(客户和服务),用于计算银行账户的交易,以总提款和存款以及最终余额的摘要结束。但是,不是保持当前账户余额的运行选项卡,而是在每次循环后重置余额 - 例如,如果第一笔交易是500美元的存款,那么在该交易之后发布的当前余额将是准确的,但是在下一笔交易中(例如,提取75美元),当前余额将不计入之前的存款。下面是计算当前余额的代码模块,以及调用此模块的循环。这是我第一次在构造函数中声明变量,因此可能与错误有关。

public void computeCurrentBalance(){
   double deposit,withdrawal;

   if (choice == 'D' || choice == 'd'){
      System.out.print ("Enter amount of Deposit:   $");
      deposit = scan.nextDouble();
      currentBalance = initialBalance + deposit;
      totalDeposits = deposit + totalDeposits;
   }
   if (choice == 'W' || choice == 'w'){
         System.out.print ("Enter amount of Withdrawal:   $");
         withdrawal = scan.nextDouble(); 
         currentBalance = initialBalance - withdrawal;
         totalWithdrawals = withdrawal + totalWithdrawals;
   }
}
for (ctr = 0; ctr < 8; ctr++){
    accounts.enterChoice();
    accounts.computeCurrentBalance();
    currentBalance = accounts.getCurrentBalance();
    System.out.println ("Current Balance: $" + currentBalance);
}

1 个答案:

答案 0 :(得分:1)

computeCurrentBalance()始终设置currentBalance = initialBalance + depositcurrentBalance = initialBalance - withdrawal,而不会更改initialBalance。您需要更改这些语句以避免此问题。