这是一个有点牵强的问题。我正在编写一个 Lisp 评估器算法,该算法采用输入表达式,例如:
(+ (- 6) (* 2 3 4) (/ (+ 3) (*) (- 2 3 1)))
问题是:由于操作 (- 6) 和 (*),它会引发 EmptyStack 错误
当我将它写为 (- 0 6) 和 (* 1) 时,它会以正确的结果正确编译。我认为它正在寻找从某些东西中减去,并乘以某些东西(不能没有数字)。它与我的操作数评估的结构有关。我想在程序本身中实现这一点,而不必手动添加零进行减法和一个用于乘法。关于如何去做的任何想法?
我整天都在盯着它看,似乎无法弄清楚为什么我的推送/弹出结构会以这种方式起作用。我尝试使用正则表达式进行试验,但这似乎没有奏效。
程序结构:
1) 使用两个堆栈:Object 类型的expressionStack和 Double 类型的currentOperationStack。
2) evaluateCurrentOperation()方法评估当前操作:
从 expressionStack 中弹出操作数并将它们推送到 currentOperationStack 直到找到运算符。
在 currentOperationStack 的操作数上使用运算符。
将结果推送到表达式堆栈中。
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);
}
}