1.5.4 Switch Statement

Add this to your Selection project.

NOTES:  
  • only int and char data types may be used to in the control expression. In this case (month) must be either an int or a char.
  • String and enumerated data types will also work
  • breaks are required after each case statement or all case statements up to the break will execute

switch Demo

public class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                     || (year % 400 == 0) )
                    numDays = 29;
                else
                    numDays = 28;
                break;
        }
        System.out.println("Number of Days = " + numDays);
    }
}
from the Oracle site
Comments