Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use conditional statements in switch-case in Android?

I can't seem to find a straight forward yes or no to this in my searching. In Android, is there a way to use a conditional statement in case-switch? For example, with age being an int value:

switch (age){
case (>79):
 // Do this stuff
 break;
case (>50):
 // Do this other stuff
break;
etc, etc

I've tried several ways to code this (completely shooting in the dark) and come up with compiler errors, and I've also tried a nested IF statement, but it doesn't support break so the logic breaks down and it ends up also executing ELSE code lower in the nesting. I feel like switch-case is my best bet but I can't find an example of the correct syntax for what I'm trying to do! Any help would be appreciated. All the examples I find just use switch-case for a few things like if it is a 1 do this, if it's a 2 do that, but without making 100 case statements to check against age, I'm not sure how else to work this.

like image 839
Robert Avatar asked Sep 19 '14 19:09

Robert


3 Answers

No. You cannot do this,

switch (age){
case (>79):
  // Do this stuff
  break;
case (>50):
  // Do this other stuff
  break;
}

You need an if and else,

if (age > 79) {
 // do this stuff.
} else if (age > 50) {
 // do this other stuff.
} // ...
like image 142
Elliott Frisch Avatar answered Sep 30 '22 18:09

Elliott Frisch


It is not possible. Instead, Try this minimalist approach

 age > 79 ? first_case_method() 
          : age > 50 ? second_case_method() 
          : age > 40 ? third_case_method() 
          : age > 30 ? fourth_case_method() 
          : age > 20 ? fifth_case_method()
          : ... 
          : default_case_method();
like image 32
Williem Avatar answered Sep 30 '22 18:09

Williem


You can't do this use if then statement.

if(age > 79)
{
   //do stuff
}
else if(age > 50)
{
   //do stuff
}
else
{
   /do stuff
}

etc...

like image 44
brso05 Avatar answered Sep 30 '22 18:09

brso05