View Full Version : Java stacks
When I pop stuff out of my Stack in Java, it comes off as an Object, how can I convert it to 'int'? I need to use simple arithmetic on it and put the answer back on the stack, so how do i convert it to whatever, since i cant seem to put it back in as an 'int'? I seem to have been pushing stuff in as 'Character' objects. I tried this to convert to 'int':
p=Integer.parseInt(r.toString());
And after the job is done what do I do to push it back on the stack so i can display the answer???
UnitedWeStand
07-30-02, 10:26 PM
Can you show the code that you are using to push values onto the stack? If you are using Character objects, you are only going to be able to represent 0-9, are you sure that is what you want to do?
To convert Character objects to ints try this:
// the (Character) code will coerce the Object back into a Character
Character ch = (Character)stack.pop() ;
// get the char version of the Character
char c = ch.charValue() ;
// converts the char c into an int using base 10
int num = Character.digit( c , 10 ) ;
If you want to push that int back onto the stack, you'll need to wrap it in an Integer object first, like so:
stack.push( new Integer( num ) ) ;
What I was basically trying to do is push any digits from an existing string buffer called 'postfix' onto a stack and pop them if i encountered any operators. Then i evaluate the operation and push the answer back onto the stack.
Here's my code:
public void postfixEvaluator()
{
char d,o;
int m,y=0,p,q,ans;
Object r,s;
postfix.append(")");
m=postfix.length();
for(y=0;y<m;y++)
{
d=postfix.charAt(y);
if(d=='+' || d=='-' || d=='*' || d=='/')
{
r=s2.pop();
s=s2.pop();
p=Integer.parseInt(r.toString());
q=Integer.parseInt(s.toString());
if(d=='+')
ans=p+q;
Integer a=new Integer(ans);
String x=new String(a.toString());
s2.push(x);
}
else
{
Character D=new Character(d);
s2.push(D);
}
}
vBulletin® v3.7.3, Copyright ©2000-2008, Jelsoft Enterprises Ltd.