+ 2

how to use or (||) oparetor in java switch?

https://code.sololearn.com/cA3A189a18A7/?ref=app plz fix this error

15th Mar 2021, 2:30 PM
Jawad Ibrahim Shopnil
Jawad Ibrahim Shopnil - avatar
8 Antworten
+ 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
15th Mar 2021, 2:56 PM
Jayakrishna 🇮🇳
+ 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.
15th Mar 2021, 4:42 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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 -> //... }
15th Mar 2021, 8:05 PM
zemiak
+ 3
@Jawad Shopnil that @zemiak has a simple solution ..That's awesome new feature i think. Its new to me.. tqs to zemiak..
16th Mar 2021, 9:39 AM
Jayakrishna 🇮🇳
+ 1
can you explain why is not working?
15th Mar 2021, 2:58 PM
Jawad Ibrahim Shopnil
Jawad Ibrahim Shopnil - avatar
+ 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..
15th Mar 2021, 3:11 PM
Jayakrishna 🇮🇳
+ 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
15th Mar 2021, 10:01 PM
zemiak
0
Write a program that asks the user to input a sentence and then counts the number of words in the sentence؟؟ please help😥
18th Mar 2021, 8:05 PM
Zozo Znzon
Zozo Znzon - avatar