Withdraw Exception Java

不想你离开。 提交于 2019-12-25 02:42:23

问题


I have a problem when I ask the user for the amount to be withdrawn from their balance. I have a method called withdraw, and i pass their balance. Then I want to check if the amount that they want to withdraw is less than their balance. If yes, I would like to make the user to retry.

So far, it checks for the input but i keep getting an output for each try.

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); }}

Output:

What is your balance? 100 How much would you like to withdraw?200 ------ERROR------ That is not a valid amount to withdraw. How much would you like to withdraw? 500 ------ERROR------ That is not a valid amount to withdraw. How much would you like to withdraw? 50

You have withdrawn 50.0 and your new balance is 50.0

I do not want the last two outputs below...

You have withdrawn 500.0 and your new balance is -400.0 You have withdrawn 200.0 and your new balance is -100.0


回答1:


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
 }
 }


来源:https://stackoverflow.com/questions/20257570/withdraw-exception-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!