Skip to content

Instantly share code, notes, and snippets.

@michalwa
Last active August 24, 2018 19:37
Show Gist options
  • Save michalwa/0b357a50e2fb28eb062346c3ab6443a9 to your computer and use it in GitHub Desktop.
Save michalwa/0b357a50e2fb28eb062346c3ab6443a9 to your computer and use it in GitHub Desktop.
RPN Evaluator
package michalwa.rpn;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;
public class RPNDemo
{
@FunctionalInterface
private static interface Operator
{
public double eval(double a, double b);
}
public static void main(String[] args)
{
HashMap<Character, Operator> ops = new HashMap<Character, Operator>();
ops.put('+', (a, b) -> a + b);
ops.put('-', (a, b) -> a - b);
ops.put('*', (a, b) -> a * b);
ops.put('/', (a, b) -> a / b);
System.out.print("Type in your RPN expression: ");
Scanner scanner = new Scanner(System.in);
Stack<Double> stack = new Stack<Double>();
boolean noOps = true;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
stack.push(scanner.nextDouble());
} else {
char op = scanner.next().charAt(0);
if(ops.containsKey(op)) {
if(stack.size() >= 2) {
double b = stack.pop();
double a = stack.pop();
stack.push(ops.get(op).eval(a, b));
noOps = false;
}
}
}
}
if(noOps || stack.size() != 1) {
System.out.println("This is not a valid RPN expression.");
System.exit(0);
} else {
scanner.close();
System.out.println(" = " + stack.peek());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment