Infix to Postfix Notation Parentheses issue

108 Views Asked by At

So I am currently working on a project to convert infix to postfix notation and I am almost finished with the project. It correctly converts infix to postfix until I try adding parentheses it ends up incorrectly formatted.

static int precedence(String c){
        switch(c){
            case"+":
            case"-":
                return 1;
            case"*":
            case"/":
                return 2;
            default:
                return -1;
        }
    }

I believe that this next part the code is good because everything works correctly without parentheses.

// Precondition: every operator/operand will be separated by at least one space
    public static String ConvertToPostfix(String infix) throws InvalidInfixEquationException
    {


        String[] tokens = infix.split("");
        String result= " ";

        Stack<String> stack= new Stack<>();


        for(int i = 0; i<tokens.length; i++){
            String current = tokens[i];

            if(precedence(current)>0){

                while(!stack.isEmpty() && precedence(stack.peek())>= precedence(current)){
                    result += stack.pop() + " ";
                }
                stack.push(current);
            } else if(!stack.isEmpty()&& precedence(stack.peek())<= precedence(current)){
                result += stack.pop() + " ";
            }

I believe that the issue I'm having is with the next part of my code involving manipulating the parentheses.

else if(current== ")"){
                String s = stack.pop();
                while(s !="("){
                    result += s;
                    s= stack.pop();
                }
            } else if(current == "("){
                stack.push(current);
            }
            else {
                result += current + " ";
            }
        }

       for(int i=0;i <= stack.size(); i++){
           result+= stack.pop() + " ";
        }

    return result;

    }

This is my main method and I have included an example output. import java.util.Stack; public class RPNcalc {

    public static void main( String[] args) throws InvalidInfixEquationException, InvalidPostfixEquationException {
    String result= "(3+4)/3*2"; // output 3 4 + 3 / 2 *

    System.out.println(ConvertToPostfix(result));

This is the output that I am getting

 ( 3 4 ) 3 / 2 * + 
0

There are 0 best solutions below