我一直在研究一个用于中缀到后缀转换的程序,并且除了我无法弄清楚在哪里对错误的左括号进行错误检查之外,还有所有工作。基本上用户输入一个字符串,程序进入这个类并转换它但我想确保它们输入了正确数量的括号。我已经尝试了多个地方,但不断提出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
}
答案 0 :(得分:0)
首先,您必须将while
循环更改为此表单:
while (!stack.empty() && precedence(stack.peek(), character)) {
postFix += stack.pop();
}
即。在while
的检查中更改表达式的顺序:stack.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;
}