中缀到后缀转换Java的括号错误检查
我一直在做一个中缀到后缀转换的程序,所有的东西都在工作,除了我不知道在哪里放一个缺少左括号的错误检查。基本上,用户输入一个字符串,程序转到这个类并转换它,但我想确保他们输入了正确数量的括号。我尝试了多个地方,但不断出现EmptyStackException中缀到后缀转换Java的括号错误检查,java,stack,infix-notation,postfix-notation,Java,Stack,Infix Notation,Postfix Notation,我一直在做一个中缀到后缀转换的程序,所有的东西都在工作,除了我不知道在哪里放一个缺少左括号的错误检查。基本上,用户输入一个字符串,程序转到这个类并转换它,但我想确保他们输入了正确数量的括号。我尝试了多个地方,但不断出现EmptyStackException import java.util.*; public class PostfixConversion { public static boolean precedence(char first, char second) {
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
}
import java.util.*;
公共类后固定转换{
公共静态布尔优先级(字符优先,字符第二)
{
int v1=0,v2=0;
//先找到价值
如果(第一个=='-'| |第一个=='+')){
v1=1;
}else if(first=='*'| | first=='/')){
v1=2;
}//如果结束
//找到第二个值
如果(秒=='-'| |秒=='+')){
v2=1;
}else if(second=='*'| | second=='/')){
v2=2;
}//如果结束
如果(v1
首先,您必须更改,同时将循环更改为此表单:
while (!stack.empty() && precedence(stack.peek(), character)) {
postFix += stack.pop();
}
i、 e.检查时更改中表达式的顺序:stack.empty()
检查应该是第一个
第二个修复方法是添加“没有匹配的左括号。”
此处的错误消息:
if (!stack.isEmpty() && stack.peek().equals('(')) {
stack.pop(); // pop/remove left parenthesis
} else {
postFix = "There is no matching left parenthesis.";
return postFix;
}
请给出一个示例,在该示例中,您会收到EmptyStackExceptions
@andemoniy Err,这是一个缺少左括号的表达式?