Skip to content

Instantly share code, notes, and snippets.

@RyanBreaker
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save RyanBreaker/1823267e68ed337ee377 to your computer and use it in GitHub Desktop.

Select an option

Save RyanBreaker/1823267e68ed337ee377 to your computer and use it in GitHub Desktop.
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