Reputation: 321
For some reason when I test my "100-50-40" here I am getting "60" instead of "10". All other combinations work, such as "10+20" and "40-20". The problem occurs when I try to subtract multiple numbers in a row. Any ideas?
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;
}
Upvotes: 0
Views: 414
Reputation: 86391
You're getting 90 because you evaluate 50-40 before subtracting the result from 100.
In this code, you're dividing the expression at the first minus:
right = exp.substring(i+1, exp.length());
leftValue = Double.parseDouble(left);
rightValue = subtract(right);
answer = leftValue - rightValue;
The rightValue is "50-40" and the leftValue is 100.
You can address this particular case by finding the last minus.
That said, if you eventually want to handle more complex expressions with other operators and grouping, you may find it useful to read more about hand-writing recursive-descent parsers or using parser generators. With a parser generator, you specify the grammar you want, and the tool builds the code to parse it for you. My own favorite parser generator for Java is Antlr.
Upvotes: 6