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 twochar
s to mean this character or this other one as you try here :||
is a logic OR that has to be placed between two boolean expressions such as :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 :
To specify more logical ORs, using a collection that contains the valid chars is an interesting possibility :
To improve the performance (if you have many valid characters), you could use a
Set
:If the conditional statement has to be used multiple times, instantiating the collections a single time is better.