java撤销一步,撤销异常Java

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值