Sparks
Sparks

Reputation: 105

shorten multiple if statements for the same variable

So I need to check the value of one variable and set the value of another appropriately. What I'm currently doing which I suspect there's a shortcut for is:

if(i==a){j=foo}
if(i==b){j=bar}
if(i==c){j=etc}
...

I'm hoping there's some sort of code that looks something like:

if(i==
a: j=foo,
b: j=bar,
c: j=etc,
....
)

obviously that syntax is made up and not right. But I'm just hoping there's some way of saving me typing out an if statement for every possible thing. All the other articles I can find are trying to set multiple values of i to the same value of j which is not helping here.

Thanks for help!

Upvotes: 0

Views: 337

Answers (1)

bweber
bweber

Reputation: 4092

You might want to try the switch(variable) {...} statement like this:

switch(i){
    case a : j = foo; break;
    case b : j = bar; break;
    case c : j = etc; break;
    default : // i was not equal to any of those
}

Upvotes: 4

Related Questions