Web Analytics Made Easy -
StatCounter Need Help Writing A JavaScript Switch (Case) Statement - CodingForum

Announcement

Collapse
No announcement yet.

Need Help Writing A JavaScript Switch (Case) Statement

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Need Help Writing A JavaScript Switch (Case) Statement

    Please help me write a JavaScript Switch (Case) statement to test whether a prompt entered grade is between 100 and 90, 90 and 80, 80 and 70, and so forth. I wrote a similar " working " program using the JavaScript If-Else-If statement, and encountered no major problems. However, I am having difficulty doing the same using a JavaScript Switch (Case) statement.

    See below sample " non-working " attempt to use a JavaScript Switch (Case) statement to test whether a prompt entered grade is between 100 and 90, 90 and 80, and so forth:

    Thank you in advance for your people person assistance. - Wayne

    ////////////////////////////////////////////////////////////////////////////////

    <body>

    <script language="javascript">
    <!--

    var grade = prompt("enter student's javascript course grade:", "grade")

    // switch (case) statement

    switch (grade)
    {
    case (grade <= 100 && grade >=90):
    alert ("hurray; i earned an a!!!!!!")
    break

    case (grade <= 90 && grade >=80):
    alert ("i was robbed; i only rerceived a b!!!!")
    break


    default:
    alert ("invalid grade; grade must be between 0 and 100")
    }

    -->
    </script>

    </body>

  • #2
    The cases in the code are valid, but they are Boolean cases that evaluate to either true or false, depending on the grade.

    So, the "grade" value must be either Boolean true or Boolean false for the "I received a [grade letter]" alert to appear.

    To use switch statements correctly, use exact cases that tell what the value could be, such as this code:

    Code:
    switch (grade) 
    { 
    case 100:
    case 99:
    case 98:
    case 97:
    case 96:
    case 95:
    case 94:
    case 93:
    case 92:
    case 91:
    case 90:
    alert ("hurray; i earned an a!!!!!!") 
    break 
    case 89:
    case 88:
    case 87:
    case 86:
    case 85:
    case 84:
    case 83:
    case 82:
    case 81:
    case 80:
    alert ("i was robbed; i only received a b!!!!") 
    break 
    
    
    default: 
    alert ("invalid grade; grade must be between 0 and 100") 
    }
    This simple example shows the inefficiency of switch statements for some tasks. In a task like this, if/else statements work much better:

    Code:
    if(grade <= 100 && grade >=90)
     alert ("hurray; i earned an a!!!!!!") 
    else if(grade <= 90 && grade >=80) 
     alert ("i was robbed; i only received a b!!!!") 
    else
     alert ("invalid grade; grade must be between 0 and 100")
    I hope this helps.

    Comment


    • #3
      The key to the below code is realizing that the cases are examined in the order listed, and the first one to "make a match" forces execution out of the switch statement (unless you forgot the "break;"!!)

      Code:
      switch (true)  {
         case grade >= 90:
            alert ("Yay, I got an A!");
            break;
      
         case grade >=80:
            alert("Pay your fee and get a B");
            break;
      
         case grade >=70:
            alert("Oh, I C how this works!");
             break;
      
         case grade >=60:
            alert("Color the picture of this pretty pony and you\'ll feel better");
             break;
      
          default:
             alert ("can you say \'Affirmative Action\'?");
             break;
      
      }  // switch ()

      Comment


      • #4
        To use switch statements correctly, use exact cases that tell what the value could be, such as this code:
        This guy get paid by the line of code

        Comment


        • #5
          I could be wrong....

          DEFN:
          Code:
          [b]
          switch (expression){
             case label : 
                statements;
                break;
             case label : 
                statements;
                break;
             ...
             default : statements;
          }
          [/b]
          But in your case, I dont think you want to use case

          I think it would look something like this:

          Code:
          <script language="javascript"> 
          <!-- 
            var grade = parseInt(prompt("enter student's javascript course grade:", "grade"));
          
          <EDIT REMOVED!> Use RadarBobs code its best.
          
          // --> 
          </script>
          I dont remember if there is a way to do ranges in JavaScript in a case statement...

          An expression is (A && B) a label is just (B) from what I understand...

          -S. Bob
          DOH! this is what I get for looking it up :P
          Last edited by Soldier Bob; Jul 12, 2002, 04:37 PM.

          Comment


          • #6
            A small point; but we're leaning here. Note the highlight in the code snippit below.

            case (grade <= 100 && grade >=90):
            alert ("hurray; i earned an a!!!!!!")
            break
            case (grade <= 90 && grade >=80):
            alert ("i was robbed; i only rerceived a b!!!!")
            break


            "90" is both an A and a B.
            "That's not Logical" - Mr. Spock

            Comment


            • #7
              Code:
              <html>
              <head>
              <title>untitled</title>
              </head>
              <body>
              <script type="text/javascript">
              
              function getGrade() {
              var grade = prompt('Enter student&#92;'s javascript course grade:', 'grade');
              if (/^(100|\d{2})%?$/.test(grade)) { //valid input - '100' or 2 digits, optional '%'
              grade = grade.replace(/%/, ''); //trim '%' if there
              if (grade == '100') alert('Perfect. Go to the head of the class.');
              else {
              switch (grade.charAt(0)) { //use tens
              case '9' : alert('Hurray; I earned an A!');
              break;
              case '8' : alert('I was robbed; only received a B!!!!');
              break;
              case '7' : alert('Average; I like being an average person.');
              break;
              case '6' : if (grade.charAt(1)>'4') { //>64
              alert('Well, heck, I passed didn&#92;'t I?');
              break;
              }
              default: 
              alert ('Click on "Summer School Enrollment" below...');
              break;
              }
              }
              }
              else {
              alert('Please enter a numerical grade of 100 or less.');
              getGrade();
              }
              }
              
              getGrade();
              
              </script>
              </body>
              </html>

              Comment


              • #8
                adios;
                First, I acknowledge the spirit in which this code sample is offered. Likewise I offer the following for everyone's consideration in the context of "time is money" and "hey, I'm the poor sob who has to maintain this code!"

                Why make one case an "if" and the rest of the cases a "switch"? IMHO that just complicates the code. If I wanted to add a new alert for a perfect score I'd just add it as the first case thus:

                Code:
                switch (true) {
                   case grade==100:
                      alert ("Perfect Score! Great Job!");
                      break;
                
                   case grade >= 90:
                      .... original code ......
                }
                Now, you have only one statement, not two - that's imperically / theoritically less complex.


                Additionally, again IMHO, the technique you demonstrate, while interesting for certain coding demo purposes, unnecessarily obsfucates the purpose of the code. Ahem... my version is virtually self documenting; your's definitely is not. In other other words, "production code" is no place for showing off

                I use numbers in the switch that map directly to the domain "grades". Ninety, one hundred, eighty, etc. map directly to grades. On the other hand, by manipulating the digits and using nine, eight, etc. ; it's close, but it removes your "code model" just a bit from the domain of "grades" and thus causes the following:
                • Requires more testing
                • Requires in-line documentation to clearly explain the "mapping" from the digits to the grade domain.
                • Takes longer to comprehend; even for the original author (a month later for example)
                • Changes are more complex and error prone because of the "compounding" by using a SWITCH inside an IF
                • It's very unconventional coding style. I say use IF-ELSE-IF or SWITCH, but not both.


                Make things as simple as possible, but no simpler
                - Albert Einstein
                Last edited by RadarBob; Jul 14, 2002, 12:02 AM.

                Comment


                • #9
                  Adios,

                  Not to be rude or anything, but I think you have WAY too much time on your hands.

                  Comment

                  Working...
                  X