suicuned
suicuned

Reputation: 37

Trying to convert infix to postfix returns backwards output

I am creating a Reverse Polish Notation calculator that converts an infix expression to a postfix expression. However, my operators are outputting backwards. For example, I have entered the infix as "1+5*(3*2)" and when I run the program, I get the output "+ 1 * * 3 2 5" when it should be "1 5 3 2 + * +" and I can't figure out why.

public class RPNcalc extends Stack
{
    public static void main( String[] args)
    {
      String infix = "1+5*(3*2)";
      RPNcalc test = new RPNcalc();
      String output = test.ConvertToPostfix(infix);
      System.out.println(output);
    }


    public static String ConvertToPostfix(String infix)
    {
      Stack stack1 = new Stack();
      char ch;
      String postfix = "";

      for (int i = 0; i < infix.length(); i++)
      {
        ch = infix.charAt(i);

        if (isOperator(ch))
        {
          postfix = postfix + ch + " ";
        }
        else if (ch == '(')
        {
          stack1.push(ch);
        }
        else if (ch == ')')
        {
          while (stack1.peek() != '(')
          {
            postfix = postfix + stack1.pop() + " ";
          }
          stack1.pop();
        }
        else
        {
          while (!stack1.isEmpty() && !(stack1.peek() == '(') && (precedence(ch) <= precedence(stack1.peek())))
          {
            postfix = postfix + stack1.pop() + " ";
          }
          stack1.push(ch);
        }
      }
      while (!stack1.isEmpty())
      {
        postfix = postfix + stack1.pop();
      }
      return postfix;
    }

Upvotes: 1

Views: 194

Answers (1)

Kaplan
Kaplan

Reputation: 3758

There is only a “!” missing:

It must read:
if( ! isOperator( ch ) ) {…}

and the output is correct: 1 5 3 2 * * +   evaluates to 31

There is something wrong with the spacing between * and +
postfix + ' ' + stack1.pop() ?

A very good description of the shunting-yard-algorithm is here to find:
https://en.wikipedia.org/wiki/Shunting-yard_algorithm#Detailed_example

And by the way – in Java the function name should start with a lower-case letter:
convertToPostfix( String infix )

Upvotes: 1

Related Questions