出于某种原因,当我在这里测试我的“100-50-40”时,我得到的是“60”而不是“10”。所有其他组合都有效,例如“10+20”和“40-20”。当我尝试连续减去多个数字时会出现问题。有任何想法吗?
public double add(String exp){
String left = "";
String right = "";
double leftValue = 0;
double rightValue = 0;
double answer = 0;
for(int i=0;i<exp.length();i++)
{
if(exp.charAt(i)=='+')
{
right = exp.substring(i+1, exp.length());
leftValue = subtract(left);
rightValue = add(right);
answer = leftValue + rightValue;
return answer;
}
else
{
left = left + exp.substring(i,(i+1));
}
} // End for loop
answer = subtract(exp);
return answer;
} // End add method
//guaranteed there are no addition operators in exp
public double subtract(String exp){
String left = "";
String right = "";
double leftValue = 0;
double rightValue = 0;
double answer = 0;
for(int i=0;i<exp.length();i++)
{
if(exp.charAt(i)=='-')
{
right = exp.substring(i+1, exp.length());
leftValue = Double.parseDouble(left);
rightValue = subtract(right);
answer = leftValue - rightValue;
return answer;
}
else
{
left = left + exp.substring(i,(i+1));
}
} // End for loop
answer = Double.parseDouble(exp);
return answer;
}