Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. package converter;
  2. import java.util.Stack;
  3. import java.util.Scanner;
  4.  
  5. public class converter
  6. {
  7. // check priority the highest is the first
  8. static int Prec(char ch)
  9. {
  10. switch (ch)
  11. {
  12. case '+':
  13. case '-':
  14. return 1;
  15.  
  16. case '*':
  17. case '/':
  18. return 2;
  19.  
  20. case '^':
  21. return 3;
  22. }
  23. return -1;
  24. }
  25.  
  26. // Converter method
  27. static String ToPostfix(String exp)
  28. {
  29. // empty string for result
  30. String result = new String("");
  31.  
  32. // New stack
  33. Stack<Character> stack = new Stack<>();
  34.  
  35. // for loop on the given exp string from main (char by char)
  36. for (int i = 0; i<exp.length(); ++i)
  37. {
  38. char c = exp.charAt(i);
  39.  
  40. // is character?
  41. if (Character.isLetterOrDigit(c))
  42. result += c;
  43.  
  44. // is ( ?
  45. else if (c == '(')
  46. stack.push(c);
  47.  
  48. // is ) ?
  49. else if (c == ')')
  50. {
  51. // Pop everying inside () ... check everything not inside ()
  52. while (!stack.isEmpty() && stack.peek() != '(')
  53. result += stack.pop();
  54.  
  55. if (!stack.isEmpty() && stack.peek() != '(')
  56. return "Invalid Expression";
  57. else
  58. stack.pop();
  59. }
  60. // is * / + - ?
  61. else
  62. {
  63. // Priority
  64. while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){
  65. if(stack.peek() == '(')
  66. return "Invalid Expression";
  67. result += stack.pop();
  68. }
  69. stack.push(c);
  70. }
  71. }
  72.  
  73. // pop all the operators from the stack
  74. while (!stack.isEmpty()){
  75. if(stack.peek() == '(')
  76. return "Invalid Expression";
  77. result += stack.pop();
  78. }
  79. return result;
  80. }
  81.  
  82.  
  83. public static void main(String[] args)
  84. {
  85. System.out.println("Type your Infix: ");
  86.  
  87. Scanner s = new Scanner(System.in);
  88. String exp = s.next();
  89.  
  90. System.out.println(ToPostfix(exp));
  91. }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement