Joh*_*ohn 4 c# exception try-catch
我写了一个程序来模仿收银机的运作方式.
如果例如用户输入字母而不是数字,我需要一些关于如何使程序处理的帮助.
然后我希望用户输入的字母丢失,用户将获得从头开始的新机会.
我已经使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
热烈欢迎任何帮助.
Jon*_*eet 10
首先 - 更重要的是 - 对于货币价值,你应该使用decimal而不是double.十进制浮点数更适合货币值,货币值用十进制精确表示 - 而二进制浮点类型(double和float)更适合"自然"值,如高度和重量,无论如何绝不会有绝对精确的测量值.有关更多详细信息,请参阅有关二进制浮点和十进制浮点的文章.
接下来,我建议您使用decimal.TryParse- 而不是使用异常处理进行此验证,它会返回是否成功.这样你就不必使用try/catch来捕获一个可以轻易避免的非常可预测的异常.例如:
decimal value;
while (!decimal.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("Sorry, that wasn't a valid number");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1612 次 |
| 最近记录: |