C#运算运算的错误处理
Error handling of operation calculations with C#
我想用 C# 创建一个控制台计算器。从名为 expressions.txt 的文件中读取数据。
文件的列由两个数字和一个操作组成。
我只想使用文件中的操作符号和我选择的数字进行计算。
如果我停止输入,它将停止迭代,然后退出程序。我也想做错误处理。
例如:如果列表中没有运算符,我想得到一个“错误的运算符”消息。
如果我想除以 0,或者如果我输入字符串而不是数字,我想得到“其他错误”消息。
我在错误处理中做错了什么。
我想寻求有关正确错误处理的帮助。这是我的代码:
class Program
{
// 1.Reading:
static List<Expression> expressions = new List<Expression>();
static void Read()
{
string[] rows = File.ReadAllLines("expressions.txt");
foreach (var item in rows)
{
expressions.Add(new Expression(item));
}
}
//counting:
static void Calculator()
{
//string[] operators = { "div", "mod", "%", "/", "*", "-", "+" };
string counting = "";
string actionRequest = "";
while (actionRequest != "stop")
{
Console.Write("\nI need an action:");
actionRequest = Console.ReadLine();
if (actionRequest != "stop")
{
string[] data = actionRequest.Split(' ');
int firstNumber = int.Parse(data[0]);
string symbol = Convert.ToString(data[1]);
int secondNumber = int.Parse(data[2]);
try
{
counting = firstNumber + " " + symbol + " " + secondNumber;
switch (symbol)
{
case "mod":
actionRequest = counting + " = " + (firstNumber % secondNumber);
Console.WriteLine($"{counting} = {firstNumber % secondNumber}");
break;
case "div":
actionRequest = counting + " = " + (firstNumber / secondNumber);
Console.WriteLine($"{counting} = {firstNumber / secondNumber}");
break;
case "/":
actionRequest = counting + " = " + (Double.Parse(data[0]) / Double.Parse(data[2]));
Console.WriteLine($"{counting} = {Double.Parse(data[0]) / Double.Parse(data[2])}");
break;
case "*":
actionRequest = counting + " = " + (firstNumber * secondNumber);
Console.WriteLine($"{counting} = {firstNumber * secondNumber}");
break;
case "+":
actionRequest = counting + " = " + (firstNumber + secondNumber);
Console.WriteLine($"{counting} = {firstNumber + secondNumber}");
break;
case "-":
actionRequest = counting + " = " + (firstNumber - secondNumber);
Console.WriteLine($"{counting} = {firstNumber - secondNumber}");
break;
//default: // --> that's the fault.
// return ($"Bad operator!");
}
}
catch (Exception)
{
Console.WriteLine($"Other error!");
}
}
else
{
Console.Write("Exit ---> |press any key|");
break;
}
}
}
static void Main(string[] args)
{
Read();
Calculator();
Console.ReadKey();
}
}
Expression.cs:
class Expression
{
public int op1, op2;
public string operation;
// ctor
public Expression(string row)
{
op1 = Convert.ToInt32(row.Split()[0]);
operation = row.Split()[1];
op2 = Convert.ToInt32(row.Split()[2]);
}
}
这是练习的expressions.txt:
让我们先提取模型(所有可能的操作):
static Dictionary<string, Func<double, double, double>> s_Operations = new
Dictionary<string, Func<double, double, double>>(StringComparer.OrdinalIgnoreCase) {
{"+", (a, b) => a + b},
{"-", (a, b) => a - b},
{"*", (a, b) => a * b},
{"/", (a, b) => a / b},
{"%", (a, b) => a % b},
{"div", (a, b) => a / b - a % b}, // integer division
{"mod", (a, b) => a % b},
// Add more operations if required, e.g. "pow"
};
继续提取:我们准备实施Compute
:
static string Compute(string line) {
if (line == null)
return "null";
// The simplest; spaces are mandatory:
// "3 + 4" is valid, when "3 +4", "3+ 4", "3+4" are not
string[] items = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
// if we have exactly three items: double, func, double
// we can compute the formula
if (items.Length == 3 &&
double.TryParse(items[0], out var a) &&
s_Operations.TryGetValue(items[1], out var func) &&
double.TryParse(items[2], out var b))
return $"{string.Join(" ", items)} = {func(a, b)}";
else
return "Syntax error";
}
然后我们就可以轻松处理文件了...
static void Calulator() {
foreach (var line in File.ReadLines(@"c:\myFile.txt")) {
if (line.Trim() == "stop")
break;
Console.WriteLine(Compute(line));
}
}
请注意,在这种情况下,唯一可能的错误是 number / 0
即 +Inf
或 -Inf
和 0 / 0
即 NaN
(Not a N数).
...或执行控制台输入:
static void Calulator() {
while (true) {
Console.Write("\nI need an action:");
string actionRequest = Console.ReadLine().Trim();
if (actionRequest == "stop")
break;
Console.WriteLine(Compute(actionRequest));
}
}
我想用 C# 创建一个控制台计算器。从名为 expressions.txt 的文件中读取数据。 文件的列由两个数字和一个操作组成。 我只想使用文件中的操作符号和我选择的数字进行计算。 如果我停止输入,它将停止迭代,然后退出程序。我也想做错误处理。 例如:如果列表中没有运算符,我想得到一个“错误的运算符”消息。 如果我想除以 0,或者如果我输入字符串而不是数字,我想得到“其他错误”消息。 我在错误处理中做错了什么。 我想寻求有关正确错误处理的帮助。这是我的代码:
class Program
{
// 1.Reading:
static List<Expression> expressions = new List<Expression>();
static void Read()
{
string[] rows = File.ReadAllLines("expressions.txt");
foreach (var item in rows)
{
expressions.Add(new Expression(item));
}
}
//counting:
static void Calculator()
{
//string[] operators = { "div", "mod", "%", "/", "*", "-", "+" };
string counting = "";
string actionRequest = "";
while (actionRequest != "stop")
{
Console.Write("\nI need an action:");
actionRequest = Console.ReadLine();
if (actionRequest != "stop")
{
string[] data = actionRequest.Split(' ');
int firstNumber = int.Parse(data[0]);
string symbol = Convert.ToString(data[1]);
int secondNumber = int.Parse(data[2]);
try
{
counting = firstNumber + " " + symbol + " " + secondNumber;
switch (symbol)
{
case "mod":
actionRequest = counting + " = " + (firstNumber % secondNumber);
Console.WriteLine($"{counting} = {firstNumber % secondNumber}");
break;
case "div":
actionRequest = counting + " = " + (firstNumber / secondNumber);
Console.WriteLine($"{counting} = {firstNumber / secondNumber}");
break;
case "/":
actionRequest = counting + " = " + (Double.Parse(data[0]) / Double.Parse(data[2]));
Console.WriteLine($"{counting} = {Double.Parse(data[0]) / Double.Parse(data[2])}");
break;
case "*":
actionRequest = counting + " = " + (firstNumber * secondNumber);
Console.WriteLine($"{counting} = {firstNumber * secondNumber}");
break;
case "+":
actionRequest = counting + " = " + (firstNumber + secondNumber);
Console.WriteLine($"{counting} = {firstNumber + secondNumber}");
break;
case "-":
actionRequest = counting + " = " + (firstNumber - secondNumber);
Console.WriteLine($"{counting} = {firstNumber - secondNumber}");
break;
//default: // --> that's the fault.
// return ($"Bad operator!");
}
}
catch (Exception)
{
Console.WriteLine($"Other error!");
}
}
else
{
Console.Write("Exit ---> |press any key|");
break;
}
}
}
static void Main(string[] args)
{
Read();
Calculator();
Console.ReadKey();
}
}
Expression.cs:
class Expression
{
public int op1, op2;
public string operation;
// ctor
public Expression(string row)
{
op1 = Convert.ToInt32(row.Split()[0]);
operation = row.Split()[1];
op2 = Convert.ToInt32(row.Split()[2]);
}
}
这是练习的expressions.txt:
让我们先提取模型(所有可能的操作):
static Dictionary<string, Func<double, double, double>> s_Operations = new
Dictionary<string, Func<double, double, double>>(StringComparer.OrdinalIgnoreCase) {
{"+", (a, b) => a + b},
{"-", (a, b) => a - b},
{"*", (a, b) => a * b},
{"/", (a, b) => a / b},
{"%", (a, b) => a % b},
{"div", (a, b) => a / b - a % b}, // integer division
{"mod", (a, b) => a % b},
// Add more operations if required, e.g. "pow"
};
继续提取:我们准备实施Compute
:
static string Compute(string line) {
if (line == null)
return "null";
// The simplest; spaces are mandatory:
// "3 + 4" is valid, when "3 +4", "3+ 4", "3+4" are not
string[] items = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
// if we have exactly three items: double, func, double
// we can compute the formula
if (items.Length == 3 &&
double.TryParse(items[0], out var a) &&
s_Operations.TryGetValue(items[1], out var func) &&
double.TryParse(items[2], out var b))
return $"{string.Join(" ", items)} = {func(a, b)}";
else
return "Syntax error";
}
然后我们就可以轻松处理文件了...
static void Calulator() {
foreach (var line in File.ReadLines(@"c:\myFile.txt")) {
if (line.Trim() == "stop")
break;
Console.WriteLine(Compute(line));
}
}
请注意,在这种情况下,唯一可能的错误是 number / 0
即 +Inf
或 -Inf
和 0 / 0
即 NaN
(Not a N数).
...或执行控制台输入:
static void Calulator() {
while (true) {
Console.Write("\nI need an action:");
string actionRequest = Console.ReadLine().Trim();
if (actionRequest == "stop")
break;
Console.WriteLine(Compute(actionRequest));
}
}