Assignment024

Random Number Switch

As you know, if statements allow you to evaluate a condition (name=="Manuel", y<=5, i !=8) and run a block of code (Based on whether a condition evaluates to true or false). In addition, you have learned that you can provide alternate blocks of code by using else statements and evaluate multiple conditions by using elseif statements.

Still, even with elseif statements, your code can get rather cumbersome when evaluating many conditions. In some cases, when you have a single expression, consider using the switch statement. Use switch statements when you have many single expressions to check or when conditions evaluate to non true/false values. I can buy shoes, an outfit, tickets to a play, and a weekend getaway!

Here's some code:



<script language="Javascript" type="text/javascript">

//Gift certificates are given in denominations of
//100, 200, 300, 400, or 500
//Based on the of the certificate you are
//going shopping and/or out with your honey.

//declare the variable
var giftdollars;

//set the variable to an initial value using a random number
giftdollars = Math.floor(Math.random() * 5) + 1;
giftdollars = giftdollars * 100;

switch (giftdollars)
{
case 100:
document.write("I can buy shoes!");
break;

case 200:
document.write("I can buy shoes and an outfit!");
break;

case 300:
document.write("I can buy shoes, an outfit, and tickets to a play!");
break;

case 400:
document.write("I can buy shoes, an outfit, tickets to a play, and a weekend getaway!");
break;

default:
document.write("I'm buying an X-Box 360!");
}

</script>

The above code evaluates each case, and runs the subsequent block of code. The break statement steps out of the switch statement and the default provides the code to run when no case is a match.