Java Reference
In-Depth Information
Finally, the fourth and fi fth case statements output a message that the number the user has entered is
too high.
case 4:
document.write(“Too high!”);
break;
You do need to add a default case in this example, since the user might very well (despite the instruc-
tions) enter a number that is not between 1 and 5 , or even perhaps a letter. In this case, you add a mes-
sage to let the user know that there is a problem.
default:
document.write(“You did not enter a number between 1 and 5.”);
break;
A default statement is also very useful for picking up bugs — if you have coded some of the case
statements incorrectly, you will pick that up very quickly if you see the default code being run when it
shouldn't be.
You fi nally have added the closing brace indicating the end of the switch statement. After this you out-
put a line to indicate where the execution continues.
}
document.write(“<br />Execution continues here”);
Note that each case statement ends with a break statement. This is important to ensure that execution
of the code moves to the line after the end of the switch statement. If you forget to include this, you
could end up executing the code for each case following the case that matches.
Executing the Same Code for Different Cases
You may have spotted a problem with the switch statement in this example — you want to execute the
same code if the user enters a 1 or a 2, and the same code for a 4 or a 5. However, in order to achieve
this, you have had to repeat the code in each case. What you want is an easier way of getting JavaScript
to execute the same code for different cases. Well, that's easy! Simply change the code so that it looks
like this:
switch (secretNumber)
{
case 1:
case 2:
document.write(“Too low!”);
break;
case 3:
document.write(“You guessed the secret number!”);
break;
case 4:
case 5:
Search WWH ::




Custom Search