简体   繁体   English

条件中的Java特殊字符

[英]Java special character in conditional

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 aZ and 0-9 worked perfectly, but when I step through the debugger, the conditional for the brackets fail every time. 我的问题是这一行: if (command.charAt(index) == 123)使用ASCII值检查aZ和0-9效果很好,但是当我逐步通过调试器时,括号的条件失败每次。 Is it illegal to use the conditional like this? 使用这样的条件是否非法?

Just use the char primitive: 只需使用char基元:

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

Produces much clearer code and always works. 产生更清晰的代码,并且始终有效。

Try running this experiment: 尝试运行此实验:

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

and notice that it returns -1. 并注意它返回-1。

From the API: 从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; -2,如果字符的数字值不是非负整数; -1 if the character has no numeric value. 如果字符没有数字值,则为-1。

So the correct way to do this is 所以正确的方法是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM