CIS 160 Selection Part II
- Use many-branched selection in Java (switch)
Many-branched selection (switch)
- Traditional multi-branch selection allows branching based on equality to integral values.
In some languages you may also be able to branch based on String values. Java added the
abilty to branch based on String values in version 7.
- Multi-branch selection statements are "switch" statements in Java, C, and C++. In
Visual Basic, they are "Select Case" statements.
- Multi-branch selection may be less flexible then if/else, but is very useful for
certain situations which have a very limited number of input values (such as menu
selections).
- "If" statements easily handle ranges of values (such as hours > 40, or
age > 21 && age < 40), but switch statements may or may not depending
on the language. Visual Basic "Select Case" statements do handle ranges of values easily,
but Java's "switch" statement does not handle ranges of values.
- // this example assumes that option is an int value
switch (option) {
case 1:
System.out.println("Loading from file");
break;
case 2:
System.out.println("Saving to file");
break;
case 3:
System.out.println("Printing report");
break;
case 4:
System.out.println("Terminating program");
break;
default: // default catches any option with no matching case
System.out.println("Invalid choice");
}
- // this example assumes that option is a char value
// it allows for multiple chars to match one branch
switch (option) {
case '1':
case 'L':
case 'l':
System.out.println("Loading from file");
break;
case '2':
case 'S':
case 's':
System.out.println("Saving to file");
break;
case '3':
case 'P':
case 'p':
System.out.println("Printing report");
break;
case '4':
case 'Q':
case 'q':
System.out.println("Terminating program");
break;
default: // default catches any option with no matching case
System.out.println("Invalid choice");
}
- // you can now also match Strings in Java
// this example assumes that option is a String object
switch (option) {
case "Load":
System.out.println("Loading from file");
break;
case "Save":
System.out.println("Saving to file");
break;
case "Print":
System.out.println("Printing report");
break;
case "Quit":
case "Exit":
System.out.println("Terminating program");
break;
default: // default catches any option with no matching case
System.out.println("Invalid choice");
}