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");
}
}
You cannot specify the ||
operator between two char
s 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.