前缀表达式以同时评估多个表达式

时间:2015-04-12 21:01:05

标签: java expression

private class InputListener implements ActionListener
    {
      public void actionPerformed(ActionEvent e)
      {
         Stack<Integer> operandStack = new Stack<Integer>();
         Stack<Character> operatorStack = new Stack<Character>();

         String input = inputTextField.getText();

         StringTokenizer strToken = new StringTokenizer(input, " ", false);


         while (strToken.hasMoreTokens())
         {
             String i = strToken.nextToken();
             int operand;
             char operator;

             try
             {
                 operand = Integer.parseInt(i);
                 operandStack.push(operand);
             }
             catch (NumberFormatException nfe)
             {
                 operator = i.charAt(0);
                 operatorStack.push(operator);
             }
          }
          int result = sum (operandStack, operatorStack);
          resultTextField.setText(Integer.toString(result));
       }

我的前缀表达式代码一次只会评估一个表达式(即+ 3 1)。我希望它在一个用户输入表达式中评估多个表达式(即* + 16 4 + 3 1)。如何编辑提供的代码以使其评估多个表达式?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

要简单地让程序执行更多操作,您可以使用循环来继续操作operandStack并将前一个结果的结果推送到堆栈。我留下了println语句,以便您可以看到它的作用。此外,我修改了您的方法,使其可以位于独立的main方法中。

你应该研究一下Shunting-yard算法,实现它很有趣,它有点像你在这里做的。 http://en.wikipedia.org/wiki/Shunting-yard_algorithm

public static void main(String[] args) {
    Stack<Integer> operandStack = new Stack<Integer>();
    Stack<Character> operatorStack = new Stack<Character>();

    String input = "12 + 13 - 4";

    StringTokenizer strToken = new StringTokenizer(input, " ", false);

    while (strToken.hasMoreTokens()) {
        String i = strToken.nextToken();
        int operand;
        char operator;

        try {
            operand = Integer.parseInt(i);
            operandStack.push(operand);
        } catch (NumberFormatException nfe) {
            operator = i.charAt(0);
            operatorStack.push(operator);
        }
    }

    // loop until there is only 1 item left in the operandStack, this 1 item left is the result
    while(operandStack.size() > 1) {
        // some debugging println
        System.out.println("Operate\n\tbefore");
        System.out.println("\t"+operandStack);
        System.out.println("\t"+operatorStack);

        // perform the operations on the stack and push the result back onto the operandStack
        operandStack.push(operate(operandStack, operatorStack));

        System.out.println("\tafter");
        System.out.println("\t"+operandStack);
        System.out.println("\t"+operatorStack);
    }

    System.out.println("Result is: " + operandStack.peek());
}

/**
 * Performs math operations and returns the result. Pops 2 items off the operandStack and 1 off the operator stack. 
 * @param operandStack
 * @param operatorStack
 * @return
 */
private static int operate(Stack<Integer> operandStack, Stack<Character> operatorStack) {
    char op = operatorStack.pop();
    Integer a = operandStack.pop();
    Integer b = operandStack.pop();
    switch(op) {
        case '-':
            return b - a;
        case '+':
            return a + b;
        default:
            throw new IllegalStateException("Unknown operator '"+op+"'");
    }
}

我将operate方法(以前称为sum)尽可能接近你所拥有的方法,但我认为只需将2个整数和一个运算符传递给功能。使功能改变你的堆栈不是一件好事,可能会导致令人困惑的问题。

请考虑改为使用此方法签名:

private static int operate(Integer a, Integer b, char operator) {
    switch(operator) {
        case '-':
            return b - a;
        case '+':
            return a + b;
        default:
            throw new IllegalStateException("Unknown operator '"+operator+"'");
    }
}

然后从堆栈中弹出并将它们传递给方法。保持堆栈在一个地方改变代码。

operandStack.push(operate(operandStack.pop(), operandStack.pop(), operatorStack.pop()));
相关问题