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