Prev | Current Page 195 | Next

Carl Reynolds and Paul Tymann

"Schaum's Outline of Principles of Computer Science"


switch
The last control structure we will discuss here is the switch statement. Like the if statement, the
switch statement allows your program to select certain statements to execute under certain conditions. The
switch statement is more complex, and one can always use a series of if statements instead of a switch
statement, but switch is very appropriate and readable for some programming problems.
Suppose we have a group of students and want to assign them to different dorms depending upon whether
they are freshmen, sophomores, juniors, or seniors. Let??™s assume that the variable yearInSchool is coded
as an int, and is set to 1 for freshmen, 2 for sophomores, 3 for juniors, and 4 for seniors. We could then use
this code to decide to which dorm each student should be assigned:
74 PROGRAMMING IN JAVA [CHAP. 5
switch( yearInSchool ) {
case 1: System.out.println( "Oberlies Hall" );
break;
case 2: System.out.println( "Kiriazides Hall" );
break;
case 3: System.out.println( "Glisson Dorm" );
break;
case 4: System.out.println( "Valk Hall" );
break;
default: System.out.println( "illegal year" );
}
If a student is a freshman, the student will be assigned to Oberlies Hall; if the student is a sophomore, the
student will be assigned to Kiriazides Hall; etc.


Pages:
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
Władysławowo noclegi pity pozycjonowanie bilety lotnicze świnoujście noclegi