Tanvir
Tanvir

Reputation: 1683

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... E.g-

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

....... enter image description here

Upvotes: 0

Views: 132

Answers (4)

Phix
Phix

Reputation: 9910

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.

Upvotes: 0

Inon Stelman
Inon Stelman

Reputation: 965

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;

Upvotes: 0

Jamshid
Jamshid

Reputation: 340

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.

Upvotes: 1

Kevin Coppock
Kevin Coppock

Reputation: 134714

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.

Upvotes: 2

Related Questions