Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package www;
- import java.util.Scanner;
- import java.util.Stack;
- //////////////////////////////////////////////////////////////////
- class Postfix {
- int n;
- Stack <Character> st = new Stack();
- Postfix(int total){
- n= total;
- st.push('(');
- } /// Constructor
- boolean isOperator(char c){
- if(c== '+'|| c== '-' || c=='/'||
- c=='*' || c == '%'|| c== '^') return true;
- else return false;
- } /// is operator
- boolean isOperand(char c){
- if((c>='A' && c<='Z' ) || (c>='a' && c<='z')
- || (c>='0' && c<='9') || (c==' ')|| (c=='.'))
- return true;
- else
- return false;
- } /// is operand
- int precedence(char c){
- switch(c){
- case'^' : return 3;
- case'%' : return 2;
- case'*' : return 2;
- case'/' : return 2;
- case'+' : return 1;
- case'-' : return 1;
- default : return 0;
- } /// switch
- } /// precedence
- String convert(String q){
- String p ="";
- int i;
- char c;
- for(i=0;i<n;i++){
- c = q.charAt(i);
- if(isOperand(c)==true){
- p = p+c;
- }
- else if(c=='(')st.push(c);
- else if(isOperator(c)==true){
- p = p + " ";
- while(precedence(st.peek())>=precedence(c)){
- p = p+" "+st.pop()+" ";
- } /// end of while
- st.push(c);
- } // is operator
- else if(c ==')'){
- while(st.peek()!='(')
- p=p+ " "+st.pop()+ " ";
- st.pop();
- }
- } /// end of For
- return p;
- } //convert
- } /// end of postfix class
- ////////////////////////////////////////////////////////////////////
- public class cse0208 {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- Scanner s = new Scanner(System.in);
- String p,q;
- System.out.println("Inter an Infix expression");
- q= s.nextLine();
- q= q.trim()+')';
- int total;
- total = q.length();
- Postfix pf = new Postfix(total);
- p =pf.convert(q);
- System.out.println("After Postfix Expression");
- System.out.println(p);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement