I am trying to make a postfix calculator in Java. I am using a Java stack. Everything seems to work fine except that I seem to be unable to push onto the stack. Here is my method that would push to the stack and calculate the given equations:
private void jButtonEqualsActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Postfix calculations done here
Stack<String> jStack = new Stack<>();
String field = jTextField1.getText();
char ch = 0;
for (int c = 0; c < field.length(); c++)
{
ch = field.charAt(c);
System.out.println(field );
System.out.println(ch );
//check for an integer, if its valid, push it onto stack
if (ch >= 0 && ch <= 9)
{
System.out.println("pushing an integer to the stack." );
jStack.push(Character.toString(ch));
}
//check for operators and calculate accordingly
else if( Character.toString(ch) == "+" )
{
System.out.println("popping from stack" );
int rVal = Integer.parseInt(jStack.pop());
int lVal = Integer.parseInt(jStack.pop());
jStack.push(Integer.toString(rVal + lVal));
}
else if( Character.toString(ch) == "-" )
{
int rVal = Integer.parseInt(jStack.pop());
int lVal = Integer.parseInt(jStack.pop());
jStack.push(Integer.toString(lVal - rVal));
}
else if( Character.toString(ch) == "*" )
{
int rVal = Integer.parseInt(jStack.pop());
int lVal = Integer.parseInt(jStack.pop());
jStack.push(Integer.toString(rVal * lVal));
}
else if( Character.toString(ch) == "/" )
{
int rVal = Integer.parseInt(jStack.pop());
int lVal = Integer.parseInt(jStack.pop());
jStack.push(Integer.toString(lVal / rVal));
} else {
//
}
}
if ( !jStack.empty())
{
String result = jStack.pop();
System.out.println( result );
jTextField1.setText(result);
}
else {
System.out.println( "Your stack is empty and it shouldnt be." );
}
}
No matter what I enter, I always get the message that my stack is empty at the end, and none of my Prints trigger that tell me it is pushing or popping. Have I missed some vital step?