前缀表达式同时计算多个表达式

Prefix expression to evaluate multiple expressions simultaneously

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)。如何编辑提供的代码以使其计算多个表达式?感谢您的帮助。

为了简单地让您的程序多做一点,您可以使用循环来继续对 operandStack 进行操作,并将前一个结果的结果推送到堆栈。我留下了我的 println 语句,这样你就可以看到它在做什么。我还修改了您的方法,因此它可以放在独立的 main 方法中。

您应该研究调车场算法,实现起来很有趣,而且有点像您在这里所做的。 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()));