当我要求用户从余额中提取金额时,我遇到了问题。我有一个名为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 ------错误------这不是一个有效的退出金额。你要退多少钱? 50
您已撤回50.0且新余额为50.0
我不希望下面的最后两个输出......
您已撤回500.0且您的新余额为-400.0您已撤回200.0并且您的新余额为-100.0
答案 0 :(得分: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
}
}