JRJC - How To Use a Switch Statement

The general form of the switch statement looks like this:

    switch( expression )
    {
        case constant:
            stuff
            break;
        case constant:
            stuff
            break;
        case constant:
            stuff
            break;
        default:
            stuff
            break;
    }

You can have as many case statements as you want. You don't have to have a default statement if you don't want to.

expression is something that has to evaluate to something that is the same type as all of your constant values. After expression is evaluated, the resulting value is compared to each constant until a match is found and that stuff is executed. When break is encountered, the switch statement is exited.

If no match is found, the stuff under default is executed.

If no match is found and there is no default, then the switch statement is exited.

Example:


    switch ( dayOfWeek )
    {
        case 1:
            showMondayAgenda();
            break;
        case 2:
            showTuesdayAgenda();
            break;
        case 3:
            showWednesdayAgenda();
            break;
        case 4:
            showThursdayAgenda();
            break;
        case 5:
            showFridayAgenda();
            break;
        default:
            System.out.println("We don't work on weekends!");
    }

My wild theories that you don't need to know right now: For more information on switch statements, read page 175 of Just Java 1.2., or pages 71 through 73 in Just Java 2 (sixth edition).






For more information, please visit my java site.

And for a change of pace, you can visit my permaculture site.






© 2000 paul wheaton