Search code examples
javainfix-notationpostfix-mta

How to rewrite my toPostfix() method to use isOperator()?


In my program I am working on converting from infix to postfix. I have a method named isOperator(), which will return true if the precedance of the operator is greater than 0.

I am supposed to rewrite the toPostfix() method using isOperator(), but I am unsure where to begin.

public class Expression {
   private static final String SPACE = " ";
   private static final String PLUS = "+";
   private static final String MINUS = "-";


   public static int rank(String operator) {
      switch (operator) {
         case "*":
         case "/":
            return 2;
         case PLUS:
         case MINUS:     //2
            return 1;
         default:
            return -1;
      }
   }

   public static boolean isOperator(String token) {     //4
      if (rank(token) > 0){
         return true;
      }
      return false;
   }

   public static String toPostfix(String infixExpr) {
      StringBuilder output = new StringBuilder();
      Stack<String> operators = new ArrayStack<>();
      for (String token: infixExpr.split("\\s+")) {
         if (rank(token) > 0) { // operator
            // pop equal or higher precedence
            while (!operators.isEmpty() &&
                  rank(operators.peek()) >= rank(token)) {
               output.append(operators.pop() + SPACE);
            }
            operators.push(token);
         } else {               // operand
            output.append(token + SPACE);
         }
      }
      while (!operators.isEmpty()) {
         output.append(operators.pop() + SPACE);
      }
      return output.toString();
   }

   public static void main(String[] args) {
      System.out.println(rank("/"));
      String infix = "a * b * c + d / e / f";
      System.out.println(toPostfix(infix));
   }
}

Solution

  • Change if(rank(token) > 0){ in your postfix method to isOperator(token)