问题
i recently wrote a java program that takes an infix expression and converts it into a postfix expression. It works for the most part but i am getting wrong outputs for some expressions. For example the expression a+b+c+d+e will output abcde+++++ when it should output a b + c + d + e +.
import java.util.Stack;
public class ITP {
public static Stack<Character> stack;
public static String inFixExp;
public static String postFixExp = "";
public static String infixToPostfix(String exp){
ITP o = new ITP();
stack = new Stack<Character>();
inFixExp = exp;
for (int i = 0; i < inFixExp.length(); i++) {
if (inFixExp.charAt(i) == '(')
stack.push(inFixExp.charAt(i));
else if (inFixExp.charAt(i)==')'){
while (stack.peek()!='('){
postFixExp += stack.pop();
}
stack.pop();
}else if ((inFixExp.charAt(i)=='*')||(inFixExp.charAt(i)=='/')||(inFixExp.charAt(i)=='+')||(inFixExp.charAt(i)=='-')){
while(!stack.isEmpty() && o.getPredence(inFixExp.charAt(i)) < o.getPredence(stack.peek()))
postFixExp += stack.pop();
stack.push(inFixExp.charAt(i));
}else
postFixExp += inFixExp.charAt(i);
}
while(!stack.isEmpty())
postFixExp += stack.pop();
return postFixExp;
}
public int getPredence(Object op) {
if((op.equals("*")) || (op.equals("/")))
return 3;
else if((op.equals("+"))||(op.equals("-")))
return 1;
else
return 0;
}
}
I found out that if i change the < with <= in line 24 it will fix this problem but then i will get an empty stack error and some other expressions will output incorrectly, such as a+b*c which will output ab+c*, when it is supposed to be abc*+.
回答1:
Your
if ((inFixExp.charAt(i) == '*') || ...
checks charAt()
but your getPredence(precedence?)
checks for a String
, try comparing against a char
instead.
来源:https://stackoverflow.com/questions/4240595/getting-wrong-outputs-in-infix-to-postfix-application-with-java