2014-05-09 89 views
2

我想問一個問題。如果金額大於餘額,則必須退還餘額並將餘額設置爲零。我該怎麼做?我嘗試了很多不同的方法來解決這個問題,但它沒有奏效。謝謝你的幫助。如何返回並設置爲零?

public class BankAccount { 
    double balance; 

    BankAccount(double openingBalance){ 
     balance=openingBalance; 
    } 
     public double getBalance(){ 
     return balance; 
    } 
    public void deposit(double amount){ 
     balance += amount; 
    } 
    public double withdraw (double amount){ 
     if (balance > amount){ 
      balance -= amount; 
     }else if (amount > balance || amount == balance){  
      **return balance; 
      balance = 0** 
     } 
     return amount; 
    } 
} 

Driver類

public class Driver { 

    static BankAccount acc3; 

    public static void main (String[] args){ 
     BankAccount acc3 = new BankAccount ("Alana","Neil", 5000); 
     System.out.println("\nName: " +acc3.Name()); 
     System.out.println("Amount: $" +acc3.balance); 
     acc3.deposit(100); 
     System.out.println("Deposit Amount: $" +acc3.balance); 
     System.out.println("Withdrawl Amount: $"+acc3.withdraw(5400)); 
     System.out.println("The New Balance: $" +acc3.balance); 

    } 
} 

回答

5

使用一個臨時變量:

double tmp = balance; 
balance = 0; 
return tmp; 
0

,如果你只是沒有編碼你的意思(改變量時餘額不這樣會更簡單足夠):

public double withdraw (double amount){ 
    if (amount > balance) { 
     amount = balance; 
    } 
    balance -= amount; 
    return amount; 
} 
0

else部分可以是:

} 
else { 
    amount = this.balance; 
    this.balance = 0; 
} 

所以你符合要求返回僅爲可撤銷的平衡,同時也餘額爲零。

0

首先你不需要返回金額,因爲你將它傳遞給方法。 而你想回來?金額大的還是可以退款的錯誤? 和方法:

public double withdraw (double amount){ 
    if (balance > amount){ 
     balance -= amount; 
    }else{ //no need for second if since we check in first 
      // if amount is smaller then balance 
     // if you whant to withdraw all money 
     return balance = 0; // 
     // or return -1 and in balance method change if balance = -1 you are broke 
     return balance = -1; 
    } 
    return balance; 
} 
0
public double withdraw (double amount){ 

    double toReturn = amount; 

    if (balance > amount){ 
     balance -= amount; 
    } 
    else if (amount > balance) { 
     toReturn = balance;  
     balance = 0; 
    } 
    else if (amount == balance){ 
     balance = 0; 
    } 
    return toReturn; 
}