代码之家  ›  专栏  ›  技术社区  ›  Keith Hinton

中缀表达式解算器中出现空堆栈异常

  •  0
  • Keith Hinton  · 技术社区  · 7 年前

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

    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 回复  |  直到 7 年前
        1
  •  1
  •   samabcde    7 年前

    假设输入表达式为“3+4” 在线54

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

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

    if(isInteger(token) == true)
    

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

         value2 = valueStack.pop();
    

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

    表达式=表达式。replaceAll(“[\t\n]”,“”)+“=”;