This forum is now read-only. Please use our new forums! Go to forums

banner
Close banner
0 points
Submitted by Bobby7
about 11 years

Can you use else if / if else statements multiple times?

I know the following doesn’t work:

var computerChoice = Math.random();

if (computerChoice<=0.25){
computerChoice = "rock";
}

else if (computerChoice<=0.50){
computerChoice = "paper";

else if (computerChoice<=0.75){
computerChoice = "Tank";

}
else {
computerChoice = "scissors";
}

But out of curiosity, if you wanted more choices using Math.random, are you limited to just if, else if, and else? If you are, do you get round this by nesting if/else statements inside other ones or is there another method?

Answer 514a8bea4a9e0e2522000cf1

0 votes

Permalink

You can use multiple else if but each of them must have opening and closing curly braces {}.

if (){
}
else if (){
}
else if(){
}
else{
}

You can replace if with switch statement which is simpler but only for comparing same variable.

You will learn switch in Section 5 - Control Flow. Part 2

points
Submitted by Henner Setyono
about 11 years

1 comments

Bobby7 about 11 years

Yeah, I figured that out as I completed more exercises. At the time, I didn’t realise I’d missed the closing brace after ‘paper’, which confused me. Thanks for replying.