Java 17 Recipes


-3. Executing Code Based on a Specified Value


Download 3.2 Mb.
Pdf ko'rish
bet133/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   129   130   131   132   133   134   135   136   ...   245
Bog'liq
Java 17 Recipes

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 expression.
 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 the rock-paper-scissors game! The RockPaperScissors class shows two different 
switch statements: an int as the switch expression type and an enum type.
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;
Chapter 7 Data SourCeS anD ColleCtionS


249
}
switch (hand) {
case ROCK:
System.out.println("Rock");
break;
case PAPER:
System.out.println("Paper");
break;
case SCISSORS:
System.out.println("Scissors");
break;
default:
System.out.println("Invalid");
}
}
private static void playHands(int yourHand, int myHand) {
// Rock = 1
// Paper = 2
// Scissors = 3
// Hand combinations:
// 1,1; 2,2; 3,3 => Draw
// 1,2 => sum = 3 => Paper
// 1,3 => sum = 4 => Rock
// 2,3 => sum = 5 => Scissors
//
switch ((yourHand == myHand) ? 0 : (yourHand + myHand)) {
case 0:
System.out.println("Draw!");
break;
case 3:
System.out.print("Paper beats Rock. ");
printWinner(yourHand, 2);
break;
Chapter 7 Data SourCeS anD ColleCtionS


250
case 4:
System.out.print("Rock beats Scissors. ");
printWinner(yourHand, 1);
break;
case 5:
System.out.print("Scissors beats Paper. ");
printWinner(yourHand, 3);
break;
default:
System.out.print("You cheated! ");
printWinner(yourHand, myHand);
}
}
private static void printWinner(int yourHand, int winningHand) {
if (yourHand == winningHand) {
System.out.println("You win!");
}
else {
System.out.println("I win!");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Let's Play Rock, Paper, Scissors");
System.out.println(" Enter 1 (Rock)");
System.out.println(" Enter 2 (Paper)");
System.out.println(" Enter 3 (Scissors)");
System.out.print("> ");
int playerHand = input.hasNextInt() ? input.nextInt() : -99;
int computerHand = (int)(3*Math.random()) + 1;
System.out.print("Your hand: (" + playerHand + ") ");
getHand(playerHand);
System.out.print("My hand: (" + computerHand + ") ");
Chapter 7 Data SourCeS anD ColleCtionS


251
getHand(computerHand);
playHands(playerHand, computerHand);
}
}
When the RockPaperScissors class is executed, an interactive game begins, allowing 
users to type input at the keyboard. The users can type the number corresponding to the 
entry they’d like to choose, and the computer utilizes random number calculations to 
beat the users’ choices.
Java 7 added the capability to switch on strings. The SwitchTypeChecker class 
demonstrates a string as the switch expression type. The isValidSwitchType() method 
takes a Class object and determines whether the corresponding type is a valid type 
used in a switch expression. So, SwitchTypeChecker is using a switch statement to 
simultaneously demonstrate switching on strings and to show the valid types for use in a 
switch expression: 
public class SwitchTypeChecker {
public static Class varTypeClass(Object o) { return o.getClass(); };
public static Class varTypeClass(Enum e) { return e.getClass() 
.getSuperclass(); };
public static Class varTypeClass(char c) { return char.class; };
public static Class varTypeClass(byte b) { return byte.class; };
public static Class varTypeClass(short s) { return short.class; };
public static Class varTypeClass(int i) { return int.class; };
public static Class varTypeClass(long l) { return long.class; };
public static Class varTypeClass(float f) { return float.class; };
public static Class varTypeClass(double d) { return double.class; };
public static Class varTypeClass(boolean d) { return boolean.class; };
public void isValidSwitchType(Class typeClass) {
String switchType = typeClass.getSimpleName();
boolean valid = true;
switch (switchType) {
case "char":
case "byte":
case "short":
case "int":
Chapter 7 Data SourCeS anD ColleCtionS


252
System.out.print("Primitive type " + switchType);
break;
case "Character":
case "Byte":
case "Short":
case "Integer":
System.out.print("Boxed primitive type " + switchType);
break;
case "String":
case "Enum":
System.out.print(switchType);
break;
default: // invalid switch type
System.out.print(switchType);
valid = false;
}
System.out.println(" is " + (valid ? "" : "not ") +
"a valid switch type.");
}
public static void main(String[] args) {
SwitchTypeChecker check = new SwitchTypeChecker();
check.isValidSwitchType(varTypeClass('7'));
check.isValidSwitchType(varTypeClass(7));
check.isValidSwitchType(varTypeClass(777.7d));
check.isValidSwitchType(varTypeClass((short)7));
check.isValidSwitchType(varTypeClass(new Integer(7)));
check.isValidSwitchType(varTypeClass("Java 8 Rocks!"));
check.isValidSwitchType(varTypeClass(new Long(7)));
check.isValidSwitchType(varTypeClass(true));
check.isValidSwitchType(varTypeClass(java.nio.file 
.AccessMode.READ));
}
}
Chapter 7 Data SourCeS anD ColleCtionS


253
Here is the result of executing SwitchTypeChecker.
Primitive type char is a valid switch type.
Primitive type int is a valid switch type.
double is not a valid switch type.
Primitive type short is a valid switch type.
Boxed primitive type Integer is a valid switch type.
String is a valid switch type.
Long is not a valid switch type.
boolean is not a valid switch type.
Enum is a valid switch type.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   129   130   131   132   133   134   135   136   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling