所以我正在用PostFix和Infix表达式做一些作业。我遇到了一些问题,似乎无法找到我遇到问题的位置。大部分我都可以通过Postfix工作。当我不希望它被打印时,我得到一些(或)打印的等式。另外,当我没有匹配的括号时,我不会收到像我想要的那样的错误。Stack,圆括号匹配
public String Infix(String equation) throws Exception{
Stack stack=new Stack();
boolean parensMatch=false;
int priority=0;
String temp="";
for(int i=0; i<equation.length(); i++){
char c=equation.charAt(i);
//if the character is equal to left paren, push
if(c=='('){
stack.push(c);
}
//if the character is equal to right paren, we start popping until we find a match
else if(c==')'){
try{
while(stack.peek()!='('){
temp+=stack.pop();
}
if(stack.peek()=='('){
char ch=stack.pop();
parensMatch=true;
}
if(parensMatch==false){
throw new Exception("Parens Not Match Error");
}
}catch(Exception e){
System.out.println(e);
}
parensMatch=false;
}
//if the character is equal to an operator, we do some extra work
//to figure out what is going to happen
else if(c=='+' || c=='-' || c=='*' || c=='/' || c=='^'){
char top=stack.peek();
if(top=='^')
priority=2;
else if(top=='*' || top=='/')
priority=1;
else
priority=0;
if(priority==2){
if(c=='*' || c=='/'){
temp+=stack.pop();
}
else if(c=='+' || c=='-'){
temp+=stack.pop();
}
else{
temp+=stack.pop();
}
}
else{
if(c=='*' || c=='/'){
temp+=stack.pop();
stack.push(c);
}
else if(c=='+' || c=='-'){
stack.push(c);
}
else{
stack.push(c);
}
}
}
//if the character is a space, we ignore it and move on
else if(c==' '){
;
}
//if the character is a letter, we add it to the string
else{
temp+=c;
}
}
int len = stack.size();
for (int j = 0; j < len; j++)
temp+=stack.pop();
return temp;
}
这是我对缀后缀方法
(((A + B) - (C - D))/(E - F))
这是我需要解决的表情之一,AB+CD--(EF-/
是我所得到的,当它打印到屏幕上。 ((A
是另一个,这个应该给我一个错误,但A((
被打印到屏幕上。
我一直在运行调试很长一段时间,似乎无法获得任何地方。
任何帮助将是非常有帮助的。我知道它与发布的代码有关,但我无法找到逻辑错误。提前致谢!
所以我添加了一个新的功能来帮助匹配parens,我认为它会很有用。它采用方程式并只计算它们是否匹配。
public static int matchingParens(String equation){
int match=0;
for(int i=0; i<equation.length(); i++){
char c=equation.charAt(i);
if(c=='(')
match++;
else if(c==')')
match--;
else
;
}
return match;
}
现在一切都很顺利。我已经弄清楚了。谢谢@AwfullyAwesome – kevorski