如果我输入一个负数,但它不起作用,则控制台应该引发异常。我在这里想念什么吗?

问题描述 投票:0回答:2
    public decimal CurrentBalance = 1000.00m;

    public decimal WithdrawCurrentAmount { get; set; }





    public decimal MakeWithdraw()
    {
        Console.WriteLine("How much would you like to withdraw from your Current account?", WithdrawCurrentAmount);

        if (WithdrawCurrentAmount < 0) 
        {
            throw new Exception("You cannot withdraw a negative amount" );               
        }

        WithdrawCurrentAmount = Convert.ToDecimal(Console.ReadLine());

        CurrentBalance = CurrentBalance - WithdrawCurrentAmount;
        Console.WriteLine("\nAvailable Current Balance is now: {0}", CurrentBalance);
        return CurrentBalance;     
c# if-statement exception throw
2个回答
2
投票

您必须将Convert行移至if语句之前,否则用户输入的值不会设置到您的测试变量中


1
投票

您应该在检查之前分配值:

WithdrawCurrentAmount = Convert.ToDecimal(Console.ReadLine()); // this line now is before checking 

if (WithdrawCurrentAmount < 0) 
{
   throw new Exception("You cannot withdraw a negative amount" );   
}

CurrentBalance = CurrentBalance - WithdrawCurrentAmount;
Console.WriteLine("\nAvailable Current Balance is now: {0}", CurrentBalance);

return CurrentBalance;  
© www.soinside.com 2019 - 2024. All rights reserved.