Last active
August 29, 2015 14:01
-
-
Save RyanBreaker/1823267e68ed337ee377 to your computer and use it in GitHub Desktop.
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 Main { | |
| public static void main(String[] args) { | |
| Scanner input = new Scanner(System.in); | |
| String inputString; | |
| Stack stack = new Stack(); | |
| while(true) { | |
| System.out.print("> "); | |
| inputString = input.nextLine(); | |
| if(inputString.contentEquals("q")) | |
| break; | |
| for(String s : inputString.split(" ")) { | |
| if(s.length() == 0) | |
| break; | |
| // First try to see if s is just a number and can be pushed... | |
| try { | |
| stack.push(Double.parseDouble(s)); | |
| // Otherwise move on with life. | |
| } catch (NumberFormatException e) { | |
| if (s.contentEquals("clear")) | |
| stack.clear(); | |
| else { | |
| try { | |
| if (s.contentEquals("drop")) | |
| stack.pop(); | |
| else { | |
| double n1 = stack.pop(); | |
| double n2 = stack.pop(); | |
| if (s.contentEquals("+")) | |
| stack.push(n1 + n2); | |
| else if (s.contentEquals("-")) | |
| stack.push(n2 - n1); | |
| else if (s.contentEquals("/")) | |
| stack.push(n2 / n1); | |
| else if (s.contentEquals("*")) | |
| stack.push(n1 * n2); | |
| } | |
| } catch (EmptyStackException f) { | |
| System.out.println("Stack is empty!"); | |
| } | |
| } | |
| } | |
| } | |
| stack.printStack(); | |
| } | |
| System.out.println("Bye!"); | |
| } | |
| } | |
| class Stack { | |
| List<Double> stackList = new ArrayList<Double>(); | |
| public void push(double n) { | |
| stackList.add(n); | |
| } | |
| public double pop() { | |
| if(stackList.size() == 0) | |
| throw new EmptyStackException(); | |
| return stackList.remove(stackList.size() - 1); | |
| } | |
| public void printStack() { | |
| System.out.println("Size: " + stackList.size()); | |
| for(double n : stackList) | |
| System.out.println(n); | |
| } | |
| public void clear() { | |
| stackList.clear(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment