+ 2
how to use or (||) oparetor in java switch?
https://code.sololearn.com/cA3A189a18A7/?ref=app plz fix this error
8 Answers
+ 4
You cant use || binary operator with strings in switch case there..
Alternatively you can use
case "A" :
case "a" :
{ same logic for both without using break;} it works
+ 4
Hello Jawad Shopnil
There is no deeper reason, it is just how the switch statement is designed.
For some reason you also can't uses ranges like this: case 1...10:
Would be nice but Java didn't implemented it.
If you want to use || or && then you need to use if statements.
Or as Jayakrishna🇮🇳 mentioned you can use of the so callled "fall through". Here is a small example:
public class Program
{
public static void main(String[] args) {
String test = "A";
switch(test){
case "A":
case "a": System.out.println("works");
break;
}
}
}
Executes case A and because there is no break case a will also execute.
+ 3
you can also do
String type = scanInput.nextLine().toUpperCase();
or from Java 14 there is option to use syntax
switch (type) {
case "A", "a" -> {
//...
}
case "B", "b" -> {
//...
}
default ->
//...
}
+ 3
@Jawad Shopnil that @zemiak has a simple solution ..That's awesome new feature i think. Its new to me.. tqs to zemiak..
+ 1
can you explain why is not working?
+ 1
cases should result into a numarical value.. so switch case only works with int, char. in java it also allows strings..
Binary operator not works with strings. . So "A" || "a" invalid in java..
+ 1
in Java specification
15.24. Conditional-Or Operator ||
Each operand of the conditional-or operator must be of type boolean or Boolean, or a compile-time error occurs.
https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.24
0
Write a program that asks the user to input a sentence and then counts the number of words in the sentence؟؟
please help😥