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
You can't do this use if then statement.
if(age > 79)
{
//do stuff
}
else if(age > 50)
{
//do stuff
}
else
{
/do stuff
}
etc...
You can't use conditional statements with switch
.
But you CAN do it with if
statements! If you have a loop you can use continue
to stop any upcoming lines and start from the beginning of the innermost loop.
if(age>76){
// Code...
continue;
}else if(age>50){
// More Code...
continue;
}else{
// Even more code...
continue;
}
If you are using a loop you might want to look at What is the "continue" keyword and how does it work in Java?. This is not a good place to use switch.
if(age > 79)
{
//do stuff
continue; // STOP FLOW HERE AND CONTINUE THE LOOP
}
else if(age > 50)
{
//do stuff
continue; // STOP FLOW HERE AND CONTINUE THE LOOP
}
each case of switch is supposed to be an integer or String since JavaSE 7 and you are trying to feed a boolean value to it so its not possible .Read oracle doc to know about java switch in detail http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
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();