我已经写了一个模拟收银机工作原理的程序。
我需要一些帮助如何使程序照顾,例如,如果用户输入字母而不是数字。
然后,我希望用户输入的字母丢失,用户将获得从头开始的新机会。
我已经使用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();
}
}任何帮助都会受到热情的欢迎。
发布于 2013-11-18 22:38:29
首先,也是更重要的是,对于货币值,您应该使用decimal而不是double。十进制浮点数更适合于货币值,而二进制浮点类型(double和float)更适合于身高和体重等“自然”值,这些值无论如何都不会有绝对精确的测量值。有关更多详细信息,请参阅我在binary floating point和decimal floating point上的文章。
接下来,我建议您使用decimal.TryParse来进行验证,而不是使用异常处理,它会返回是否成功。这样,您就不必使用try/catch来捕获可以轻松避免的非常可预测的异常。例如:
decimal value;
while (!decimal.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("Sorry, that wasn't a valid number");
}发布于 2013-11-18 22:38:10
您应该使用int.TryParse。如果输入不是有效的整数,则返回false。
如果返回false,则可以将其用作提示用户在中输入其他值的一种方式。
编辑
正如Jon Skeet所指出的,在处理货币时,你真的应该使用decimal类型。
发布于 2013-11-18 22:38:47
使用try parse:
decimal totalAmount;
bool ok = decimal.TryParse(outConsole.ReadLine(), out totalAmount);
if(!ok){
//Bad input. Do something
}else{
//input ok, continue
}使用相同的方法来解析整数。
https://stackoverflow.com/questions/20050359
复制相似问题