In: Computer Science
how do I write a class PostFix that has one method covert that converts an infix expression (as a string input) to postfix in java?
Sample Output:
The screenshots are attached below for reference.
Please follow them for proper output.
Program code to copy:
import java.util.*;
public class PostFix{
public static int precedence(char c){
if(c=='+' || c=='-')//return the precedence value of
operators
return 1;
if(c=='*' || c=='/')
return 2;
else
return 3;
}
public static String convert(String e){
String res=new String("");
char c;
Stack<Character> s=new Stack<>();//Use the stack to
convert to PostFix form
for(int i=0;i<e.length();i++){//iterate through the string
c=e.charAt(i);
if(Character.isLetterOrDigit(c))//if it not operator add it to res
string
res=res+c;
else{
while(!s.isEmpty() &&
precedence(c)<=precedence(s.peek())){
res=res+s.pop();//pop the stack if character is a operator for less
precedence values
}
s.push(c);//push character after popping all the operators of less
precedence
}
}
while(!s.isEmpty()){
res=res+s.pop();//empty the stack
}
return res;
}
public static void main(String[] args){
String e="1+2-3+6+5";//create string in infix form
System.out.println(convert(e));//call function and print returned
string
}
}