如何使用堆栈创建Postfix表示法?

时间:2015-11-17 22:14:23

标签: java

我一直在编写一个接受字符串输入的类,然后将其转换为后缀表示法。出于某种原因,我似乎无法找到我所拥有的错误。在我运行的最后几个测试用例之前,一切似乎都能正常工作。

我的输入测试用例:(a*(b+c)-(d-e)/f) *g/(h-i)-j *k

我的预期输出测试用例:abc+*de-f/-g*hi-/jk*-

我的输出案例:abc+de-f/-*ghi-jk*-/*

我一直在看我的代码2小时尝试不同的东西来解决问题,但我似乎无法找到问题所在。如果有人能帮我识别问题,我将非常感激。

这是班级:

import java.util.Stack;

public class InfixToPostfixConverter
{
//**********************************************************************
//The precedence method determines the precedence between two operators.
//If the first operator is of higher or equal precedence than the second
//operator, it returns the value true, otherwise it returns false.
//***********************************************************************
public static boolean precedence(char topStack, char currentChar)
{
   if(topStack == '*' || topStack == '/'){
       if(currentChar == '+' || currentChar == '-'){
           return true;
       }
   }
   else if(topStack == currentChar){
       return true;
   }
   else if(topStack == '+' && currentChar == '-'){
      return true;
   }
   else if(topStack == '-' && currentChar == '+'){
      return true;
   }
   else if(topStack == '*' && currentChar == '/'){
       return true;
   }
   else if(topStack == '/' && currentChar == '*'){
       return true;
   }

   return false;
}
char currentChar = infixString.charAt(i);

    //Case A:
     if(currentChar != '+' && currentChar != '-' && currentChar != '*' && currentChar != '/' && currentChar != '(' && currentChar != ')' ){
         postfixString += currentChar;
     }

    //Case B:
     else if(currentChar == '('){
         stack1.push(currentChar);
     }

    //Case C:
     else if(stack1.isEmpty() && currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/'){
         stack1.push(currentChar);
     }

    //Case D:
     else if(currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/' && !stack1.isEmpty()){
         char topStack = stack1.peek();

        while(!stack1.isEmpty()){
            if(precedence(topStack, currentChar)){
                postfixString += stack1.pop();
            }
            else{
                stack1.push(currentChar);
                break;
            } 

        }



     }

    //Case E:
     else if(currentChar == ')' && !stack1.isEmpty()){
         while(!stack1.isEmpty() && stack1.peek() != '('){
             postfixString += stack1.pop();
         }
         stack1.pop();
     }


  } //end of for loop


    //Case F:
  if(!stack1.isEmpty() && stack1.peek() == '('){
      return "No matching close parenthesis error.";
  }
  else if(!stack1.isEmpty() && stack1.peek() != '('){
      while(!stack1.isEmpty() && stack1.peek() != '('){
          postfixString += stack1.pop();
      }
  }


  return postfixString;


}//end of convertToPostfix method

}//end of the InfixToPostfixConverter class

0 个答案:

没有答案