中缀表达式求解器

时间:2017-11-06 05:37:33

标签: java exception stack infix-notation

所以我的程序假设采用语法正确的中缀表达式 包含整数操作数和GUI中的四个算术运算符(+ - * /)并显示结果。不幸的是,如果我输入一个像3 + 4这样的简单表达式,程序会抛出一个空堆栈异常。我只是刚刚开始使用堆栈,所以请原谅我,如果它的东西很简单,我会出错。请帮忙!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;


public class inFix extends JFrame
{
   private Container contents;
   private JLabel infixLabel, resultLabel, result;
   private JTextField infixText;
   private JButton evaluate;

   public inFix()
   {
      super("Infix Expresion Evaluator");
      contents = getContentPane();
      contents.setLayout( new FlowLayout() );

      infixLabel = new JLabel("Enter Infix Expression:");
      infixText = new JTextField("", 14);

      evaluate = new JButton("Evaluate");

      resultLabel = new JLabel("Result:");
      result = new JLabel("???");

      contents.add( infixLabel );
      contents.add( infixText );
      contents.add( evaluate );
      contents.add( resultLabel );
      contents.add( result );


      ButtonHandler bh = new ButtonHandler();

      evaluate.addActionListener( bh );

      setSize( 350, 200 );
      setVisible( true );
   }

   private class ButtonHandler implements ActionListener
   {
      public void actionPerformed( ActionEvent ae )
      {
         result.setText(infix(infixText.getText()));
      }
   }


   public String infix(String expression)
   {
      expression=expression.replaceAll("[\t\n ]", "")+"=";
      String operator = "*/+-";
      int value1, value2;
      char ch;
      StringTokenizer tokenizer = new StringTokenizer(expression, operator, true); 
      Stack<Integer> valueStack = new Stack<Integer>();
      Stack<Character> operatorStack = new Stack<Character>();

      while(tokenizer.hasMoreTokens())
      {
         String token = tokenizer.nextToken();
         if(isInteger(token) == true)
            valueStack.push(Integer.parseInt(token));
         else if(token.charAt(0) == '(')
            operatorStack.push(token.charAt(0));
         else if(token.charAt(0) == ')')
            while(operatorStack.peek() != '(')
            {
               value1 = valueStack.pop();
               value2 = valueStack.pop();
               valueStack.push(solver(value1, value2, operatorStack.pop()));
            }
         else if(token.charAt(0) == '+' || token.charAt(0) == '-' || token.charAt(0) == '*' || token.charAt(0) == '/')
         {
            while(!operatorStack.isEmpty() && precedence(token.charAt(0)) <= precedence(operatorStack.peek()))
            {
               value1 = valueStack.pop();
               value2 = valueStack.pop();
               valueStack.push(solver(value1, value2, token.charAt(0)));
            }
            operatorStack.push(token.charAt(0));
         }
      }
      while(!operatorStack.isEmpty())
      {
         value1 = valueStack.pop();
         value2 = valueStack.pop();
         ch = operatorStack.pop();
         valueStack.push(solver(value1, value2, ch));
      }


      String result = Integer.toString(valueStack.pop());
      return result;     
   }

   public static boolean isInteger(String s)
   {
      try
      { 
         Integer.parseInt(s);
      } 
      catch(NumberFormatException e)
      {
         return false; 
      } 
      catch(NullPointerException e) 
      {
         return false;
      }
      return true;
   }
   public int solver( int value1, int value2, char operator)
   {
      if(operator == '*')
         return value1 * value2;
      else if(operator == '/')
         return value1 / value2;
      else if(operator == '+')
         return value1 + value2;
      else if(operator == '-')
         return value1 - value2;
      else
         return 0;
   }

   public int precedence(char op)
   {
      if(op == '+' || op == '-')
         return 1;
      else if(op == '*' || op == '/')
         return 2;
      else
         return -1;
   }   


   public static void main( String [] args )
   {
      inFix infixsolver = new inFix();
      infixsolver.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

}

1 个答案:

答案 0 :(得分:1)

假设输入表达式为“3 + 4” 第54行

expression=expression.replaceAll("[\t\n ]", "")+"=";

表达式变为“3 + 4 =” 在令牌化器操作之后,令牌为[“3”,“+”,“4 =”],这会在第65行上为令牌“4 =”产生错误结果

if(isInteger(token) == true)

因此,当您在第89行弹出时,值的数量不足

     value2 = valueStack.pop();

要解决问题,请删除第54行中的+“=”

expression=expression.replaceAll("[\t\n ]", "")+"=";