Results 1 to 3 of 3

Thread: Java stacks

  1. #1
    chumee
    Guest

    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???

  2. #2
    Registered User UnitedWeStand's Avatar
    Join Date
    Mar 2002
    Location
    Michigan, USA
    Posts
    1,198
    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:



    Code:
    stack.push( new Integer( num ) ) ;

  3. #3
    chumee
    Guest
    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);

    }

    }

Bookmarks

Posting Permissions

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