2016-03-22 19 views
1

什麼,我試圖做的是設置一個透支額度,即-150用戶不能收回任何進一步的,如果他們的餘額爲-150。我的代碼如下:如何設置一個透支額度

withdraw方法

public void Withdraw(double amount){ 


    if (amount + 5 > balance){ //If amount and transaction fee is greater than balance then apply for overdraft 
     System.out.println("Insufficent funds"); 
     System.out.println("Would you like to apply for an ovedraft?"); 
     System.out.println("1:Yes"); 
     System.out.println("2:No, return me back to menus"); 
     Choice = Option.nextLine(); 
     if (Choice.equalsIgnoreCase("1")){ 
     if((balance = balance - amount+5)<=-150){ //If balance is grater than 150 , apply for overdraft 
      System.out.println("You have exceeded your Overdraft Limit, you will now be returned back to the menus"); 
     return; 

     } 
     else{ //if not exceeding bank balance 
      balance -= amount + 5; 
      System.out.println("You have withdrawen £" + amount); 
      System.err.println("You now have a balance of £" +balance); 
      return; 
     } 
    } 
} 

} 

他們都在同一個班,這是「帳戶」,現在情況是確實發生的信息 - (「您已超出透支限制,現在將返回到菜單「),並返回到菜單,但是當我去查餘額仍被扣錢,並顯示一個平衡,越過-150如。 -190我怎樣才能讓-150成爲限制而不是再減去。希望這個問題被理解。

+1

堆棧溢出降價的解釋變量,類引起你寫他們以大寫字母。啊。 – Gendarme

回答

4

這裏的問題:

if ((balance = balance - amount + 5) <= -150) { 

關鍵在這裏的是=。也就是說前檢查assigtning新的金額

像這樣的事情可能會避免此問題。

if (balance - amount - 5 < 0) { 
     System.out.println("Insufficent funds"); 
     System.out.println("Would you like to apply for an ovedraft?"); 
     System.out.println("1:Yes"); 
     System.out.println("2:No, return me back to menus"); 
     Choice = Option.nextLine(); 
     if (Choice.equalsIgnoreCase("1")) { 
      if (balance - amount - 5 <= -150) { 
       System.out.println("You have exceeded your Overdraft Limit, you will now be returned back to the menus"); 
      } else { //if not exceeding bank balance 
       balance -= amount + 5; 
       System.out.println("You have withdrawen £" + amount); 
       System.err.println("You now have a balance of £" + balance); 
      } 

通知的更明確的計算(if (balance - amount - 5 <= -150)),該乾式運行使用<= 0的數學和比較。這是通俗易懂的。

2

if((balance = balance - amount+5)<=-150)是你的問題。首先,你還沒有寫amount+5括號內,所以它應該是amount-5代替。其次,你實際上在這裏改變你的平衡(=是分配操作符)。你也寫了<=而不是<。什麼,你不是應該寫如下:

if(balance-(amount+5) < -150)

0

附加到所有的答案上面,我補充一點:

,如果我有1 $和我做的透支$ 50那麼我的帳戶可以在

1 $ -55 $ = -54 $

但這裏這個條件是不可能的

if (amount + FEES > balance) { // If amount and transaction fee is greater than balance then apply for overdraft 
System.out.println("Insufficent funds");