I am creating a program and part of the program receives an expression with the following conditions:
-
Allowed chars: “1234567890+-*/() ” — notice the space at the end of them
-
Must be balanced
-
Starts and ends with “(” and “)”
-
The separation is a single white space between each operator, operand or/and parenthesis:
I have done the first two conditions, but I am stuck with the third one.
Examples:
( 1 + ( ( 22 – 322 ) * 4 / 5 ) ) <<< Valid
( 1+ ( ( 22 – 322 ) * 4 / 5 ) ) <<< Invalid
( 1 + (( 22 – 322 ) * 4 / 5 ) ) <<< Invalid
( 1 + ( ( 22 – 322 )* 4 / 5 ) ) <<< Invalid
Here is what I have done so far:
public static boolean isSSWS(String e) {
boolean valid = false;
int indexOfWS = 0;
Character preChar = '\0';
Character postChar = '\0';
while(!valid && (indexOfWS < e.length())) {
indexOfWS = e.indexOf(" ", indexOfWS + 1);
preChar = e.charAt(indexOfWS - 1);
postChar = e.charAt(indexOfWS + 1);
if(preChar == ' ' || postChar == ' ') {
return false;
}
}
return true;
}
isSSWS, is *S*eparated with *S*ingle *W*ite *S*pace
indexOfWS, index of white space
Edited, I didn’t notice that numbers shouldn’t have spaces. Bit messy, but works for all inputs I’ve tried.