从Java中提取异常

从Java中提取异常,java,exception,Java,Exception,当我要求用户从其余额中提取金额时,我遇到了一个问题。我有一个叫做取款的方法,我通过了他们的余额。然后我想检查他们想要取款的金额是否少于他们的余额。如果是,我想让用户重试 到目前为止,它检查输入,但每次尝试我都会得到一个输出 public void withdraw (double balance){ System.out.println("How much would you like to withdraw?"); double amount = keyboard.nextDouble();

当我要求用户从其余额中提取金额时,我遇到了一个问题。我有一个叫做取款的方法,我通过了他们的余额。然后我想检查他们想要取款的金额是否少于他们的余额。如果是,我想让用户重试

到目前为止,它检查输入,但每次尝试我都会得到一个输出

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.0,新余额为50.0

我不想要下面的最后两个输出

您已提取500.0,新余额为-400.0您已提取200.0,新余额为-100.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
 }
 }
{ System.out.println(“您想提取多少?”); double amount=键盘.nextDouble(); 尝试 { 如果(金额<余额) { 余额=余额金额; System.out.println(“您已提取”+金额+,新余额为”+余额); } 其他的 抛出新的不正确的异常(); } 捕获(不正确) { System.out.println(e.getMessage()); 取款(余额);//如果继续输入错误的金额,则继续调用循环的方法 } }
您的问题解决了吗?如果是这样,请给出答案。如果您捕获了几行前刚刚抛出的异常,最好不要首先抛出它-使用If/else!对于在特定情况下不希望出现的指纹,再次使用if/else