在Java中抛出异常 [英] Throwing Exception in Java

查看:131
本文介绍了在Java中抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我询问使用者从余额中扣除金额时,我遇到问题。
我有一个方法叫退出,我通过他们的余额。然后我想检查他们想要提取的金额是否少于他们的余额。如果是,我想让用户重试。



到目前为止,它检查输入,但是我每次尝试都会得到一个输出。

  public void withdraw(double balance)
{
System.out.println(你想退出?);
double amount = keyboard.nextDouble();

try
{
if(amount> balance)
{
throw new incorrectWithdrawException();
}
}
catch(incorrectWithdrawException e)
{
System.out.println(e.getMessage());
提款(余额); //如果持续输入不正确的金额,则继续调用该方法
}
balance = balance-amount;
System.out.println(您已撤销+金额+,您的新余额为+余额);
}

输出:



你的余额是多少? 100
你想退出多少钱?200
------错误------这不是有效的退款金额。
你想退出多少钱? 500
------错误------这不是有效的退款金额。
你想退出多少钱?您已经撤回50.0,您的新余额为50.0
您已撤回500.0,您的新余额为-400.0
您已撤销200.0和你的新余额是-100.0



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

解决方案

当金额>余额时,您已经通过用户的下一个输入作为新的余额,这是非常有问题的...用户可以欺骗余额


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 You have withdrawn 500.0 and your new balance is -400.0 You have withdrawn 200.0 and your new balance is -100.0

I do not want the last two outputs...

解决方案

when amount > balance, you've passed user's next input as new balance, which is very problematic... user can cheat the balance

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

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