Hi,
I am working on an assignment where I had to take code using ‘if’ and in the instructor’s words transform it into code using ‘switch’ and I must have the same outcome as the code using ‘if’.
I realize this may not be the best way of using ‘switch’ but that is the assignment I’ve been given.
The //numbers in the code are the numbers I’m using to test.
My problem with the code as is:
1) When I type alpha characters into the prompt, the comment in the default document.write is not returned as I expected it would be – I may just not understand the ‘default’ exactly and how it works.
2) I believe the top three lines of code are supposed to be
var myAge = prompt(“Enter your age “, “”);
myAge = parseInt(myAge);
switch (myAge) {
My understanding is the data entered is converted to a number and that number is stored in ‘myAge’ and then compared to each line of applicable code. However, written this way the code does not execute. If I use switch (true), the code executes,
Any suggestions, tips, help is appreciated – thank you.
Here is my code:
var myAge = Number (prompt(“Enter your age “, 30));
myAge = parseInt(myAge);
switch (true)
{
case (myAge >= 0 && myAge <= 10) && (myAge >= 80 || myAge <= 10): //5
document.write(“myAge is between 0 and 10 <br />”);
document.write (“myAge is 80 or above OR 10 or below <br />”);
break;
case (!(myAge >= 0 && myAge <=10) && (myAge >= 80 || myAge <= 10) && (myAge >= 30 && myAge <=39 || (myAge >= 80 && myAge <= 89))): //88
document.write (“myAge is NOT between 0 and 10 <br />”);
document.write (“myAge is 80 or above OR 10 or below <br />”);
document.write(“myAge is between 30 and 39 or myAge is between 80 and 89 <br />”);
break;
case (!(myAge >= 0 && myAge <=10) && myAge >= 30 && myAge <=39 || (myAge >= 80 && myAge <= 89)): //33
document.write (“myAge is NOT between 0 and 10 <br />”);
document.write(“myAge is between 30 and 39 or myAge is between 80 and 89 <br />”);
break;
case (!(myAge >= 0 && myAge <=10) && (myAge >= 80 || myAge <= 10)): //90
document.write (“myAge is NOT between 0 and 10 <br />”);
document.write (“myAge is 80 or above OR 10 or below <br />”);
break;
case (!(myAge >= 0 && myAge <=10)): //20
document.write (“myAge is NOT between 0 and 10 <br />”);
break;
default:
document.write(“You did not enter a number. Please enter a number.”);
break;
}
document.write(“<BR>Execution continues here”);
</script>