1

我一直在研究一个用于中缀到后缀转换的程序,并且一切正常,除了我无法弄清楚在哪里对丢失的左括号进行错误检查。基本上用户输入一个字符串,程序进入这个类并转换它,但我想确保他们输入了正确数量的括号。我尝试了多个地方,但不断提出 EmptyStackExceptions。

import java.util.*;

public class PostfixConversion {


   public static boolean precedence(char first, char second)
   {
      int v1 = 0, v2 = 0;
      //find value for first
      if(first == '-' || first == '+'){
         v1 = 1;
      }else if(first == '*' || first == '/'){
         v1 = 2;    
      }//end if

      //find value for second
      if(second == '-' || second == '+'){
         v2 = 1;
      }else if(second == '*' || second == '/'){
         v2 = 2;    
      }//end if

     if(v1 < v2){
        return false;
     }//end if

     return true;
  }//end precedence method

 //converts infix expression into postfix expression
 public static String convertToPostfix(String infixExp)
  {
     String postFix = "The Postfix Expression is: ";
     Stack<Character> stack = new Stack<Character>();
     char character = ' ';

     for(int i = 0; i < infixExp.length(); i++)
     {
         character = infixExp.charAt(i);

         //determine if character is an operator
         if(character == '*' || character == '-' || character == '/' || character == '+')
         {
             while(!stack.empty() && precedence(stack.peek(), character)){
                 postFix += stack.pop();
             }//end while
             stack.push(character);
         }
         else if(character == '(') //check for left parenthesis
         {
             stack.push(character);
         }
         else if (character == ')') 
         {
             while(!stack.peek().equals('(') && !stack.isEmpty()){ //add characters until left parenthesis
                 postFix += stack.pop();
             }//end while

             if(!stack.isEmpty() && stack.peek().equals('(')){
                 stack.pop(); // pop/remove left parenthesis
             }
         }
         else
         {
             postFix += character;
         }//end if
     }//end for
     while(!stack.empty()) //add the remaining elements of stack to postfix expression
     {
         if(stack.peek().equals('('))
         {
             postFix = "There is no matching right parenthesis.";
             return postFix;
         }
         postFix += stack.pop();
     }
         return postFix;
 }//end convertToPostfix
}
4

1 回答 1

0

首先,您必须将while循环更改为这种形式:

while (!stack.empty() && precedence(stack.peek(), character)) {
    postFix += stack.pop();
}

即更改检查中表达式的顺序whilestack.empty()检查应该是第一个。

第二个修复将在"There is no matching left parenthesis."此处添加错误消息:

if (!stack.isEmpty() && stack.peek().equals('(')) {
   stack.pop(); // pop/remove left parenthesis
} else {
   postFix = "There is no matching left parenthesis.";
   return postFix;
}
于 2013-04-19T08:16:01.040 回答