如果我输入负数,控制台应该会抛出异常,但它不起作用.我在这里错过了什么吗?


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

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

还应使用Decimal.TryParse方法,以避免在用户输入"10 美元"或任何无法转换为十进制值的内容时出错。

在分配从控制台输入的值之前检查WithdrawCurrentAmount的值 - 默认值decimal0.0,因此您的if条件始终返回false;

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

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;  

此外,如果您输入的内容无法转换为decimal您将收到异常。

相关内容

最新更新