运算符在以字符串形式给出的中缀表达式的后缀表示法的输出中放错了位置



这是一个 Java 代码,它将具有多个大括号级别的输入中缀表达式字符串作为输入,并将操作数和输出混合为一个长后缀表达式。

我将中缀表示法 String 转换为后缀,因为我想消除所有大括号并尊重运算符优先级。大括号、除法、乘法、加法和减法。

此程序无法正常工作。例如,输出:

"9+3/4-(4/2(*(3+(5-2^2((">

应该是

9 3 4/+ 4 2/3 5 2 2 ^ - + * -

(根据本网站(

但给我:

934/+42/*3522^-+-

为什么会有这种错误的输出?是否有可能找到问题?

import java.util.ArrayList;
import java.util.Stack;
class infixToPostfix{
Stack<String> stack;
ArrayList<String> operators;
String postFix;
int[] operand = {-1, -1, 1};
int[] plusorminus = {1,2,-1};
int[] timesordivide = {3,4,-1};
int[] raiseto = {6,5,-1};
int[] openparenthesis = {-1,0,-1};
public infixToPostfix(String infix) {
stack = new Stack<String>();
operators = new ArrayList<String>();
operators.add("+");
operators.add("-");
operators.add("x");
operators.add("/");
operators.add("^");
operators.add("(");
operators.add(")");
postFix = new String();
while(infix.length() > 0){
String operand = new String();
String operator = new String();
if(!operators.contains(infix.substring(0, 1))){
while(!operators.contains(infix.substring(0, 1)) && !infix.isEmpty()){
operand = infix.substring(0,1);
infix = infix.substring(1);
}
postFix = postFix + operand;
}
else if(operators.get(5).equals(infix.substring(0, 1))){
stack.push(infix.substring(0, 1));
infix = infix.substring(1);
}
else if(operators.get(6).equals(infix.substring(0, 1))){
while(!stack.peek().equals("(")){
postFix = postFix + stack.pop();
}
stack.pop();
infix = infix.substring(1);
}
else{
operator = infix.substring(0,1);
int[] current = getICPandISP(operator);
if(!stack.isEmpty()){
int[] top = getICPandISP(stack.peek());
while(current[0] < top[1] && !stack.isEmpty()){
postFix = postFix + stack.pop();
if(!stack.isEmpty())
top = getICPandISP(stack.peek());
}
}
stack.push(operator);
infix = infix.substring(1);
}
}
postFix = postFix + infix;
while(!stack.isEmpty()){
postFix = postFix + stack.pop();
}
}
public String toString(){
return postFix;
}
private int[] getICPandISP(String operator){
if(operator.equals("+") || operator.equals("-")){
return plusorminus;
}
else if(operator.equals("*") || operator.equals("/")){
return timesordivide;
}
else if(operator.equals("^")){
return raiseto;
}
else{
return openparenthesis;
}
}
public static void main(String[] args){
infixToPostfix convert = new infixToPostfix("9+3/4-(4/2)*(3+(5-2^2))");
//"A+B/C-(A/D)*(A+(C-E^F))");
System.out.println(convert);
}
}

输出为:

934/+42/*3522^-+-

找到了我的解决方案。在这里。差异补丁应该是:

- 运算符.add("x"(;

+ 运算符.add("*"(;

如果您担心输出中没有间距(如果您的输入中有像"42"这样的多位数值,您将无法从输出中知道它是"42"还是"4 2"(,请在构建 postFix 字符串时插入空格:

改变:

postFix = postFix + stack.pop()

自:

postFix = postFix + " " + stack.pop()

(发生在多个地方 - 最好重构到它自己的方法中。

最新更新