Java后缀计算器。不能推到堆叠?

时间:2016-10-18 17:22:45

标签: java calculator

我正在尝试用Java创建一个后缀计算器。我正在使用Java堆栈。一切似乎工作得很好,除了我似乎无法推入堆栈。这是我的方法,它将推送到堆栈并计算给定的方程式:

    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." );
     }
} 

无论我输入什么,我总是得到消息,我的堆栈在结尾处是空的,并且我的所有Prints都没有触发告诉我它正在推或弹。我错过了一些重要的步骤吗?

0 个答案:

没有答案