Skip to content

Instantly share code, notes, and snippets.

@iamaamir
Last active February 15, 2018 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamaamir/8cfb1b471fa844c4932cb1af359799de to your computer and use it in GitHub Desktop.
Save iamaamir/8cfb1b471fa844c4932cb1af359799de to your computer and use it in GitHub Desktop.
wap that reads postfix expressions and prints their values. Each input expression should be entered on its own line, and the program should terminate when the user enters a blank line. Please do error checking for any error.
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
/*
wap that reads postfix expressions and prints their values.
Each input expression should be entered on its own line,
and the program should terminate when the user enters a blank line.
Please do error checking for any error.
Assume only binary operators, and that the expressions contain no variables.
Note that you will need to use
parentheses to indicate the order of application of the operators in the expression.
Here are sample input–output
pairs:
78 78
78 6 + 84
78 6 + 9 2 - / 12
78 + error
2 + 3 error
*/
public class Postfix {
private final Scanner input;
boolean error = false;
public Postfix() {
input = new Scanner(System.in);
}
public int solution(String exp) throws EmptyStackException {
if (exp.isEmpty()) {
System.exit(0);
}
Stack<Integer> s = new Stack<>();
Scanner tokens = new Scanner(exp);
while (tokens.hasNext()) {
if (tokens.hasNextInt()) {
s.push(tokens.nextInt());
} else {
int num2 = s.pop();
int num1 = s.pop();
String op = tokens.next();
switch (op) {
case "+":
s.push(num1 + num2);
break;
case "-":
s.push(num1 - num2);
break;
case "*":
s.push(num1 * num2);
break;
default:
s.push(num1 / num2);
break;
}
}
}
return s.pop();
}
private void showResult(String msg) {
System.out.println(msg);
System.out.println("Result " + solution(input.nextLine()));
}
private void run() {
do {
try {
if (!error) showResult("Enter Postfix Expression: "); else {
error = false;
showResult("Error, Enter Correct Postfix expression.");
}
} catch (EmptyStackException e) {error = true;}
} while (true);
}
public static void main(String[] args) {
new Postfix().run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment