The original question came from this web site.
And this is the third revision. I delete spaces and validate an equation before computing.
public class Main {
private static final String EQUATION_REGEX = "^-?\\d+((\\/|\\*|\\+|-)\\d+)*$";
// http://www.careercup.com/question?id=4911380140392448
public static void main(String[] args) {
String equationWithAllSigns = "-1 * 5 * 4/2 - 8*9 - 16+1";
// Delete spaces
equationWithAllSigns = equationWithAllSigns.replaceAll("\\s+", "");
// Compute the equation if it's valid
if (equationWithAllSigns.matches(EQUATION_REGEX)) {
double allSignsResult = computeWithAllOperations(equationWithAllSigns);
System.out.println(allSignsResult);
} else {
System.out.println("Invalid equation");
}
}
private static double computeWithAllOperations(String input) {
double result = 0.0;
/*
* 1. Replace - with +- except the minus which is the first symbol of
* the input.
* 2. Split the input string by +
* 3. Calculate the products and quotients
* 4. Sum up the results
*/
// (\\d)- is used instead of - to support strings starting with -
String parts[] = input.replaceAll("(\\d)-", "$1+-").split("\\+");
for (String part : parts) {
result += computeMultAndDivision(part);
}
return result;
}
private static double computeMultAndDivision(String part) {
String[] parts = part.split("(?=[/*])|(?<=[/*])");
double result = Double.parseDouble(parts[0]);
for (int i = 1; i < parts.length; i += 2) {
String op = parts[i];
double val = Double.parseDouble(parts[i + 1]);
switch (op) {
case "*":
result *= val;
break;
case "/":
result /= val;
break;
}
}
return result;
}
}