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
的值 - 默认值decimal
为0.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
您将收到异常。