This EmptyStackException continues to pop up. Obliviously there is nothing in my stack, but the first element that the User inputs. However, I am not sure where the code i
String in = input.next();
reads you one word, then you are trying to tokenise that word. Perhaps you meant String in = input.nextLine();
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#next() http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextLine()
Also, you have these two lines in your code.
if (!stack.isEmpty())
// throw new StackUnderflowException("Empty Stack");
This is plain wrong. Without its curly braces, the if
affects the next statement. It is not the comment - it is the following if.
This:
if (!stack.isEmpty())
// throw new StackUnderflowException("Empty Stack");
// Base case: stack has 1 element, which is the answer => finished
if (stack.size() == 1)
System.out.printf("Finished, Answer: %s\n",stack.peek());
is equivalent to this:
if (!stack.isEmpty())
if (stack.size() == 1)
System.out.printf("Finished, Answer: %s\n",stack.peek());
and this:
if (!stack.isEmpty() && stack.size() == 1){
System.out.printf("Finished, Answer: %s\n",stack.peek());
}
Moral: always use curly brackets with an if
AND don't comment out assertions. Even if you do comment out assertions, comment them completely, and not one half of them, epecially when the other half is an un-bracketed if.
Third, your logic is flawed. You do this:
push all symbols to the stack, then pop the top three and consider them an operator and two numbers. This will work with some inputs if you use a queue instead.
4 5 * 6 -
By your logic, this will pop * 6 -
and crash. If you use a queue, it will work in this case
4 5 * 6 -
20 6 -
14
But not is this case:
(1+1)*(1+1)
express as RPN
1 1 + 1 1 + *
2 1 1 + *
Next, you pop 2 1 1 and crash.
Instead, what you should do:
Read the input. For each symbol:
if it is a number,
push it on the stack.
else,
pop two numbers from the stack,
perform the operation and
push the result.
import logging, sys, time
import jenkins from jenkinsapi.jenkins
import Jenkins from jenkinsapi.build
import Build from collections import OrderedDict
LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
A stack is LIFO, or "Last in, First out". So when you have an input sequence of 4 5 * 6 -
and do this:
rpnStack.push(st.nextToken());
The first thing you pop will be "-", the second thing will be "6", and the third thing will be "*". Is this what you expect?
Also, instead of:
String temp1 = stack.peek();
stack.pop();
You can do:
String temp1 = stack.pop();