/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] JavaScript using switch – student learning

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>

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@JMRKEROct 08.2014 — Couple of problems.

  • 1. True || False cannot be used in the switch command. It is looking for the switch (argument) to match the various case qualifiers. Hint: Set the switch (var) variable to a string assignment and then check the case constants to match the string variable.


  • 2. Document.write() is not the proper command to use to display after the page has been rendered. If you do it that way, the program will re-load and start from scratch as if the use had never entered an age value.


  • Take another look at the w3 schools tutorial on using the switch command.
    Copy linkTweet thisAlerts:
    @daveyerwinOct 08.2014 — xx
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 08.2014 — Hi and thank you so much for stepping in!

    When you say set the switch (var) to a string it should look like this [COLOR="#0000CD"]var myAge = Number (prompt("Enter your age ", "30"));[/COLOR]? Do I then need to change all of the cases to be in "" to be strings like this: [COLOR="#0000CD"]case "(myAge >= 0 && myAge <= 10) && (myAge >= 80 || myAge <= 10)":[/COLOR] ?


    I understand what you are saying about using things properly but I'm supposed to follow what little instruction has been provided by the instructor. The first piece of code I had to re-write from the text book is this:

    <script type="text/javascript">

    var myAge = Number(prompt("Enter your age", 30));

    if (myAge >= 0 && myAge <= 10)
    {
    document.write ("myAge is between 0 and 10 <br />");
    }

    if (!(myAge >= 0 && myAge <=10))
    {
    document.write ("myAge is NOT between 0 and 10 <br />");
    }

    if (myAge >= 80 || myAge <= 10)
    {
    document.write ("myAge is 80 or above OR 10 or below <br />");
    }

    if (myAge >= 30 && myAge <=39 || (myAge >= 80 && myAge <= 89))
    {
    document.write("myAge is between 30 and 39 or myAge is between 80 and 89");
    }


    </script>


    The instructions for the next part of the assignment are:

    JavaScript - Assignment 3 &#8211; 5 %

    Task 1: Type In Example Code and Run It &#8211; 1 point - that I did and everything worked.

    [COLOR="#FF0000"]Task 2: Make modifications in the sample code &#8211; 2 point - this is what I'm trying to do now and was told I need to have the same outcome as when using 'if'.[/COLOR]

    Task 3: Write your Own Code &#8211; 2 points - haven't started this.

    A3 Task 1: Type In Example Code and Run It

    Type in Notepad++ editor and test the code samples presented in textbook:

    &#8226; Textbook page 61 &#8211; Multi-condition if statements. Save the file as T1.html. - 'if' code just posted.

    A3 Task 2: Make modifications in the sample code

    Transform the multi-condition if statements sample code (textbook &#8211; page 61) into a switch sample code. Also please save the program as T2.html

    I emailed the instructor for clarification on the results I received and this is his reply:

    [COLOR="#0000CD"]The ranges for which you have to test are as follow:



  • 1. 0 - 10


  • 2. 30 - 39


  • 3. 80 - 89


  • 4. < 0 OR > 89


  • 5. default


  • and each of these ranges requires a unique combination of the original document.write() statements. You will need more cases to get the same output as the textbook example. You could need 6 or 7 cases depending on your code.

    Good luck,

    Ayman

    [/COLOR]
    Copy linkTweet thisAlerts:
    @deathshadowOct 08.2014 — While you can do "Switch with expressions", it's grossly inefficient code from an execution standpoint as you're basically adding extra tests to the scenario. Passing "true" to case as the variable is how you do it, but beware that when you 'break' the secondary tests won't run and you end up pointlessly and needlessly convoluted.

    Of course, the example code you were told to start with is really farking stupid for checking values more than once that are already established, so what you are supposed to do with it being so idiotically stupid only an educator could come up with something that mind-numbingly dumbass.

    Hell, the text doesn't even describe the conditions properly. >=0 and <=10 means it's between -1 and 11. >=30 and <=39 means it's between 29 and 40. The word "between" is not inclusive! :/

    I'd also add a trap for NaN, and as mentioned NOT be trying to use document.write for that.

    &lt;div id="output"&gt;&lt;/div&gt;

    &lt;script type="text/javascript"&gt;&lt;!--

    var
    output = document.getElementById('output'),
    myAge = Number(prompt('Enter your age', 30));

    function echo(txt) {
    output.appendChild(document.createTextNode(txt));
    output.appendChild(document.createElement('br'));
    }

    switch (true) {
    case (myAge &lt;= 0):
    case (myAge === NaN):
    echo('Invalid Age -- must be a non-zero number');
    break;
    case (myAge &lt;= 10):
    echo('myAge is between 0 and 11');
    case (myAge &gt;= 80):
    echo('myAge is above 79 or below 11');
    if (myAge &lt;= 10 || myAge &gt; 89) break;
    case (myAge &gt;= 30 &amp;&amp; myAge &lt;=39):
    echo('myAge is between 29 and 40 or between 79 and 90');
    break;
    }

    --&gt;&lt;/script&gt;


    Though that's some really jacktarded code, that's how it would be done using "switch by expression." *NOTE* I added error condition handling. Basically we keep the number of condition checks down by using case's drop-through. Still needs one IF though to hop out prematurely for the 80+ condition the same time as the thirtysomething condition.

    It's stuff like this that makes me think most IT educators aren't qualified to be teaching jack ****, and are little more than a leech on the teat of society.
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 08.2014 — This is the first time I've laughed since I started working on this assignment - thanks for your reply. I still have multiple assignments, a mid-term and final exam to get through with this instructor. Needless to say I'm hoping he isn't teaching the remaining four courses I have left after this one. The text book for the course is Beginning JavaScript by Paul Wilton and Jeremy McPeak. The instructor takes some of the sample code from each chapter then has us modify it per his instructions and I'm just not understanding some of it and yet I really want to learn this to be able to use it - so frustrating.

    I totally missed the actual ages until you pointed it out - thank you. Reading your code makes sense in my head compared to the way I structured my code based on his instructions and feedback. I prefer to learn how to be efficient when coding and the previous two HTML courses I did really adhered to the W3C and yet this course doesn't seem to at all.

    I think I should put both you and the other person who assisted on standby! Thank you! ?
    Copy linkTweet thisAlerts:
    @JMRKEROct 09.2014 — Using 'deathshadow's example, here is how you could modify it to show other possible prompt inputs without running the program N times.

    [code=php]
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title> HTML5 page </title>
    </head>
    <body>
    <div id="output"></div>
    <script type="text/javascript">
    var output = document.getElementById('output');
    // var myAge = Number(prompt('Enter your age', 30));

    // for testing purposes
    var ranges = ['xx', -1,0,10,20,30,40,50,60,70,80,90]; // various other possible PROMPT inputs
    for (var i=0; i<ranges.length; i++) { testLoop(ranges[i]); }

    function echo(txt) {
    output.appendChild(document.createTextNode(txt));
    output.appendChild(document.createElement('p'));
    }

    function testLoop(myAge) {
    document.getElementById('output').innerHTML += (myAge+' is my Age ---------------------');
    switch (true) {
    case (myAge <= 0):
    case (myAge === NaN): echo('Invalid Age -- must be a non-zero number'); break;

    case (myAge <= 10): echo('myAge is between 0 and 11');
    case (myAge >= 80): echo('myAge is above 79 or below 11');
    if (myAge <= 10 || myAge > 89) break; // switch breakout ONLY under these conditions

    case (myAge >= 30 && myAge <=39): echo('myAge is between 29 and 40 or between 79 and 90'); break;

    default: echo('Default display'); break; // shows all OTHER possibilities
    }
    }
    </script>
    </body>
    </html>

    [/code]
    Copy linkTweet thisAlerts:
    @JMRKEROct 09.2014 — And, as if that were not enough, another alternative solution. [ (testLoop() and LoopTest() functions ]
    [code=php]
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title> HTML5 page </title>
    </head>
    <body>
    <div id="output"></div>
    <script type="text/javascript">
    var output = document.getElementById('output');
    // var myAge = Number(prompt('Enter your age', 30));

    // for testing purposes
    var ranges = ['xx', -1,0,10,20,30,40,50,60,70,80,90]; // various other possible PROMPT inputs
    for (var i=0; i<ranges.length; i++) {
    output.innerHTML += ranges[i]+' is my Age --------------------- ';
    if (isNaN(ranges[i])) { echo('is Not A Number'); } else { testLoop(ranges[i]); LoopTest(ranges[i]); }
    output.innerHTML += '<p>';
    }

    function echo(txt) { output.innerHTML += txt; }

    function testLoop(myAge) {
    output.innerHTML += '<br>';
    switch (true) {
    case (myAge <= 0):
    case (myAge === NaN): echo('Invalid Age -- must be a non-zero number'); break;

    case (myAge <= 10): echo('myAge is between 0 and 11');
    case (myAge >= 80): echo('myAge is above 79 or below 11');
    if (myAge <= 10 || myAge > 89) break; // switch breakout ONLY under these conditions

    case (myAge >= 30 && myAge <=39): echo('myAge is between 29 and 40 or between 79 and 90'); break;

    default: echo('Default display'); break; // shows all OTHER possibilities
    }
    }

    function LoopTest(myAge) {
    echo('<br>');
    var fnd = -1, msg = 'Invalid Entry';
    if (myAge <= 0) { fnd = 0; }
    if ( (myAge > 0) && (myAge <= 10) ) { fnd = 1; }
    if ( (myAge >= 30) && (myAge <= 39) ) { fnd = 2; }
    if ( (myAge >= 80) && (myAge <= 89) ) { fnd = 3; }
    if (myAge >= 90) { fnd = 4; }

    switch (fnd) {
    case 0: msg = 'Age less than or equal to 0'; break;
    case 1: msg = 'Age between 1 and 10 inclusive'; break;
    case 2: msg = 'Age between 30 and 39 inclusive'; break;
    case 3: msg = 'Age between 80 and 89 inclusive'; break;
    case 4: msg = 'Age greater than 89'; break;
    default: msg = 'Default display'; break;
    }
    output.innerHTML += msg;
    }
    </script>
    </body>
    </html>

    <!-- Given parameters:
    The ranges for which you have to test are as follow:

    1. 0 - 10

    2. 30 - 39

    3. 80 - 89

    4. < 0 OR > 89

    5. default
    -->
    [/code]
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 10.2014 — I think I should be taking my course on here! I have copied and pasted and printed this and the addition of the comments really helps me to understand how the code executes. It's frustrating that I'm not learning properly via the course I'm taking.
    ×

    Success!

    Help @BlondieC spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...