Results 1 to 4 of 4
- 10-05-2009, 07:25 PM #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
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.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; } }
- 10-05-2009, 07:29 PM #2
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
You pushed Strings and tried to pop integers.
Push integers.
- 10-05-2009, 07:35 PM #3
Java Code:int i = Integer.parseInt(theStack.pop() ); // will parse the string to integer
My Hobby Project: LegacyClone
- 10-05-2009, 07:40 PM #4
Senior Member
- Join Date
- Nov 2008
- Posts
- 105
- Rep Power
- 0
Similar Threads
-
Cannot start j2me polish in netbeans
By arnab321 in forum CLDC and MIDPReplies: 10Last Post: 09-05-2011, 11:18 AM -
Big O Notation
By dsym@comcast.net in forum New To JavaReplies: 1Last Post: 02-21-2009, 06:02 PM -
Postfix-Notation
By little_polarbear in forum New To JavaReplies: 9Last Post: 09-09-2008, 04:24 PM -
Big Oh Notation and Heaps
By gibsonrocker800 in forum Advanced JavaReplies: 8Last Post: 01-25-2008, 10:06 PM -
Using Stacks
By ravian in forum New To JavaReplies: 7Last Post: 11-28-2007, 09:53 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks