Switch

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #1

    Switch

    Switch
    If there are large number of selections the if statement can become very cumbersome.
    When the comparisons are for equality with integral values known in advance we may use switch. e.g. if d is a char
    Code:
       if (d=='s') System.out.println(" Saturday or Sunday");
       else if (d=='m') System.out.println(" Monday");
            else if (d=='t') System.out.println(" Tuesday");
                //etc......
    could be implemented as a switch
    Code:
        
        switch (day)
           {
            case 's': System.out.println("Saturday or Sunday");
                      break;
            case 'm': System.out.println("Monday");
                      break;
            case 't': System.out.println("Tuesday or Thursday");
                      break;
            case 'w': System.out.println("Wednesday");
                      break;
            case 'f': System.out.println("Friday");
                      break;
            default:  System.out.println("I don't know this day");
           }
    note:
    (1) The condition must have type byte, char, int etc.
    (2) The expression after each case must be a constant.
    (3) The expression must be assignable to the type of the switch.
    (4) break is required to break out of switch
Working...