Advertisement
Guest User

javaPosfixConversion

a guest
Jul 17th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1.  
  2. package www;
  3. import java.util.Scanner;
  4. import java.util.Stack;
  5.  
  6. //////////////////////////////////////////////////////////////////
  7.  
  8. class Postfix {
  9.  
  10. int n;
  11. Stack <Character> st = new Stack();
  12.  
  13. Postfix(int total){
  14.  
  15. n= total;
  16. st.push('(');
  17.  
  18. } /// Constructor
  19.  
  20. boolean isOperator(char c){
  21.  
  22. if(c== '+'|| c== '-' || c=='/'||
  23. c=='*' || c == '%'|| c== '^') return true;
  24.  
  25. else return false;
  26. } /// is operator
  27.  
  28. boolean isOperand(char c){
  29.  
  30. if((c>='A' && c<='Z' ) || (c>='a' && c<='z')
  31. || (c>='0' && c<='9') || (c==' ')|| (c=='.'))
  32.  
  33. return true;
  34. else
  35. return false;
  36.  
  37. } /// is operand
  38.  
  39.  
  40. int precedence(char c){
  41.  
  42. switch(c){
  43.  
  44. case'^' : return 3;
  45. case'%' : return 2;
  46. case'*' : return 2;
  47. case'/' : return 2;
  48. case'+' : return 1;
  49. case'-' : return 1;
  50. default : return 0;
  51.  
  52. } /// switch
  53.  
  54. } /// precedence
  55.  
  56.  
  57. String convert(String q){
  58.  
  59. String p ="";
  60. int i;
  61. char c;
  62.  
  63. for(i=0;i<n;i++){
  64.  
  65. c = q.charAt(i);
  66.  
  67. if(isOperand(c)==true){
  68. p = p+c;
  69. }
  70.  
  71. else if(c=='(')st.push(c);
  72.  
  73. else if(isOperator(c)==true){
  74. p = p + " ";
  75. while(precedence(st.peek())>=precedence(c)){
  76. p = p+" "+st.pop()+" ";
  77.  
  78.  
  79. } /// end of while
  80. st.push(c);
  81.  
  82. } // is operator
  83.  
  84.  
  85.  
  86. else if(c ==')'){
  87.  
  88. while(st.peek()!='(')
  89. p=p+ " "+st.pop()+ " ";
  90.  
  91. st.pop();
  92. }
  93.  
  94.  
  95. } /// end of For
  96.  
  97. return p;
  98. } //convert
  99.  
  100. } /// end of postfix class
  101.  
  102. ////////////////////////////////////////////////////////////////////
  103.  
  104. public class cse0208 {
  105.  
  106. /**
  107. * @param args the command line arguments
  108. */
  109. public static void main(String[] args) {
  110.  
  111. Scanner s = new Scanner(System.in);
  112. String p,q;
  113. System.out.println("Inter an Infix expression");
  114.  
  115. q= s.nextLine();
  116. q= q.trim()+')';
  117. int total;
  118. total = q.length();
  119.  
  120. Postfix pf = new Postfix(total);
  121. p =pf.convert(q);
  122.  
  123. System.out.println("After Postfix Expression");
  124. System.out.println(p);
  125.  
  126.  
  127. }
  128.  
  129. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement