# Reverse Polish notation with stacks confusion

• 10-05-2009, 07:25 PM
jigglywiggly
Reverse Polish notation with stacks confusion
Ok just to give you an idea if you don't know what reverse polish notation is:
(5+3)/2 In reverse polish notation is
5
3
+
2
/

But that's not what I came here, I can figure the way to do that myself.

But what I am confused is this:
Code:

```Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer         at CalcStack.solve(CalcStack.java:21)         at CalcStackDriver.main(CalcStackDriver.java:19)```

Basic driver
Code:

```import java.util.*; public class CalcStackDriver {       public static void main(String[] args) {     Stack j = new Stack();     Object firstthing ="2";     Object secondthing ="3";     Object thirdthing ="/";                     j.push(thirdthing);     j.push(secondthing);     j.push(firstthing);     CalcStack m = new CalcStack(j);       m.solve();     } }```

And where the computation is done
Code:

```import java.util.*; public class CalcStack {     Stack theStack;     double finalvalue=0;     public CalcStack(Stack j) {     theStack=j;     int counter=0;     }     public double solve()  {  while(!(theStack.empty())) {                           double d=0;             int j = ((Integer) theStack.pop()).intValue(); //here is where the error points too             int m = ((Integer) theStack.pop()).intValue();             String s = ((String) theStack.pop()).toString();             if(s.equals("+")) {                 d=j+m;                 finalvalue=d;                 theStack.push(d);             }             if(s.equals("*")) {                 d=j*m;                 finalvalue=d;                 theStack.push(d);             }             if(s.equals("/")) {                 d=j/m;                 finalvalue=d;                 theStack.push(d);             }           //(3+2)/2             //3             //2             //+             //2      5/2             ///         }           return finalvalue;         }             }```
It's says I can't convert a String to an int, but I'm a bit confused why not? This doesn't seem like a hard problem, I don't think I am thinking straight. Oh and don't comment on my algorithim, it's just a basic thing to see if it works.
• 10-05-2009, 07:29 PM
r035198x
You pushed Strings and tried to pop integers.
Push integers.
• 10-05-2009, 07:35 PM
mrmatt1111
Code:

`int i = Integer.parseInt(theStack.pop() ); // will parse the string to integer`
• 10-05-2009, 07:40 PM
jigglywiggly
Says I can't do that because it can't find parseInt in Object.