Java special character in conditional check

203 views Asked by At

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?

2

There are 2 answers

0
Vitruvie On BEST ANSWER

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.

0
Amir Afghani On

Try running this experiment:

public class Test {
    public static void main(String[] args) {
        System.out.println(Character.getNumericValue('['));
    }
}

and notice that it returns -1.

From the API:

Returns: the numeric value of the character, as a nonnegative int value; -2 if the character has a numeric value that is not a nonnegative integer; -1 if the character has no numeric value.

So the correct way to do this is

command.charAt(index) == '[' as has been pointed out.