2013-11-28 149 views
0

我向用戶詢問要從餘額中提取的金額時遇到問題。我有一個叫撤回的方法,我通過他們的平衡。然後,我想檢查他們想要提取的金額是否低於餘額。如果是,我想讓用戶重試。撤銷異常Java

到目前爲止,它檢查輸入,但我不斷得到每次嘗試的輸出。

public void withdraw (double balance){ 
System.out.println("How much would you like to withdraw?"); 
double amount = keyboard.nextDouble(); 

try 
{ 
    if(amount > balance) 
    { 
     throw new IncorrectWithdrawException(); 
    } 
} 

catch(IncorrectWithdrawException e) 
{ 
    System.out.println(e.getMessage()); 
    withdraw(balance);// keeps calling the method for a loop if they keep entering incorrect amount 
} 

balance = balance-amount; 
System.out.println("You have withdrawn "+amount+ " and your new balance is "+balance); }} 

輸出:

什麼是你的平衡? 100 您要退出多少?200 ------錯誤------這不是一個有效的撤回金額。你想退出多少? 500 ------錯誤------這不是一個有效的撤回金額。你想退出多少? 50

您已經撤出50.0和新餘額爲50.0

我不希望下面的最後兩個輸出...

您已經撤出500.0和新餘額爲-400.0您已取消200.0,您的新餘額爲-100.0

+2

是否解決了您的[上一個問題](http://stackoverflow.com/q/20257052/418556)?如果是這樣,請[接受](http://meta.stackexchange.com/a/65088/155831)答案。 –

+0

如果您發現剛剛拋出幾行的異常,最好不要將它拋在第一位 - 請改用if/else!對於您不想在特定情況下出現的打印件,請再次使用if/else – alfasin

回答

0
public void withdraw (double balance) 
{ 
    System.out.println("How much would you like to withdraw?"); 
    double amount = keyboard.nextDouble(); 

    try 
    { 
    if(amount < balance) 
    { 
    balance = balance-amount; 
    System.out.println("You have withdrawn "+amount+ " and your new balance is "+balance); 
    } 
    else 
    throw new IncorrectWithdrawException(); 
    } 
catch(IncorrectWithdrawException e) 
{ 
    System.out.println(e.getMessage()); 
    withdraw(balance);// keeps calling the method for a loop if they keep entering incorrect amount 
} 
}