If I were to play a roshambo session against the computer, I would like to make my choice only by typing the first letter "Rock", "Paper" or "Scissors".
Using rich enum is a natural choice here:
private enum Choice { ROCK ("Rock"), PAPER ("Paper"), SCISSORS ("Scissors"); private String displayName; private static final List<Choice> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); private Choice(String dn) { displayName = dn; } public static Choice getRandomChoice() { return VALUES.get(RANDOM.nextInt(SIZE)); } public static Choice fromInput(String input) { if (input == null || input.length() == 0) { return null; } for (Choice c : VALUES) { if (Character.toLowerCase(c.displayName.charAt(0)) == Character.toLowerCase(input.charAt(0))) { return c; } } return null; } public static String promptText() { StringBuilder sb = new StringBuilder(); for (Choice c : VALUES) { if (sb.length() > 0) { sb.append(", "); } sb.append(c.displayName).append(" (") .append(c.displayName.charAt(0)).append(")"); } sb.append(". Pick one!"); return sb.toString(); } }
With most of the functionality declaratively encoded in enum , your client code will become much simpler. enum also handles random computer selection (idea from this answer).
while (true) { Choice choice = null; while (choice == null) { System.out.println(Choice.promptText()); choice = Choice.fromInput(scan.next()); } String computerChoice = Choice.getRandomChoice().displayName;
You can also encapsulate most (if not all) of the logic available in the getGameOutcome method in Choice .
source share