Main.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import java.lang.Integer;
  2. import java.util.Scanner;
  3. import java.util.Stack;
  4. class Main {
  5. public static void main(String args[]) {
  6. Scanner input = new Scanner(System.in);
  7. System.out.print("Enter Equation : ");
  8. String postfix = infixToPostfix(input.nextLine());
  9. System.out.println(solve(postfix));
  10. input.close();
  11. }
  12. public static int solve(String postfix) {
  13. Stack<Integer> ints = new Stack<>();
  14. for (int i = 0; i < postfix.length(); i++) {
  15. char x = postfix.charAt(i);
  16. if (x == ' ') {
  17. continue;
  18. } else if (Character.isDigit(x)) {
  19. String fullNumber = "";
  20. while (postfix.charAt(i) != ' ') {
  21. fullNumber += postfix.charAt(i);
  22. i++;
  23. }
  24. ints.push(Integer.parseInt(fullNumber));
  25. } else {
  26. int num2 = ints.pop();
  27. int num1 = ints.pop();
  28. switch (x) {
  29. case '/':
  30. ints.push(num1 / num2);
  31. break;
  32. case '*':
  33. ints.push(num1 * num2);
  34. break;
  35. case '+':
  36. ints.push(num1 + num2);
  37. break;
  38. case '-':
  39. ints.push(num1 - num2);
  40. break;
  41. }
  42. }
  43. }
  44. return ints.pop();
  45. }
  46. public static Integer calculatePrecedence(Character c) {
  47. if (c == '*' || c == '/') {
  48. return 1;
  49. } else {
  50. return 0;
  51. }
  52. }
  53. public static String infixToPostfix(String infix) {
  54. Stack<Character> stack = new Stack<>();
  55. String postfix = "";
  56. int i = 0;
  57. while (i < infix.length()) {
  58. char c = infix.charAt(i);
  59. if (Character.isDigit(c)) {
  60. String num = "";
  61. while (
  62. (i < infix.length()) && Character.isDigit(infix.charAt(i))
  63. ) {
  64. num += infix.charAt(i);
  65. i++;
  66. }
  67. postfix += num + " ";
  68. } else {
  69. while (
  70. !stack.empty() &&
  71. calculatePrecedence(stack.peek()) >= calculatePrecedence(c)
  72. ) {
  73. postfix += stack.pop();
  74. }
  75. stack.push(c);
  76. i++;
  77. }
  78. }
  79. while (!stack.empty()) {
  80. postfix += stack.pop();
  81. }
  82. return postfix;
  83. }
  84. }