简体   繁体   中英

Switch-case with variations in android

I wonder if I can turn the following chart into switch-case statement in android. I know I can do it with if-else but I just wonder if I can... Eg-

switch (bodyfat)
case 2-4 : show (Essential Fat);
case 6-13 : show (Athelete Fat);

....... 在此处输入图片说明

In this case you're better off sticking with an if-else statement. The equivalent for a switch case (which I don't recommend using) would be something like this:

switch(bodyfat) {
    case 2:
    case 3:
    case 4:
        show (Essential Fat);
        break;
    case 6:
    case 7:
    //...etc.
}

Then it just falls through for any of the values. You have to have a case for every value, though. For a range of values like this you're better off sticking with if-else.

switch (bodyfat) {
case 2:
case 3:
case 4: show (Essential Fat); break;

}

instead of this:

if (bodyfat >= 2 && bodyfat =< 4) {
 show (Essential Fat);
} else if (bodyfat >= 6 && bodyfat =< 13) {
show (Athelete Fat);
}

you can try this.

You can do it with switch case in the following way:

switch (bodyfat)
    case 2: 
    case 3:
    case 4:
        show (Essential Fat);
        break;
    case 6: 
    case 7:
    case 8:
    case 9: 
    case 10:
    case 11:
    case 12: 
    case 13:
        show (Athelete Fat);
        break;

I'm a fan of tertiary statements for a two-outcome check:

IFat result = (bodyfat >= 2 && bodyfat <= 4) ? EssentialFat : AthleteFat;
show(result);

Assumes interfaces or subclass structure, but thought I'd include this in the discussion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM