import java.lang.Integer; import java.util.Scanner; import java.util.Stack; class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print("Enter Equation : "); String postfix = infixToPostfix(input.nextLine()); System.out.println(solve(postfix)); input.close(); } public static int solve(String postfix) { Stack ints = new Stack<>(); for (int i = 0; i < postfix.length(); i++) { char x = postfix.charAt(i); if (x == ' ') { continue; } else if (Character.isDigit(x)) { String fullNumber = ""; while (postfix.charAt(i) != ' ') { fullNumber += postfix.charAt(i); i++; } ints.push(Integer.parseInt(fullNumber)); } else { int num2 = ints.pop(); int num1 = ints.pop(); switch (x) { case '/': ints.push(num1 / num2); break; case '*': ints.push(num1 * num2); break; case '+': ints.push(num1 + num2); break; case '-': ints.push(num1 - num2); break; } } } return ints.pop(); } public static Integer calculatePrecedence(Character c) { if (c == '*' || c == '/') { return 1; } else { return 0; } } public static String infixToPostfix(String infix) { Stack stack = new Stack<>(); String postfix = ""; int i = 0; while (i < infix.length()) { char c = infix.charAt(i); if (Character.isDigit(c)) { String num = ""; while ( (i < infix.length()) && Character.isDigit(infix.charAt(i)) ) { num += infix.charAt(i); i++; } postfix += num + " "; } else { while ( !stack.empty() && calculatePrecedence(stack.peek()) >= calculatePrecedence(c) ) { postfix += stack.pop(); } stack.push(c); i++; } } while (!stack.empty()) { postfix += stack.pop(); } return postfix; } }