This is a calculator I've made in C#. Is there any way to improve it? Surely there is a way to get rid of all the if
s that are nested inside one another.
namespace CalculatorCA
{
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, Func<double, double, double>> MyDict =
new Dictionary<int, Func<double, double, double>>();
FillDictionary(MyDict);
bool KeepOn = true;
while (KeepOn)
{
Console.WriteLine("Enter the first number!");
double first;
if (double.TryParse(Console.ReadLine(), out first))
{
Console.WriteLine("Please choose one of the following:\n1-Add\n2-Substract\n3-Multiply\n4-Divide");
int choice;
if (int.TryParse(Console.ReadLine(), out choice))
{
if (MyDict.ContainsKey(choice))
{
Console.WriteLine("Enter the second number!");
double second;
if (double.TryParse(Console.ReadLine(), out second))
{
Console.WriteLine("The result is : {0}", MyDict[choice](first, second));
}
}
else
{
Console.WriteLine("Invalid operation!");
}
}
}
Console.WriteLine("Continue?[Y/N]");
KeepOn = Console.ReadKey().Key == ConsoleKey.Y;
Console.Clear();
}
}
public static void FillDictionary(Dictionary<int,Func<double,double,double>> myDictionary)
{
myDictionary.Add(1, (x, y) => x + y);
myDictionary.Add(2, (x, y) => x - y);
myDictionary.Add(3, (x, y) => x * y);
myDictionary.Add(4, (x, y) => x / y);
}
}
}