Case Statement With Multiple Values in Each 'When' Block

Case statement with multiple values in each 'when' block

In a case statement, a , is the equivalent of || in an if statement.

case car
when 'toyota', 'lexus'
# code
end

Some other things you can do with a Ruby case statement

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;
}

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 blocks fall
through
: All statements after the matching case label are executed in
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

Multiple case/when conditions with ||

Please do search before asking question, you can get its answer easily in other questions

choice = gets.chomp
case choice
when 'js', 'JS'
puts 'Websites!'
when 'Python', 'python'
puts 'Science!'
when 'Ruby', 'ruby'
puts 'Web apps!'
else
puts "I don't know!"
end

After suggestions

choice = gets.chomp
puts case choice
when 'js', 'JS'
'Websites!'
when 'Python', 'python'
'Science!'
when 'Ruby', 'ruby'
'Web apps!'
else
"I don't know!"
end

Best way to do a PHP switch with multiple values per case?

For any situation where you have an unknown string and you need to figure out which of a bunch of other strings it matches up to, the only solution which doesn't get slower as you add more items is to use an array, but have all the possible strings as keys. So your switch can be replaced with the following:

// used for $current_home = 'current';
$group1 = array(
'home' => True,
);

// used for $current_users = 'current';
$group2 = array(
'users.online' => True,
'users.location' => True,
'users.featured' => True,
'users.new' => True,
'users.browse' => True,
'users.search' => True,
'users.staff' => True,
);

// used for $current_forum = 'current';
$group3 = array(
'forum' => True,
);

if(isset($group1[$p]))
$current_home = 'current';
else if(isset($group2[$p]))
$current_users = 'current';
else if(isset($group3[$p]))
$current_forum = 'current';
else
user_error("\$p is invalid", E_USER_ERROR);

This doesn't look as clean as a switch(), but it is the only fast solution which doesn't include writing a small library of functions and classes to keep it tidy. It is still very easy to add items to the arrays.

Using 'case' with multiple conditions

You have two problems with your code. First of all, this:

[1..3 && 1]

is an array with one element. Since .. has lower precedence than &&, you're really writing 1..(3 && 1) which is just a complicated way of saying 1..1. That means that your case is really:

case[roll1, roll2]
when [1..1]
"Low / Low"
when [4..1]
"High / Low"
when [1..2]
"Low / High"
when [4..2]
"JACKPOT!!"
end

The second problem is that Array doesn't override the === operator that case uses so you'll be using Object#=== which is just an alias for Object#==. This means that your case is equivalent to:

if([roll1, roll2] == [1..1])
"Low / Low"
elsif([roll1, roll2] == [4..1])
"High / Low"
elsif([roll1, roll2] == [1..2])
"Low / High"
elsif([roll1, roll2] == [4..2])
"JACKPOT!!"
end

[roll1, roll2] will never equal [some_range] because Array#== compares element by element and roll1 will never == a range; furthermore, you're also comparing arrays with different sizes.

All that means that you have a complicated way of saying:

result = nil

I'd probably just use an if for this:

result = if (1..3).include?(roll1) && roll2 == 1
'Low / Low'
elsif (4..6).include?(roll1) && roll2 == 1
'High / Low'
...

or you could use === explicitly:

result = if (1..3) === roll1 && roll2 == 1
'Low / Low'
elsif (4..6) === roll1 && roll2 == 1
'High / Low'
...

but again, watch out for the low precedence of ...

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.



Related Topics



Leave a reply



Submit