2

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*+.

Manishearth
  • 14,882
  • 8
  • 59
  • 76
Thomas
  • 23
  • 3

1 Answers1

1

Your

if ((inFixExp.charAt(i) == '*') || ...

checks charAt() but your getPredence(precedence?) checks for a String, try comparing against a char instead.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • You're welcome. Personally, I try not to use Object in method signatures since the Object super type might cause the user to lose track of typing. Although, in this case this is not very relevant. –  Nov 21 '10 at 22:19