samedi 7 mars 2015

infix to postfix in java using stack class



I'm trying to write infix to postfix program in java using stack. Here is my code:



import java.io.*;
import java.util.*;
public class ONP{
public static void main(String args[]) throws java.io.IOException, NumberFormatException ,EmptyStackException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));

int n=Integer.parseInt(br.readLine());
StringBuilder out= new StringBuilder();

Stack st=new Stack();

for(int i=0;i<n;i++){
String input=br.readLine();
char in[]=input.toCharArray();
int len=input.length();
for (int j=0;j<len;j++){
if (in[j]>='a' && in[j]<='z'){
out.append(in[j]);
}

else if(in[j]=='('){
st.push(new Character(in[j]));

}
else if(in[j]=='+' || in[j]=='-' || in[j]=='*' || in[j]=='/' || in[j]=='^'){
st.push(new Character(in[j]));

}

else if(in[j]==')'){
int k=j;

while(in[k]!='(' && !st.empty() ){

char ch=st.pop().toString().charAt(0);
if(ch!='('&&ch!=')')
out.append(ch);
k--;
}
}


}
out.append("\n");

}
System.out.print(out);
}
}


Input:



((a+t)*((b+(a+c))^(c+d)))


Output:



at+bac++*cd+^


"*" should come after "+^" but it comes after "++". I can't find the bug.




Aucun commentaire:

Enregistrer un commentaire