Thread: Reverse Polish notation with stacks confusion

1. Senior Member
Join Date
Nov 2008
Posts
105
Rep Power
0

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:
Java 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
Java 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
Java 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.

2. Senior Member
Join Date
Aug 2009
Posts
2,388
Rep Power
10
You pushed Strings and tried to pop integers.
Push integers.

3. Java Code:
`int i = Integer.parseInt(theStack.pop() ); // will parse the string to integer`

4. Senior Member
Join Date
Nov 2008
Posts
105
Rep Power
0
Says I can't do that because it can't find parseInt in Object.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•