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
解决方案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
}
}