Separated expression string processing to its own method and created basic REPL
This commit is contained in:
parent
4a27d77713
commit
8234e92ce1
46
Program.cs
46
Program.cs
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user