Postfix Expressions Problem

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.*;

publicclass PostfixExpressions

{

publicstaticvoid main(String[] args)

{

Scanner scan=new Scanner(System.in);

String in=scan.next();

int answer=solve(in);

System.out.println(answer);

}

publicstaticint 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());

elseif(comparingyay.compareTo("-")==0)

{

int b=stk.pop();

int a=stk.pop();

stk.push(a-b);

}

elseif(comparingyay.compareTo("/")==0)

{

int b=stk.pop();

int a=stk.pop();

stk.push(a/b);

}

elseif(comparingyay.compareTo("*")==0)

stk.push(stk.pop()*stk.pop());

}

}

}

return stk.pop();

}

}

>

[3616 byte] By [bcleva] at [2007-11-26 14:07:16]
# 1

You don't check for the number of elements in your stack, you just check whether it's empty and, if not, pop 2 elements (though it might be only 1) off it.

Your program looks rather C-ish; equality checking on Strings is done via equals(), compareTo() is, uhm, unconventional. Though you don't need to check Strings at all while you have chars1.

The Integer conversion part could be done this way:

stk.push(new Integer(chars1 - '0'));

Edit: apart from these comments, your program works for me with the input "32+".

quittea at 2007-7-8 1:53:00 > top of Java-index,Java Essentials,Java Programming...