Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Postfix Expressions Problem

807607Jan 4 2007 — edited Jan 4 2007
I wrote a program for my AP Comp Sci A class that takes a postfix expression (e.g. 32+) and converts it into an infix expression (e.g. 3+2) and then solves it. It worked before I converted it into the 'solve' method, but now I did (because its required), it keeps giving me an EmptyStackException on the line "
if(comparingyay.compareTo("+")==0)
                     stk.push(stk.pop()+stk.pop());
"
If anyone can help me debug this, I would be forever greatful.
 
import java.util.*;
   import java.io.*;
    public class PostfixExpressions																									
   {
       public static void main(String[] args)
      {
         Scanner scan=new Scanner(System.in);
         String in=scan.next();
         int answer=solve(in);
         System.out.println(answer);
      }    
       public static int solve(String y)
      {
         Stack<Integer> stk= new Stack<Integer>();
         for(int x=0;x<y.length();x++)
         {
            char chars1=y.charAt(x);
            if(Character.isLetterOrDigit(chars1))
            {
               Integer ints=new Integer(0); 
               stk.push(ints.valueOf(y.substring(x,x+1)));
            }
            String comparingyay=y.substring(x,x+1);
            if(comparingyay.compareTo("+")==0||comparingyay.compareTo("-")==0||
               comparingyay.compareTo("*")==0||comparingyay.compareTo("/")==0)
            {
               if(!stk.isEmpty())
               {
                  if(comparingyay.compareTo("+")==0)
                     stk.push(stk.pop()+stk.pop());
                  else if(comparingyay.compareTo("-")==0)	  
                  {
                     int b=stk.pop();
                     int a=stk.pop();
                     stk.push(a-b);
                  }
                  else if(comparingyay.compareTo("/")==0)
                  {
                     int b=stk.pop();
                     int a=stk.pop();
                     stk.push(a/b);
                  }
                  else if(comparingyay.compareTo("*")==0)
                     stk.push(stk.pop()*stk.pop());
               }
            }
         }
         return stk.pop();
      }
   }
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 1 2007
Added on Jan 4 2007
1 comment
98 views