在Java中抛出异常

时间:2013-11-28 03:11:48

标签: java exception

当我要求用户从余额中提取金额时,我遇到了问题。 我有一个名为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

我不想要最后两个输出......

3 个答案:

答案 0 :(得分:2)

不要在方法中使用异常作为一种偷偷摸摸的忍者方式来影响if / then条件代码:这不是他们的目的。例外是对无法检查的异常情况的最后防御。您的代码具有完全正常的描述和完全正常的行为。坚持正常if / then

public void withdraw (double balance)
{
  double amount;
  do
  {
    System.out.println("How much would you like to withdraw?");
    amount = keyboard.nextDouble();
    if (amount > balance)
    {
      System.out.println("I'm sorry, you cannot overdraw, please pick a lower withdrawal amount.");
    }
  }
  while(amount > balance);

  // Although you probably want to say something like
  // "or type 0 not to withdraw anything", to be nice.

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

答案 1 :(得分:0)

一个重要的注意事项:

您应检查余额以确保其大于或等于0.

(假设你不会让负平衡发生。)

答案 2 :(得分:0)

当金额>平衡,你已经将用户的下一个输入作为新余额传递,这是非常有问题的...用户可以欺骗平衡