Switch Statement

As mentioned earlier, if you were to write an if statement where you wanted to a lot of actions depending on different values, it would be better using the switch statement. The structure of this is as follows:

switch(variable) {

  • case value is certain value:

    • perform action

      break;

  • ..

    default:

    • perform action

      break;

}

An example program of the switch statement is as follows:

   1 #!/usr/bin/env seed
   2 
   3 var readline = imports.readline;
   4 var curr_char = readline.readline("Enter a character> ");
   5 
   6 switch (curr_char)
   7 {
   8   case ' ':
   9     print ("is a space character");     
  10     break;
  11   case '<':
  12     print ("is <");     
  13     break;
  14   case '>':
  15     print ("is >");
  16     break;
  17   default:
  18     print ("is something else");
  19     break;      
  20 };

The following gets input from user and puts it into curr_char variable:

var readline = imports.readline;
var curr_char = readline.readline("Enter a character> ");

The following statement sets up the switch statement using the curr_char variable

switch (curr_char)

This is the statement that is used for each comparison. To use pseudo code, each instance of this is case that curr_char is a certain value perform action. In this instance if curr_char is equal to space. There can be any number of JavaScript commands but it has always has to end with the break statement. This means that it is the end of statements for this particular case.

  case ' ':
    print ("is a space character");     
    break;

The next two case statements test to see if curr_char is equal to '<' and '>' and executes command. Every switch statement has to have a default part. This is required because if any of the other cases is not true then perform this.

  default:
    print ("is something else");
    break;

The following program shows how the case statement would like when using the if/else statements.

   1 #!/usr/bin/env seed
   2 
   3 var readline = imports.readline;
   4 
   5 var curr_char = readline.readline("Enter a character> ");
   6 
   7 if (curr_char == ' ')
   8   print ("is a space character");
   9 else if (curr_char == '<')
  10     print ("is <");
  11 else if (curr_char == '>')
  12     print ("is >");
  13 else
  14     print ("is something else");

As you can see it is a lot less understandable!

Projects/Seed/Tutorial/basic/switch (last edited 2013-11-22 19:19:57 by WilliamJonMcCann)