如何重写我的 toPostfix() 方法以使用 isOperator()?

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

在我的程序中,我正在处理从中缀到后缀的转换。我有一个名为 isOperator() 的方法,如果运算符的优先级大于 0,它将 return 为真。

我应该使用 isOperator() 重写 toPostfix() 方法,但我不确定从哪里开始。

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));
   }
}

变化:if(rank(token) > 0){

收件人:isOperator(token)

将后缀方法中的 if(rank(token) > 0){ 更改为 isOperator(token)