用字符串解析数学表达式

时间:2015-01-08 15:40:28

标签: java android beanshell

我一直试图找到解决方案好几天了,我无法弄清楚这一点。我正在编写一个程序(在某一点上)接受数学表达式并显示答案。我使用beanshell解析器来执行此操作,但评估不是问题。当用户按下"撤消"按钮,这个方法应该撤消最后一个输入(操作(+ - * /)或数字。它在最奇怪的时候给我错误,我无法弄清楚原因。有人能帮忙吗?我会感谢任何提前帮助的人!

public void undo(View v) throws EvalError{
    Interpreter interpreter1 = new Interpreter(); // interpreter to evaluate user solution
    userExpressionList.remove(userExpressionList.size()-1); // remove last element of userExpressionList
    String tempExp3 = "";
    if (userExpressionList.size() != 0){
        for (String element:userExpressionList) {
            tempExp3 = tempExp3 + element;
            if (tempExp3.substring(tempExp3.length() - 1).equals("+") || tempExp3.substring(tempExp3.length() - 1).equals("-") ||
                tempExp3.substring(tempExp3.length() - 1).equals("*") || tempExp3.substring(tempExp3.length() - 1).equals("/")) {
                    displaySolution = (Double)interpreter1.eval(tempExp3.substring(0, tempExp3.length() - 2));
                    userSolution = tempExp3.substring(tempExp3.length() - 1);
                }
            else {
                displaySolution = (Double) interpreter1.eval(tempExp3.substring(0, tempExp3.length() - 1));
                userSolution = "";
                }
            Log.i("tempExp3", tempExp3);
            Log.i("displaySolution", displaySolution.toString());
        }
        textViewUserSolution.setText(displaySolution.toString());
    }
    else {
        clear(findViewById(R.id.clearButton));
        textViewUserSolution.setText("");
    }
    Log.i("isExpectingNumber before invert", String.valueOf(isExpectingNumber));
    isExpectingNumber = !isExpectingNumber;
    Log.i("isExpectingNumber after invert", String.valueOf(isExpectingNumber));
    textViewUserExpression.setText(tempExp3);
}

如果您需要更多信息,请询问。我非常感谢你们提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

这个问题很可能是基于这样的假设:"回归"逐个字符将始终产生可以毫无问题地评估的东西。

考虑:

1+23 - you can undo '3' and eval "1+2"
1+2  - you can undo '2' but you can't eval "1+", just "1"
1+2+ - you can undo '+' and eval "1+2"

因此,

switch(exp3.charAt(exp3.length()-1)){
case '+': case '-': case '*': case '/':
    // 1+2+
    sol = int.eval( exp3.substring( 0, exp3.length()-1 ) ); // not -2!       
    usrSol = exp3.substring(exp3.length() - 1);
    break;
default:
    if( exp3.length() > 2 ){
        char d = exp3.charAt(exp3.length()-2);
        if( '0' <= d && d <= '9' ){
             // 1+23
             sol = int.eval(exp3.substring(0, exp3.length() - 1));
        } else {
             // 1+2
             sol = int.eval(exp3.substring(0, exp3.length() - 2));
        }
    } else {
        // "12"
        sol = int.eval(exp3.substring(0, exp3.length() - 1));
    }
    usrSol = "";
    break;
}