# Simple Calculator

unknown
csharp
a year ago
4.2 kB
7
Indexable
Never
```using System;
using System.Collections.Generic;

namespace Simple_Calculator
{
class FourOperatorsCalculator
{
//Description:
// - Enter an expression, example: 8.23 + 8.12
// - Check the expression's validity
// - Return the result
static void Main(string[] args)
{
//Causes Of Invalidity:
//- Invalid Operator Count
//- Invalid Types
//- Division by Zero
string quote = "Please enter a simple mathematic expression.";
char[] operators = new char[4]
{
'+', '-', '*', '/'
};
char operatorUsed;
while (true)
{
Console.WriteLine(quote);
quote = "Please enter a simple mathematic expression.";
string s = Console.ReadLine();
if (s == "\$exit") { break; }
Tools.RemoveCharsFromString(ref s, ' ');
operatorUsed = Tools.FindAndCountOperators(s, out int operatorCount, operators);
if ((operatorCount != 1) || (!(Tools.ArrayContains<char>(operators, operatorUsed))))
{
quote = "Please retry. Error: Invalid Operators or Invalid Operators Count";
continue;
}
string[] numberStrings = s.Split(operatorUsed);
double[] numbers = new double[numberStrings.Length];
bool hasOneFalse = false;
for (int i = 0; i < numberStrings.Length; i++)
{
bool isDouble = Double.TryParse(numberStrings[i], out numbers[i]);
if (!isDouble)
{
hasOneFalse = true;
}
}
if (hasOneFalse)
{
quote = "Please retry. Error: Invalid Numbers";
continue;
}
switch (operatorUsed)
{
case '+':
Console.WriteLine(numbers[0] + numbers[1]);
break;
case '-':
Console.WriteLine(numbers[0] - numbers[1]);
break;
case '*':
Console.WriteLine(numbers[0] * numbers[1]);
break;
case '/':
if (numbers[1] == 0)
{
quote = "Please retry. Error: Division by Zero.";
continue;
}
else
Console.WriteLine(numbers[0] / numbers[1]);
break;
}

}
}
}
static class Tools
{
public static void RemoveCharsFromString(ref string s, params char[] chars)
{
string result = "";
foreach (char charOfString in s)
{
if (!ArrayContains<char>(chars, charOfString))
{
result += charOfString;
}
}
s = result;
}

public static bool ArrayContains<T>(T[] container, T contained)
{
foreach (T containerMember in container)
{
if (EqualityComparer<T>.Default.Equals(containerMember, contained))
{
return true;
}
}
return false;
}

public static char FindAndCountOperators(string s, out int count, char[] operators)
{
char lastOperatorFound = '?';
count = 0;
int index = -1;
while ((index = s.IndexOfAny(operators, index + 1)) != -1)
{
count++;
if (index >= 0) { lastOperatorFound = s[index]; }
}
return lastOperatorFound;
}

}
}
```