Example #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome!\nOperations you can use: * / - + ()");
            ValidInput input = new ValidInput();

            if (input.isValid)
            {
                Console.WriteLine("result:\n" + (NormalExpression.Parse(input.input)).ToPreFixed().GetValue());
            }
            else
            {
                Console.WriteLine("invalidInput");
            }
        }
        public static new NormalExpression Parse(string input)
        {
            var  exp            = new NormalExpression();
            bool isPrevOperator = true;
            int  index          = 0;

            string[] strings = Regex.Split(input, @"[-+*/()]");
            foreach (char item in input)
            {
                switch (item)
                {
                case '+':
                    exp.items.Push(new Item(new Plus()));
                    isPrevOperator = true;
                    break;

                case '-':
                    exp.items.Push(new Item(new Minus()));
                    isPrevOperator = true;
                    break;

                case '*':
                    exp.items.Push(new Item(new Multiplicator()));
                    isPrevOperator = true;
                    break;

                case '/':
                    exp.items.Push(new Item(new Divisor()));
                    isPrevOperator = true;
                    break;

                case ')':
                    exp.items.Push(new Item(new OpenningParentheses()));
                    isPrevOperator = true;
                    break;

                case '(':
                    exp.items.Push(new Item(new ClosingParentheses()));
                    isPrevOperator = true;
                    break;

                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                case '.':
                    if (isPrevOperator)
                    {
                        for (; index < strings.Length; index++)
                        {
                            if (strings[index].Length != 0)
                            {
                                break;
                            }
                        }
                        var valid = double.TryParse(strings[index], out var doub);
                        if (valid)
                        {
                            exp.items.Push(new Item(doub));
                        }
                        index++;
                    }
                    isPrevOperator = false;
                    break;
                }
            }
            return(exp);
        }