Search code examples
javaconditional-statementsconditional-operator

Java special character in conditional check


I have some lines of code that check for brackets in a string.

while (index <= command.length()-1 && done == false) {
    if (command.charAt(index) == 123) { // ASCII value for open bracket
        braces++;
        token = token + command.charAt(index);
        index++;
    } else if (command.charAt(index) == 125) {
        braces--;
        token = token + command.charAt(index);
        index++;
    } else if (braces > 0) {
        if (command.charAt(index) > 47 && command.charAt(index) < 58 || command.charAt(index) > 64 && command.charAt(index) < 123) {
            token = token + command.charAt(index);
            index++;
        } else 
            index++;
    } else if (braces == 0) {
        if (command.charAt(index) > 47 && command.charAt(index) < 58) {
            token = token + command.charAt(index);
            index++;
            if (command.charAt(index) == 123)
                done = true;
            } else {
                index++;
                done = true;
            }
        }
    }
}

The issue I have is with this line: if (command.charAt(index) == 123)

Using the ASCII values for checking for a-Z and 0-9 worked perfectly, but when I step through the debugger, the conditional for the brackets fail every time.

Is it illegal to use conditional checking like this?


Solution

  • Just use the char primitive:

    if (command.charAt(index) == '['){ //Note the single quotes; double quotes won't work
    

    Produces much clearer code and always works.