How can I compare char characters?

六月ゝ 毕业季﹏ 提交于 2019-12-25 03:12:35

问题


Why this Java code doesn't work ? How can add logical comparison like || or $$ to type char in the if statement :

System.out.println("Type Text");
txt = ms.next();
size = txt.length();

for (int i = 0; i < size; i++) {

    if ((txt.charAt(i)) == ('a'||'b')) {
        System.out.println("is the letter A or B");
    }

}

回答1:


You cannot specify the || operator between two chars to mean this character or this other one as you try here :

if ((txt.charAt(i)) == ('a'||'b')) { ...}

|| is a logic OR that has to be placed between two boolean expressions such as :

if (txt.charAt(i) == 'a' || txt.charAt(i) == 'b'){
   ...
}

The Operators tutorial is a very good reference to summarize the operators in Java (essentially about their description and precedence).
To avoid the duplication you can introduce a local variable :

char c = txt.charAt(i);
if (c  == 'a' || c == 'b'){
   ...
}

To specify more logical ORs, using a collection that contains the valid chars is an interesting possibility :

if (Arrays.asList('a', 'b', 'c').contains(txt.charAt(i)){
   ...
}

To improve the performance (if you have many valid characters), you could use a Set:

if (new HashSet<>(Arrays.asList('a', 'b', 'c')).contains(txt.charAt(i)){
   ...
}

If the conditional statement has to be used multiple times, instantiating the collections a single time is better.



来源:https://stackoverflow.com/questions/50864702/how-can-i-compare-char-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!