所以我正在用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