【发布时间】:2013-11-28 04:13:45
【问题描述】:
当我向用户询问要从其余额中提取的金额时,我遇到了问题。我有一个叫做withdraw的方法,我通过了他们的余额。然后我想检查他们想要提取的金额是否小于他们的余额。如果是,我想让用户重试。
到目前为止,它会检查输入,但每次尝试都会得到输出。
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 ------ERROR----- 这不是一个有效的提款金额。你想取多少钱? 50
您已提取 50.0,您的新余额为 50.0
我不想要下面的最后两个输出...
您已提取 500.0,新余额为 -400.0 您已提取 200.0,新余额为 -100.0
【问题讨论】:
-
你的previous problem 解决了吗?如果有,请accept回答。
-
如果你捕捉到你刚刚在几行前抛出的异常,最好不要一开始就抛出它——使用 if/else 代替!至于你不想在特定情况下出现的打印,再次相应地使用 if/else