Separated expression string processing to its own method and created basic REPL

This commit is contained in:
Dmitriy Shishkov 2021-08-08 19:03:15 +03:00
parent 4a27d77713
commit 8234e92ce1
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060

View File

@ -8,11 +8,25 @@ namespace calculator
static void Main(string[] args)
{
if (args.Length == 0)
Console.WriteLine("REPL is not ready yet. Please, provide mathematic expression as an argument");
{
string input = readREPL();
while (input != null)
{
writeREPL(evaluate(input));
input = readREPL();
}
}
else
{
writeREPL(evaluate(args[0]));
}
}
static private double evaluate(string s)
{
try
{
string[] expr = args[0].Split();
string[] expr = s.Split();
Stack<double> st = new Stack<double>();
for (int i = 0; i < expr.Length; i++)
@ -56,11 +70,13 @@ namespace calculator
else throw new Exception("Stack corrupted");
}
Console.WriteLine(st.Pop());
return st.Pop();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Environment.Exit(1);
return -1;
}
}
@ -71,5 +87,29 @@ namespace calculator
else if (s.Length == 1) return s[0];
else throw new Exception("Got multiple characters operator");
}
static private string readREPL()
{
Console.Write(">> ");
string input = Console.ReadLine();
switch (input)
{
case "exit":
case "exit()":
case "quit":
case "quit()":
case "q":
case "":
return null;
default:
return input;
}
}
static private void writeREPL<T>(T o)
{
Console.WriteLine(o);
}
}
}