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.
Well you need to implement operator precedence, and you haven't. You need to look up the Dijkstra Shunting-yard algorithm.
It's just a small error. In this code you look for '(' in the "in" array which makes no sense. You only want to look for it on the stack.
Just change it to this
That should fix the error. But there are a lot of other details you could improve. e.g. put part of the code into another method and make use of generics and autoboxing. Use Strings instead of chars to allow operators with more then one character and also implement operator precedence so you don't need so many parentheses.
Look at this.