Java Reference
In-Depth Information
7-3. Executing Code Based on a Specified
Value
Problem
You want to execute different blocks of code based on the value of a singular expres-
sion.
Solution
Consider using a switch statement if your variable or expression result is one of the
allowed switch types and you want to test for equality against a type-compatible
constant. These examples show various ways to use the switch statement, including
a new feature that became available in Java 7: the ability to switch on Strings . First,
let's play some Rock-Paper-Scissors! The RockPaperScissors class shows two
different switch statements: one using an int as the switch expression type, and
the other using an enum type.
// See RockPaperScissors.java
public class RockPaperScissors {
enum Hand { ROCK, PAPER, SCISSORS, INVALID };
private static void getHand(int handVal) {
Hand hand;
try {
hand = Hand.values()[handVal - 1];
}
catch (ArrayIndexOutOfBoundsException ex) {
hand = Hand.INVALID;
}
switch (hand) {
case ROCK:
System.out.println("Rock");
break;
case PAPER:
Search WWH ::




Custom Search