简体   繁体   English

具有堆栈和符号表的表达式解析器

[英]Expression Parser with Stacks and Symbol Tables

First off, I'll be forthright in stating that this is a homework question. 首先,我将直言不讳地说这是一个作业问题。

I have to build an expression parser using the following code as my basis: Edit: 我必须使用以下代码构建表达式解析器: 编辑:

public class Interpreter {

public static Double parser(ST<String, Double> variables, String[] inputArray)
{       
    Double valueHolder;

    Stack<String> ops = new Stack<String>();
    Stack<Double> vals = new Stack<Double>();

    for(int i = 0; i < inputArray.length; i++)
    {
        String input = inputArray[i];

        if  (input.equals("("))                        ;
        else if (input.equals("+"))     ops.push(input);
        else if (input.equals("-"))     ops.push(input);
        else if (input.equals("*"))     ops.push(input);
        else if (input.equals("/"))     ops.push(input);
        else if (input.equals("sqrt"))  ops.push(input);

        else if (input.equals(")")) 
        {   
            String op = ops.pop();
            double v = vals.pop();
            if      (op.equals("+"))    v = vals.pop() + v;     
            else if (op.equals("-"))    v = vals.pop() - v;
            else if (op.equals("*"))    v = vals.pop() * v;
            else if (op.equals("/"))    v = vals.pop() / v;
            else if (op.equals("sqrt")) v = Math.sqrt(v);
            vals.push(v);
        }
        else if (input.matches("\\D"))
            {
                valueHolder = variables.get(inputArray[i]);
                vals.push(valueHolder);
            }
        else vals.push(Double.parseDouble(input));
    }

    return vals.pop();
}

public static String[] getValue(ST<String, Double> variables, String[] inputArray)
{
    Double keyHolder;
    Double valueHolder;

    for(int i = 0; i < inputArray.length; i++)
    {
        if(variables.contains(inputArray[i]))
            {
                keyHolder = variables.get(inputArray[i]);
                inputArray[i] = keyHolder.toString();
            }
        else if (!variables.contains(inputArray[i]))
        { if (inputArray[i].matches("\\D")) //if letter
            { if (!inputArray[i].equals("=")) //if not "="
                {for (int j = i + 1; j < inputArray.length; j++) //next element
                    { if (inputArray[j].matches("\\D")) //if letter
                        {if (!inputArray[j].matches("=")) //if not "="
                            {

                                //get values and do math
                            }
                        }
                    else if (inputArray[j].matches("\\d")) // if digit
                    { if (j + 1 >= inputArray.length)
                        {
                            valueHolder = Double.parseDouble(inputArray[j]);
                            variables.put(inputArray[i], valueHolder);
                        }
                      else parser(variables, inputArray); //if 
                    }
                    }
                }
            }

        }
    }

    return inputArray;
}

public static void main(String[] args)
{
    ST<String, Double> variables = new ST<String, Double>();

    while(!StdIn.isEmpty())
    {
        String input = StdIn.readLine();
        String[] inputArray = input.split("\\s+");          // read a line and split it by whitespace
        inputArray = getValue(variables, inputArray);       // remove any variables and replace with their associated values
        double y = parser(inputArray);  
        System.out.println(y);
    }

}

} }

Console input would be something like: 控制台输入如下所示:

A = 5
B = 10
C = A + B
D = C * C
print(D)

In this case, the output from the console would be 225. My problem is that I cannot figure out how to split the input between the symbol table's keys and values. 在这种情况下,控制台的输出为225。我的问题是我无法弄清楚如何在符号表的键和值之间分割输入。 The API for inputting keys and values is void put(Key key, Value v) where if a key is set to null, the key is removed. 用于输入键和值的API是void put(Key key, Value v) ,其中,如果键设置为null,则将其删除。 Thanks in advanced. 提前致谢。

It is not just string split, you need other checks too, like: 这不仅是字符串拆分,还需要其他检查,例如:

1) Split the string based on = pattern 1)根据=模式分割字符串

if(stringValue.matches("="))
{
 String[] valArray = stringValue.split("=");
}
else
{
// do something else
}

This will give you an array of string. 这将为您提供一个字符串数组。 Now loop through string array and check for below conditions. 现在循环遍历字符串数组,并检查以下条件。

2) Check if there is numeric value present 2)检查是否存在numeric

ie: valArray[].matches("\\d"); 即: valArray[].matches("\\d");

3) If numeric value is present, check if there is more than 1 occurrences of alphabet numeric values present (to see if there are more than 1 variables present) 3)如果存在numeric值,请检查是否存在超过1个alphabet numeric值(以查看是否存在超过1个变量)

This is to check if alphabet is present in any of split strings >> valArray[].matches("\\D"); 这是为了检查在拆分字符串中是否存在字母>> valArray[].matches("\\D");

4) Finally, if there is only 1 numeric value and 1 alphanumeric value present, store key and value. 4)最后,如果仅存在1个数字值和1个字母数字值,则存储键和值。

5) If there are more than 1 occurrences of empty variables, then you will need to skip the operation(plus, minus ...) until you have variable value present in key-value array. 5)如果空变量的出现次数超过1,则您将需要跳过该操作(加号,减号...),直到键值数组中存在变量值为止。

You can check this by checking your key-value pair array. You don't store key-value if the value if empty.

6) If = is not present then check for print in the string and do the print operation. 6)=不存在,则检查print的字符串中,并执行打印操作。

ie: 即:

if(stringValue.matches("print"));
{
//Do something
}

Note: stringValue is your console input line. 注意: stringValue是您的控制台输入行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM