Java:Stacks表达式计算器:减去或乘以时的空栈异常

时间:2016-09-30 22:27:04

标签: java algorithm stack expression evaluator

这是一个有点问题。我正在编写一个Lisp求值程序算法,它将输入的表达式写成,例如:

(+ (- 6) (* 2 3 4) (/ (+ 3) (*) (- 2 3 1)))

问题是:由于操作,它会抛出EmptyStack错误     ( - 6)和(*)

当我将其写为( - 0 6)和(* 1)时,它会正确编译并获得正确的结果。我认为它正在寻找减去 FROM 的东西,并乘以某些东西(不能没有数字)。它与我的操作数评估结构有关。我想将它实现到程序本身,而不必手动为减法添加零和一个乘法。关于如何去做的任何想法?

我一整天都在盯着它,似乎无法弄清楚为什么我的推/弹结构以这种方式起作用。我尝试使用正则表达式进行试验,但这似乎并没有成功。

计划结构:

1)使用两个堆栈:Object类型的 expressionStack ,以及Double类型的 currentOperationStack

2) evaluateCurrentOperation()方法评估当前操作:

  • 从expressionStack弹出操作数并将它们推送到currentOperationStack,直到找到一个操作符。

  • 在currentOperationStack上的操作数上使用运算符。

  • 将结果推送到expressionStack。

3) evaluate()方法计算inputExpression中的当前Lisp表达式(使用扫描程序读取,操作数的case语句)并返回结果。

import java.util.*;

public class LispEvaluator {

/**
 * Input expression
 */
private String inputExp;

/**
 * Stacks created for the main expression and current operation.
 */
private Stack<Object> expStack;
private Stack<Double> currentOpStack;


/**
 * Default constructor initializes input and creates Stack objects.
 */
public LispEvaluator()
{
    inputExp = "";
    expStack = new Stack<Object>();
    currentOpStack = new Stack<Double>();
}

/**
 * Constructor sets inputExpr to inputExpression and creates Stack objects.
 * @param inputExpression
 * @throws LispEvaluatorException
 */
public LispEvaluator(String input_Expression) throws LispEvaluatorException 
{
    // If there is no expression, throws an exception.
    if(input_Expression == null)
    {
        throw new LispEvaluatorException("Input statement is null.");
    }

    // Objects created
    inputExp = input_Expression;
    expStack = new Stack<Object>();
    currentOpStack = new Stack<Double>();
}

/**
 * evaluateCurrentOperation() method evaluates the current operation:
 * - Pops operands from expStack and pushes them onto currentOpStack until it finds an operator.
 * - Uses the operator on the operands on currentOpStack.
 * - Pushes the result into exprStack.
 */
private void evaluateCurrentOperation()
{
    String current_Operation;
    boolean numeric = true;

    // Do... while statement sets current operation (while it is numeric).
    do{
        current_Operation = (String.valueOf(expStack.pop()));

        try{
            Double number = Double.parseDouble(current_Operation);
            currentOpStack.push(number);

        }catch(NumberFormatException nfe){
            numeric = false;
        }
    } while(numeric);


    double result;
    switch (current_Operation) {
        case "*":
            result = currentOpStack.pop();
            while(!currentOpStack.isEmpty()){
                result *= currentOpStack.pop();
            }
            break;
        case "/":
            result = currentOpStack.pop();
            while(!currentOpStack.isEmpty()){
                result /= currentOpStack.pop();
            }
            break;
        case "+":
            result = currentOpStack.pop();
            while(!currentOpStack.isEmpty()){
                result += currentOpStack.pop();
            }
            break;
        case "-":
            result = currentOpStack.pop();
            while(!currentOpStack.isEmpty()){
                result -= currentOpStack.pop();
            }

            break;

        default:
            result = currentOpStack.pop();
            break;
    }

    expStack.push(result);

}

/**
 * evaluate() method evaluates the current Lisp expression in inputExpr and returns the result.
 * @throws LispEvaluatorException 
 */
public double evaluate() throws LispEvaluatorException
{
    Scanner inputExprScanner = new Scanner(inputExp);

    /**
     * Breaks the string into single characters using a delimiter.
     */
    inputExprScanner = inputExprScanner.useDelimiter("\\s*");

    /**
     * Scans the tokens in the string (runs while there is a next token).
     */
    while (inputExprScanner.hasNext())
    {

        /**
         * If it has an operand, pushes operand object onto the exprStack.
         */
        if (inputExprScanner.hasNextInt())
        {
            /**
             * Scanner gets all of the digits (regular expression \\d+ means any digit).
             */
            String dataString = inputExprScanner.findInLine("\\d+");

            expStack.push(Double.parseDouble(dataString));
        }

        else
        {
            /**
             * Gets one character in String token.
             */
            String token = inputExprScanner.next();
            char item = token.charAt(0);

            switch(item)
            {
            // If "(", next token is an operator (so do nothing).
            case '(':
                break;

            // If ")", it will evaluate that expression since parenthesis are closed.
            case ')':                   
                evaluateCurrentOperation();

                break; 

            // If there is an operator "* + / -", then it pushes the operator onto exprStack.
            case'*':
                expStack.push("*");
                break;

            case'+':
                expStack.push("+");
                break; 

            case'/':
                expStack.push("/");
                break;

            case'-':
                expStack.push("-");
                break;  

            /**
             * Default throws an error.
             */
                default:
                    throw new LispEvaluatorException(item + " is not a valid operator");
            } // end switch
        } // end else
    } // end while

    /**
     * If you run out of tokens, the value on the top of exprStack is the result of the expression.
     * 
     */

    return Double.parseDouble(String.valueOf(expStack.pop()));
}

/**
 * Reset method sets inputExpr to inputExpression and clears Stack objects.
 * @param inputExpression
 * @throws LispEvaluatorException
 */
public void reset(String inputExpression) throws LispEvaluatorException 
{
    if(inputExpression == null)
    {
        throw new LispEvaluatorException("Input statement is null");
    }

    inputExp = inputExpression;
    expStack.clear();
    currentOpStack.clear();
}

/**
 * Test method to print the result of the expression evaluator.
 * @param s
 * @param expr
 * @throws LispEvaluatorException
 */
private static void evaluateExprTest(String s, LispEvaluator expr) throws LispEvaluatorException
{
    Double result;
    System.out.println("Expression: " + s);
expr.reset(s);
    result = expr.evaluate();
    System.out.printf("Result: %.2f\n", result);
    System.out.println("-------");
}

/**
 * Main method uses test cases to test the evaluator.
 * @param args
 * @throws LispEvaluatorException
 */
public static void main (String args[]) throws LispEvaluatorException
{
    LispEvaluator expr= new LispEvaluator();

    /**
     * Expressions are tested.
     * Note: For each operation written as (- 6), in order for the Stack to continue,
     * it needs to be written as (- 0 6). This way, it is subtracting from a digit.
     */
    String test1 = "(+ 5 0 10)";
    String test2 = "(+ 5 0 10 (- 7 2))";
    String test3 = "(+ (- 0 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)))";
    String test4 = "(+ (- 0 632) (* 21 3 4) (/ (+ 32) (* 1) (- 21 3 1)))";
    String test5 = "(+ 2 6) (* 12 18) (/ (+ 32) (* 1) (- 21 3 1))";
    String test6 = "(+ 1 2 (- 5 1) (*4 11 14))";

    evaluateExprTest(test1, expr);
    evaluateExprTest(test2, expr);
    evaluateExprTest(test3, expr);
    evaluateExprTest(test4, expr);
    evaluateExprTest(test5, expr);
    evaluateExprTest(test6, expr);

}

}

自定义异常类:

public class LispEvaluatorException extends Exception{

    public LispEvaluatorException(String message) {
        super(message);

    }
}

1 个答案:

答案 0 :(得分:0)

修复非常简单:你得到的崩溃是因为一元操作是不同的特性,所以你需要明确地为它们编码。

解决此问题包括两部分:

  • 在第一个pop()
  • 之前添加对空堆栈的检查
  • 添加对一元减号-和一元分区/的检查,它们具有单独的代码路径。

以下是需要修复的代码部分:

switch (current_Operation) {
    case "*":
        if (currentOpStack.isEmpty()) {
            result = 1;
            break;
        }
        result = currentOpStack.pop();
        while(!currentOpStack.isEmpty()){
            result *= currentOpStack.pop();
        }
        break;
    case "/":
        if (currentOpStack.isEmpty()) {
            result = 1;
            break;
        }
        result = currentOpStack.pop();
        if (currentOpStack.isEmpty()) {
            // Unary division
            result = 1.0 / result;
            break;
        }
        while(!currentOpStack.isEmpty()){
            result /= currentOpStack.pop();
        }
        break;
    case "+":
        if (currentOpStack.isEmpty()) {
            result = 0;
            break;
        }
        result = currentOpStack.pop();
        while(!currentOpStack.isEmpty()){
            result += currentOpStack.pop();
        }
        break;
    case "-":
        if (currentOpStack.isEmpty()) {
            result = 0;
            break;
        }
        result = currentOpStack.pop();
        if (currentOpStack.isEmpty()) {
            // Unary minus
            result = -result;
            break;
        }
        while(!currentOpStack.isEmpty()){
            result -= currentOpStack.pop();
        }
        break;

    default:
        result = currentOpStack.pop();
        break;
}

Demo.