File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ public class Postfix {
4+ public static void main (String [] args ) {
5+ Scanner scanner = new Scanner (System .in );
6+ String post = scanner .nextLine (); // Takes input with spaces in between eg. "1 21 +"
7+ System .out .println (postfixEvaluate (post ));
8+ }
9+
10+ // Evaluates the given postfix expression string and returns the result.
11+ public static int postfixEvaluate (String exp ) {
12+ Stack <Integer > s = new Stack <Integer > ();
13+ Scanner tokens = new Scanner (exp );
14+
15+ while (tokens .hasNext ()) {
16+ if (tokens .hasNextInt ()) {
17+ s .push (tokens .nextInt ()); // If int then push to stack
18+ } else { // else pop top two values and perform the operation
19+ int num2 = s .pop ();
20+ int num1 = s .pop ();
21+ String op = tokens .next ();
22+
23+ if (op .equals ("+" )) {
24+ s .push (num1 + num2 );
25+ } else if (op .equals ("-" )) {
26+ s .push (num1 - num2 );
27+ } else if (op .equals ("*" )) {
28+ s .push (num1 * num2 );
29+ } else {
30+ s .push (num1 / num2 );
31+ }
32+
33+ // "+", "-", "*", "/"
34+ }
35+ }
36+ return s .pop ();
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments