Created
December 20, 2019 11:34
-
-
Save irfanm96/6995e407b86c2a6520986c5a70319f40 to your computer and use it in GitHub Desktop.
Java Implementation to evaluate a postfix expression using a stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
public class Main { | |
public static void main(String[] args) { | |
// the driver code | |
String expression1 = "22*3+"; | |
//should print answer as 7 | |
evaluatePostfix(expression1); | |
String expression2 = "32*2+"; | |
//should print answer as 8 | |
evaluatePostfix(expression2); | |
String expression3 = "3*2+"; | |
//should print Not a valid expression | |
evaluatePostfix(expression3); | |
} | |
//simple function to evaluate when given operands and the operator | |
//can be extended to more operators | |
static int evaluate(int operand1, int operand2, char operator) { | |
switch (operator) { | |
case '+': | |
System.out.println(operand1 + " + " + operand2); | |
return operand1 + operand2; | |
case '-': | |
System.out.println(operand1 + " - " + operand2); | |
return operand1 - operand2; | |
case '/': | |
System.out.println(operand1 + " / " + operand2); | |
return operand1 / operand2; | |
case '*': | |
System.out.println(operand1 + " * " + operand2); | |
return operand1 * operand2; | |
default: | |
return 0; | |
} | |
} | |
static void evaluatePostfix(String expression) { | |
System.out.println("Evaluating expression " + expression); | |
Stack<Character> stack = new Stack<Character>(); | |
char[] array = expression.toCharArray(); | |
int i = 0; | |
while (i < array.length) { | |
//if its a digit put it in the stack | |
if (Character.isDigit(array[i])) { | |
stack.push(array[i]); | |
} else { | |
//always stack has to be of size of 2 , if not the expression is not valid | |
if (stack.size() != 2) { | |
System.out.println("postfix expression is not valid"); | |
return; | |
} | |
//get the operands by popping the stack | |
int operand1 = Integer.parseInt(String.valueOf(stack.pop())); | |
int operand2 = Integer.parseInt(String.valueOf(stack.pop())); | |
//evaluate the operands using the operator | |
int result = evaluate(operand1, operand2, array[i]); | |
//push the result back to the stack | |
stack.push(Character.forDigit(result, 10)); | |
} | |
i++; | |
} | |
//print the result | |
System.out.println("result is " + stack.pop() + '\n'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
another way for the code but work for only one digite