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.
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.
} // ...
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();
You can't do this use if then statement.
if(age > 79)
{
//do stuff
}
else if(age > 50)
{
//do stuff
}
else
{
/do stuff
}
etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With