1

evaluate到目前为止,我有一种方法可以加、减和乘以字符串(例如“5*5”)。但是,当我尝试用三位数(“5 * 10”)评估单个数字时,它返回“5”而不是“50”。我认为我的问题是它只取两位数的第一个字符串并进行相应的评估。有任何想法吗?

这是我的代码:

public double evaluate(String exp){
        String left = "";
        String right = "";
        double leftValue = 0;
        double rightValue = 0;
        double answer = 0;
        //ensures expression matches an appropriate expression (i.e. 2+2, not "2"
        if(exp.length()==1)
        {
            //if single digit, return double value
            return Double.parseDouble(exp);
        }
        //searching for a "+"
        for(int i=0;i<exp.length();i++)
        {
            if(exp.charAt(i)=='+')
            {
                right = exp.substring(i+1, exp.length());
                leftValue = subtract(left);
                rightValue = evaluate(right);
                answer = leftValue + rightValue;
                return answer;
            }   
            else
            {
                left = left + exp.substring(i,(i+1));

            }

        } // End for loop
        answer = subtract(exp);
        return answer;
    } // End evaluate method

    // Guaranteed there are no addition operators in exp 
    public double subtract(String exp){
        String leftString = "";
        String rightString = "";
        double leftValue = 0;
        double rightValue = 0;
        double answer = 0;

        for(int i=exp.length()-1;i>=0;i--)
        {
            if(exp.charAt(i)=='-')
            {
                // Convert rightString into Double
                rightValue = Double.parseDouble(rightString);
                leftString = exp.substring(0,i);
                leftValue=subtract(leftString);
                answer = leftValue - rightValue;
                return answer;
            }   
            else
            // Accumulating the right string
            {
                rightString = rightString + exp.substring(i,(i+1));
            }
        } // End for loop
        answer= multiply(exp);

        return answer;

...then the code goes onto multiplication, etc....

    } // End evaluate method
4

2 回答 2

4

您可以使用 ScriptEngine 类并将其评估为 javascript 字符串

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");        
Object result = engine.eval("5*10");
于 2013-05-24T15:17:43.610 回答
0

subtract您“向后”“构建”rightString字符串的方法中,即转换5*1001*5= 5。
您可能需要更改它:

// Accumulating the right string
{
    rightString = rightString + exp.substring(i,(i+1));
}

对此:

// Accumulating the right string
{
    rightString = exp.substring(i,(i+1)) + rightString;
}
于 2013-05-24T15:17:59.993 回答