Using two values for one switch case statement
You can use have both CASE
statements as follows.
case text1:
case text4:{
//blah
break;
}
SEE THIS EXAMPLE:The code example calculates the number of days in a particular month:
class SwitchDemo {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
This is the output from the code:
Number of Days = 29
FALLTHROUGH:
Another point of interest is the break statement. Each break statement
terminates the enclosing switch statement. Control flow continues with
the first statement following the switch block. The break statements
are necessary because without them, statements in switch blocksfall
: All statements after the matching case label are executed in
through
sequence, regardless of the expression of subsequent case labels,
until a break statement is encountered.
EXAMPLE CODE:
public class SwitchFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
This is the output from the code:
August
September
October
November
December
Using Strings in switch Statements
In Java SE 7 and later, you can use a String object in the switch
statement's expression. The following code example, ,
displays the number of the month based on the value of the String
named month:
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
The output from this code is 8.
FROM Java Docs
Switch case with multiple values for the same case
Execution continues until it reaches a break;
. Therefore, you can list cases one after the other to get the following code execute on either one of those cases.
String commentMark(int mark) {
switch (mark) {
case 0 : // Enter this block if mark == 0
return "mark is 0" ;
case 1:
case 2:
case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
return "mark is either 1, 2 or 3" ;
// etc.
default :
return "mark is not 0, 1, 2 or 3" ;
}
}
The return
statements above serve to get out of the function. If you do not want to return
, you have to use break;
after each block, of course. This code below is equivalent to the one above.
String commentMark(int mark) {
String msg;
switch (mark) {
case 0 : // Enter this block if mark == 0
msg = "mark is 0" ;
break;
case 1:
case 2:
case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
msg = "mark is either 1, 2 or 3" ;
break;
// etc.
default:
msg = "mark is not 0, 1, 2 or 3" ;
break; // this is a good habit, in case you change default to something else later.
}
return msg;
}
Switch case with multiple values
You can remove the break to get OR
switch(code){
case case1:
case case2:
doSomething();
break;
}
Switch statement for multiple cases in JavaScript
Use the fall-through feature of the switch
statement. A matched case will run until a break
(or the end of the switch
statement) is found, so you could write it like:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
}
Multiple cases in switch statement
There is no syntax in C++ nor C# for the second method you mentioned.
There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.
How do you accept multiple values for a switch case?
You can "fall through" by having sequential case
statements without a break
between them.
switch (input) {
case 1:
cout << "option 1 \n";
break;
case 2:
case 3:
cout << "option 2 and 3 \n";
break;
default:
break;
}
Note that some compilers support range syntax like case 50 ... 100
but this is non-standard C++ and will likely not work on other compilers.
Java switch statement multiple cases
Sadly, it's not possible in Java. You'll have to resort to using if-else
statements.
PHP: How to use same logic for multiple cases in Switch statement
You are using the cases wrong. You can't use ||
in the middle of a case to say 2 or 3 or 4, but you can list multiple cases after one another without having a a break
in between to perform the same action.
$a = 5;
switch ($a) {
case 1:
$b = 1;
break;
case 2:
case 3:
case 4:
$b = 2;
break;
case 5:
$b = 3;
break;
}
return $b;
What is happening with your original code is that you get case 2 || 3 || 4
as the equivalent of case (2 || 3 || 4):
, which becomes case true:
. The ||
operator compares the truthfulness of either 2, 3 and 4 -- which all are non-zero values, so the expression evaluates to true.
You should also note that $b
is undefined when $a
is not one of 1, 2, 3, 4 or 5. You should therefor have a default
case in your switch statement, or a declaration of $b
before the switch.
Can there be multiple value assignments for the enhanced switch statement?
There's no tuple unpacking in Java. A quick alternative that still uses a switch expression could use a custom class (using Pair
in the following example):
Pair<Boolean, String> val = switch (num) {
case 0 -> Pair.of(true, "zero!");
case 1 -> Pair.of(true, "one!");
default -> Pair.of(false, "unknown :/");
};
boolean val1 = val.getLeft();
String val2 = val.getRight();
Related Topics
Pdfbox - Signature Validity Checkmark Not Visible in Acrobat Reader
Having a Column Name as Input Parameter of a Preparedstatement
Org.Postgresql.Util.Psqlexception: Fatal: Sorry, Too Many Clients Already
Why Never Change the Notifier in Receiving a Change Event
Getting Active Window Information in Java
Java.Lang.Unsupportedclassversionerror Unsupported Major.Minor Version 51.0
Automated Tests for Java Swing Guis
Jni Converting Jstring to Char *
Foreach VS Foreachordered in Java 8 Stream
Equivalent of Waitforvisible/Waitforelementpresent in Selenium Webdriver Tests Using Java
Splitting a CSV File with Quotes as Text-Delimiter Using String.Split()
In Java Critical Sections, What Should I Synchronize On
How to Select an Item from a Dropdown List Using Selenium Webdriver with Java
When Does Java's Thread.Sleep Throw Interruptedexception