-
-
Save domgetter/b5ad58537ca99361a387395cb305952c to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator Written in Java
This file contains hidden or 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.*; | |
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... "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.