The function belows validates if a mathematical expression, say 12 + 2 * (9 - 3) / 4
, does not have operators that are next to each other. It returns false
if an operator is next to another operator. Otherwise, it returns true
. For example, if the input expression is 2++1
, it will return false
. The function also recursively evaluates expressions that are inside pairs of parentheses.
private boolean validateOperators(String expression)
{
if (!validateEndCharacters(expression)) {
return false;
}
Stack s = new Stack(15); // Stack is a user-defined class.
char[] operators = { '+', '-', '*', '/' };
char prevOperator = '\0';
String subexpression = "";
boolean addSubexpression = false;
boolean isValid = false;
for (char c : expression.toCharArray()) {
if (addSubexpression) {
if (c == '(') {
s.push("(");
} else if (c == ')') {
s.pop();
if (s.isEmpty()) {
// We found the end of the expression inside the parentheses.
isValid &= this.validateOperators(subexpression);
subexpression = "";
prevOperator = '\0';
addSubexpression = false;
}
}
subexpression += Character.toString(c);
} else {
if (c == '(') {
addSubexpression = true;
s.push("(");
} else if (this.isIn(c, operators) && prevOperator == '\0') {
prevOperator = c;
} else if (this.isIn(c, operators) && prevOperator == '\0') {
isValid &= false;
break;
} else if (Character.isDigit(c)) {
prevOperator = '\0';
}
}
}
if (!s.isEmpty()) {
return false;
}
return isValid;
}
private boolean validateEndCharacters(String expression)
{
char[] operators = { '+', '-', '*', '/' };
if (this.isIn(expression.charAt(0), operators) ||
this.isIn(expression.charAt(expression.length() - 1), operators)) {
return false;
}
return true;
}
How else can I improve the functions?
'('
, decremented on')'
and tested for 0 to check a subexpression, and for (-1) to verify parens balance. \$\endgroup\$0
. Correct? \$\endgroup\$true
.isValid
starts as false and, as far as I can see, is never set to true. \$\endgroup\$