从具有运算符优先级的文本框计算字符串

时间:2015-03-03 12:10:13

标签: c# visual-studio calculator

按钮代码: 我的按钮中的所有代码都填充了文本框,其中包含数字的字符串表示形式。

    private void button9_Click(object sender, EventArgs e)
    {

        if ((screenBox.Text == "0") || (opr))
        {
            screenBox.Clear();

        }
        opr = false;
        screenBox.Text = screenBox.Text + button9.Text;
    }

操作员代码: 操作员代码完全相同。

    private void buttonAdd_Click(object sender, EventArgs e)
    {
        operation = buttonAdd.Text;
        screenBox.Text =screenBox.Text +" "+ operation +" ";

    }

等于: 现在,当我按下等号时。

    public void buttonEq_Click(object sender, EventArgs e)
    {

        operation = buttonEq.Text;
        screenBox.Text = " " + screenBox.Text + " " + operation;

        string splitUp;  //stores elements of the original string
        string expr = screenBox.Text;   //makes expr whatever is in textbox

        string[] ops;//makes array called ops

        ops = expr.Split( '(', ')', '^', '/', '*', '+', '-', '='); 
        //splits expr which contains the string input to the screenbox                             
        //using any operator as a token (unless i'm confused and you don't  
        //all them tokens with this method) 

        foreach(string op in ops)
        {
            splitUp = op;
            Console.WriteLine(op);
        }
        //string split up holds whatever is in op, which is a string that  
        //contains an element of ops, which is the array that indexes the  
        //elements of the original string
        //eg 5+5= in the text box would appear as        in the console.                      
                                                //5 
                                                //5

我现在应该如何解决这个问题,以便我的程序能够理解它已经拆分了,所以它需要在+之前和之后添加两个数字+(或'*','/',' - ')但要在执行计算之前检查操作员右侧的“(”“)”括号并收集该序列的总和第一类

我只想了解我应该采用什么样的逻辑。

1 个答案:

答案 0 :(得分:0)

好吧,所以我对被告知只是包含一个库而不是体验创建我自己的解析器的学习曲线感到很失望。

因此。它很长,我决不会得到一个高级解析器,但到目前为止它做的基本操作就像在我设置的优先级序列中操作数字等。

所以我不会详细说明,但基本上我会说有什么对我有所帮助。

  1. 准备 您将需要对堆栈,队列,列表,数组的基本了解以及如何构建Tokenization类的搜索(对于此类,您将需要了解Enums" Token"数据类型和获取函数)您将需要研究" Shunting Yard算法"和#34;反向波兰表示法" &安培;如何融入编程HEAVILY

  2. 构建令牌化类 一旦你理解了如何有效地对字符串进行Tokenize,也就是说,取一串输入并编辑它以包含适当的Tokens,或者实现一种技术,其中标记自动成为输入的一部分,并且需要对原始字符串进行最少的编辑。您应该研究如何构建一个好的Tokenization类。并尝试它。

  3. 2.5:没有错误=继续

    3.Shunting Yard和Reverse polish符号将通过使用Tokenization类中的元素和数据类型以及步骤1但来自表单类来实现。

    标记化类将包含诸如优先级关联等内容的所有信息。

    4.如果您的分流码算法在您的表单类中成功实现,则可以将反向波兰表示法合并到由Shunting Yard算法输出的运算符和操作数

    我是新手,很抱歉,我无法详细解释或者如果我犯了错误,请突出并纠正我!