Skip to content

Instantly share code, notes, and snippets.

@domgetter
Forked from StephenBerkner/RPN Calculator
Created October 12, 2017 23:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save domgetter/b5ad58537ca99361a387395cb305952c to your computer and use it in GitHub Desktop.
Save domgetter/b5ad58537ca99361a387395cb305952c to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator Written in Java
import java.util.*;
public class RPNCalc {
private static Stack<Integer> stack = new Stack<Integer>();
private static Scanner input = new Scanner(System.in);
public static void calculator() throws Exception {
System.out.println("Welcome to the RPN Calculator program!");
takeInput();
}
private static void takeInput() {
String numOrOperand = " ";
while (!numOrOperand.equals("x")) {
System.out.println("Enter next input: ");
numOrOperand = input.next();
try {
int intNumOrOperand = Integer.valueOf(numOrOperand);
stack.push(intNumOrOperand);
} catch (Exception e) {
if (numOrOperand.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (numOrOperand.equals("/")) {
stack.push((int) stack.pop() / stack.pop());
} else if (numOrOperand.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (numOrOperand.equals("-")) {
stack.push(stack.pop() - stack.pop());
} else if (numOrOperand.equals("=")) {
System.out.println(stack.pop());
} else if (numOrOperand.equals("c")) {
if (!stack.empty()) {
for (int i = 0; i < stack.size(); i++) {
stack.pop();
}
}
} else if (numOrOperand.equals("w")) {
for (int i = 0; i < stack.size(); i++) {
System.out.println(stack.get(i));
}
}
}
}
}
public static void main(String[] args) {
try {
calculator();
} catch (Exception e) {
System.out.println("Oops, that doesn't work... ");
}
}
}
@sz332
Copy link

sz332 commented May 1, 2019

Nice try, but the code is wrong, - and / has the wrong order, you need to pop them separately, and use them in the correct order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment