I want to create a console calculator in C#. The data is read from a file called expressions.txt. The columns of the file consist of two numbers and an operation. I want to calculate using only the operation symbols in the file, with numbers of my choice. If I give the input a stop, it stops iterating and then exits the program. I would also like to do error handling. For example: if there is no operator in the list, I want to get a "wrong operator" message. If I want to divide by 0, or if I enter a string instead of a number, I want to get "other error" messages. I did something wrong in error handling. I would like to ask for help in correct error handling. Here is my code:
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]);
}
}
Here is the expressions.txt for the exercise: