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.
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.
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;
}
Java - switch case, Multiple cases call the same function
You have to use case
keyword for each String like this :
switch (str) {
//which mean if String equals to
case "apple": // apple
case "orange": // or orange
case "pieapple": // or pieapple
handleFruit();
break;
}
Edit 02/05/2019
Java 12
From Java 12 there are a new syntax of switch case proposed, so to solve this issue, here is the way:
switch (str) {
case "apple", "orange", "pieapple" -> handleFruit();
}
Now, you can just make the choices separated by comma, the an arrow ->
then the action you want to do.
Another syntax also is :
consider that each case return a value, and you want to set values in a variable, lets suppose that handleFruit()
return a String
the old syntax should be :
String result; // <-------------------------- declare
switch (str) {
//which mean if String equals to
case "apple": // apple
case "orange": // or orange
case "pieapple": // or pieapple
result = handleFruit(); // <----- then assign
break;
}
now with Java 12, you can make it like this :
String result = switch (str) { // <----------- declare and assign in one shot
case "apple", "orange", "pieapple" -> handleFruit();
}
Nice syntax
switch statement with multiple cases which execute the same code
Not possible. the case
items must be VALUES. You have expressions, which means the expressions are evaluated, and the result of that expression is them compared against the value in the switch()
. That means you've effectively got
switch(...) {
case TRUE: ...
case TRUE: ...
}
You cannot use multiple values in a case. YOu can, however, use the "fallthrough support":
switch(...) {
case 'one':
case 'two':
return 'one or two';
case 'three':
case 'four':
return 'three or four';
}
Why is my switch statement running multiple cases?
It's because you don't have a break
statement. Without it, the code will "fall through".
var x = 10;
switch (x) {
case 10:
console.log('With break');
break;
case 20:
console.log('I never run');
break;
}
console.log('-------');
switch (x) {
case 10:
console.log('Without');
case 20:
console.log('a break');
case 30:
console.log('it just');
case 40:
console.log('keeps going');
}
Related Topics
Replace "\\" with "\" in a String in C#
"A Project with an Output Type of Class Library Cannot Be Started Directly"
How to Ignore JSONproperty(Propertyname = "Somename") When Serializing JSON
How to Compile and Execute New Code at Runtime in .Net
View/Edit Id3 Data for Mp3 Files
How to Get the Exif Data from a File Using C#
Best Way to Remove Duplicate Entries from a Data Table
How to Bind an Enum to a Combobox Control in Wpf
What Is Cool About Generics, Why Use Them
How to Validate Console Input as Integers
Does Disposing Streamreader Close the Stream
Random Number Generator with No Duplicates
C# Open a New Form Then Close the Current Form
How to Access a Control Inside a Xaml Datatemplate
Calculating Distance Between Two Latitude and Longitude Geocoordinates