-2

所以在这个程序中有银行账户,我正在研究一种允许用户更改余额的方法,这就是我所拥有的:

   public double modifyBalance(int accountID, double adjustment) {
     Account temp = findAccount(accountID, 0, size, lastPos);
     double currBal = temp.getBalance();    
     if (temp!= null){      
        currBal = currBal + adjustment;
     }
     else {
           System.out.println("No account found. ");
        }


     return currBal;
  }

然而 currBal 的返回并没有更新实际账户的余额,我试过temp.getBalance() = currBal;但没有奏效,并给了我一个编译错误说:

OrderedVectorOfAccounts.java:95:错误:找不到符号
temp.getBalance = currBal;
        ^
符号:变量 getBalance
位置:Account
1 类型的变量 temp 错误

例如:如果帐户的余额是 200,我“存款”或添加 200,它应该是 400,但我所拥有的仍然是 200。
任何帮助都会很棒!谢谢!

这是我的 findAccount():

public Account findAccount(int accountID, int from, int to, int [] lastPos){
     if(from > to || (from+2)/2 >= size)
        return null;
     while(from <=to) {   
        if(accountID == theAccounts[(from+to)/2].getAccountNum())
           return theAccounts[(from + to)/2];
        else if (accountID>theAccounts[(from + to)/2].getAccountNum()){
          // return findAccount(accountID, (((from + to)/2)+1), to, lastPos);
           return theAccounts[accountID-1];
        }
        else if (accountID<theAccounts[(from + to)/2].getAccountNum()){
           //return findAccount(accountID, from, (((from + to)/2)-1),lastPos);
           return theAccounts[accountID-1];
        }
     }
     lastPos[0] = (from + to)/2;
     return null;
4

2 回答 2

0

您的modifyBalance方法只是更新currBal变量,使temp对象保持不变。temp这就是不更新'scurrentBalance变量的原因。为什么不直接删除所有这些混乱并创建一个简单的setBalance方法?

public void setBalance(double balance) { this.currentBalance = balance;   }

有了这个,你可以在代码中的任何地方调用:

 Account temp = findAccount(accountID, 0, size, lastPos); 
 if (temp!= null) {   
   temp.setBalance(temp.getBalance() + adjustment); //updates temp currentBalance
 } 
 else { System.out.println("No account found. "); }
于 2012-10-31T23:12:10.180 回答
0

由于您尚未发布代码的相关部分,我假设您temp.getBalance()正在返回0.0或您的findAccount()方法返回一个空的新Account()对象。

  public Account findAccount(yourparameters) {
      Account account = new Account();
       //do your finding logic
      return account;

如果说它没有找到帐户,它仍然会返回一个 Account 对象,因此

     double currBalc= temp.getBalance(); would return 0.0  

 if (temp!= null){  // your if passes here as temp is not null    
    currBal = currBal + adjustment;   0.0+200.0
 }
 else {
       System.out.println("No account found. ");
    }

更新您的 finfAccount() 后编辑

可能是您的调用getBalance()返回 0.0

double currBal = temp.getBalance();如果它打印你 200.0 那么你的温度是空的 。

于 2012-10-31T22:32:49.537 回答