-4

这是我的课:

class EmpDetails
{
    private string _EmpName;
    private int _EmpID;
    private string _EmpDepartment;
    private string _EmpPosition;
    private decimal _Balance;
    private static int _PrevId;

    public static decimal MinBalance; //This memeber is not working as required


    **public void Withdraw(decimal amount) // The Problem is in this method**
    {
        if (this.Balance < MinBalance)
        {
            throw new ApplicationException("Insufficient funds");
        }
        else
        {
            this._Balance -= amount;
        }
    }
}

我已经强调了Withdraw我认为会产生问题的方法。假设检查余额是否小于最小余额并抛出异常。假设当我将 MinBalance 设置为 500 并将 Balance 设置为 1000,然后尝试从 1000 中提取 600 时,它应该抛出一个异常,说余额不足,但它在第一次运行时不起作用,而是在我尝试提取时起作用第二次。

4

3 回答 3

1

You'll have to check not your currente Balance but how your Balance will be after you Withdraw, thats why it is not working as you expect, you can do it like this:

public void Withdraw(decimal amount) // The Problem is in this method**
{
    if ( ( this.Balance - amount ) < MinBalance)
    {
        throw new ApplicationException("Insufficient funds");
    }
    else
    {
        this._Balance -= amount;
    }
}
于 2012-12-01T15:45:58.403 回答
1

If you step through your code, you'll see the problem. Set a breakpoint on the line if (this.Balance < MinBalance). The first time through, the balance (1000) is higher than the minimum balance (600), so the withdrawal is allowed. It sounds like you really want to check the remaining balance, not the starting balance.

于 2012-12-01T15:46:12.207 回答
1

IF I understand your description of the problem right, you want to block people from reducing your balance to below your min balance.

    public void Withdraw(decimal amount) // The Problem is in this method**
    {
        if (this.Balance < MinBalance)
        {
            throw new ApplicationException("Insufficient funds");
        }
        else
        {
            this._Balance -= amount;
        }
    }

But you're not factoring the withdrawal into that equation. change your condition to

if (this.Balance - amount < MinBalance)
{
于 2012-12-01T15:46:30.727 回答