撤销异常Java [英] Withdraw Exception Java

查看:152
本文介绍了撤销异常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); }}

输出:

你的平衡? 100
你想退出多少钱?200 ------错误------这不是有效的退款金额。你想退出多少钱? 500 ------错误------这是不是有效的退款金额。你想退出多少钱? 50

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

您已撤销50.0,您的新余额为50.0

You have withdrawn 50.0 and your new balance is 50.0


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

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

您已撤销500.0,您的新余额为-400.0您已撤销200.0,您的新余额为-100.0

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

这篇关于撤销异常Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆