我有一个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
答案 0 :(得分:4)
您可以使用ScriptEngine类并将其评估为javascript字符串
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("5*10");
答案 1 :(得分:0)
在subtract
方法中,您向后“构建”rightString
字符串“,即将5*10
转换为01*5
= 5。
你可能需要改变它:
// Accumulating the right string
{
rightString = rightString + exp.substring(i,(i+1));
}
到此:
// Accumulating the right string
{
rightString = exp.substring(i,(i+1)) + rightString;
}