It is because you enter to the stack character by character:
theStack.push((int) (ch - '0'));
Meaning that this input: 10+2, will be entered in the stack like this:
1, 0, +, 2
You want this:
10, +, 2
Try this:
String s = "10+2-3/4*11";
StringTokenizer st = new StringTokenizer(s,"[+-/*]",true);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
And see what it prints.
Also for the above you will need you stack to take String array, not char:
String num2 = theStack.pop();
String num1 = theStack.pop();
if ("+".equals(operator)) {
interAns = Integer.parseInt(num1) + Integer.parseInt(num2);
}
javaAddict
Nearly a Senior Poster
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448