下面是一个Java代码,它将具有多个大括号的输入infix表达式字符串和混合操作数和输出作为一个长后缀表达式。
我将infix表示法字符串转换为后缀,因为我希望消除所有的大括号,并尊重操作符的先导。支撑,除法,乘法,加法,减法。
这个程序工作不正常。例如:的输出:
9+3/4-(4/2)*(3+(5-2^2))
应该是
9 3 4/+4 2/3 5 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^-+-
发布于 2018-09-19 11:34:50
找到了我的解决方案。这就是了。diff修补程序应该是:
发布于 2018-10-12 12:34:51
如果您担心输出中没有空格(如果您的输入中有一个与"42“类似的多位值,您将无法从输出中得知它是"42”或“42”),那么在构建postFix字符串时插入空格:
更改:
postFix = postFix + stack.pop()至:
postFix = postFix + " " + stack.pop()(发生在几个地方-将其重构为自己的方法可能更好。)
https://stackoverflow.com/questions/52392350
复制相似问题