/ Postfix_Expression / postfix_expression.java
postfix_expression.java
1 /* 2 * We will create a stack and push elements into it (if they are numbers) 3 * If they are operands, we will pop the previou 2 values and apply the operation and push the output 4 */ 5 6 import java.util.Stack; 7 import java.util.Scanner; 8 9 public class postfix_expression { 10 public static int evalPostfix(String[] arr) { 11 Stack<Integer> stack = new Stack<>(); 12 13 for(String token : arr) { 14 if(token.matches("-?\\d+")) { // This regex expression checks if the token is a digit 15 stack.push(Integer.parseInt(token)); 16 } 17 18 else { 19 int val1 = stack.pop(); 20 int val2 = stack.pop(); 21 22 switch (token) { 23 case "+": 24 stack.push(val1 + val2); 25 break; 26 27 case "-" : 28 stack.push(val2 - val1); 29 break; 30 31 case "*" : 32 stack.push(val1 * val2); 33 break; 34 35 case "/" : 36 stack.push(val2 / val1); 37 38 default: 39 break; 40 } 41 } 42 } 43 return stack.pop(); 44 } 45 public static void main(String[] args) { 46 System.out.println("Enter the expression: "); 47 Scanner sc = new Scanner(System.in); 48 49 String expression = sc.nextLine(); 50 String[] array_elements = expression.split(""); 51 52 System.out.println(evalPostfix(array_elements)); 53 } 54 }