【发布时间】:2013-11-18 14:36:07
【问题描述】:
我编写了一个程序来模拟收银机的工作方式。
如果用户输入字母而不是数字,我需要一些帮助来处理程序。
然后我希望用户输入的字母丢失并且用户获得从头开始的新机会。
我已经使用 try 和 catch 为其编写了一些代码,但不确定应该如何编写。
class Program
{
static void Main(string[] args)
{
int cash = 0;
double totalAmount = 0;
uint subTotal;
int exchange;
double roundingOffAmount;
Console.Write("Please enter a total amount for the cash register : ");
totalAmount = double.Parse(Console.ReadLine());
if (totalAmount < 1)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("\nTotalamount needs to be more\n");
Console.ResetColor();
Environment.Exit(0);
}
try
{
Console.Write("Please enter cash for the cash register: ");
cash = int.Parse(Console.ReadLine());
if (cash < totalAmount)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("\nCash needs to be more than totalAmount\n");
Console.ResetColor();
Environment.Exit(0);
Console.WriteLine();
}
else
{
// Do nothing
}
}
catch (FormatException)
{
Console.Write("\nSorry you typed in a letter you need to type in a number");
Console.WriteLine();
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("\nSomething went wrong, please try again");
Console.ResetColor();
Console.WriteLine();
Main(args);
}
subTotal = (uint)Math.Round(totalAmount);
roundingOffAmount = subTotal - totalAmount;
exchange = cash - (int)totalAmount;
Console.WriteLine("\n Receipt"
+ "\n ------------------------------------"
+ "\n Totalt \t: \t {0:c}", totalAmount);
Console.WriteLine(" RoundingOffAmount\t: \t {0:f2}", roundingOffAmount);
Console.WriteLine(" To pay \t: \t {0:c}", subTotal);
Console.WriteLine(" Cash \t: \t {0:c}", cash);
Console.WriteLine(" Exchange \t:\t {0:c}", exchange
+ "\n ------------------------------------");
Console.WriteLine();
}
}
热烈欢迎任何帮助。
【问题讨论】:
-
尝试使用
TryParse()方法msdn.microsoft.com/en-us/library/… -
这仍然是一个控制台应用程序吗?您应该在前端和后端的两个级别上添加此检查。后端应该简单地抛出一个异常,因为它通常不应该被访问(前端不应该允许用户尝试提交错误的数据)。如果这最终将是一个网站/WPF 应用程序/...,那么您最好在此时添加验证。
-
提示:查找 TryParse