public static float calculate(String postfixExpression){ List stack = new List(); float number1 = 0; float number2 = 0; float number = 0; String infixExpression = null; String ife = null; StringBuilder numberBuilder = new StringBuilder(); for(String obj : postfixExpression.split(",")){ if(Character.isDigit(obj.charAt(0))){ number = Float.parseFloat(obj); stack.pushToStack(number); }else{ number1 = stack.popFromStack(); number2 = stack.popFromStack(); float result = 0; switch (obj){ case "+": result = number1 + number2; break; case "-": result = number1 - number2; break; case "*": result = number1 * number2; break; case "/": result = number1 / number2; break; } stack.pushToStack(result); } infixExpression = Float.toString(number1) + obj + Float.toString(number2); ife += infixExpression; } System.out.println("The infixExpression is " + infixExpression); return stack.popFromStack(); }我的代码计算逆波兰式似乎有点问题,为什么我无法得出正确答案?
时间: 2023-06-20 14:09:02 浏览: 117
可能是因为您在计算中弹出栈的顺序有误。在计算逆波兰式时,应该先弹出的是第二个数,然后再是第一个数。因此,您需要交换弹出栈元素的顺序。修改以下代码:
```
number1 = stack.popFromStack();
number2 = stack.popFromStack();
```
改成:
```
number2 = stack.popFromStack();
number1 = stack.popFromStack();
```
这应该能够解决您的问题。
阅读全文