如何精简Java石头剪刀布游戏中多结果对比的代码实现?
Hey there! Great job getting hands-on with classes, objects, and methods by building this Rock Paper Scissors game—practice like this is exactly how you solidify these concepts. I totally get where you're coming from with the redundant compareChoices method; all those repeated if/switch blocks can feel clunky. Let's break down how to streamline this into cleaner, more maintainable code.
Key Optimizations to Cut Redundancy
- Use an array for choice labels: Instead of hardcoding "Rock", "Paper", "Scissors" every time in print statements, store them in a string array. This lets you reference the choice name by its index, eliminating duplicate text.
- Leverage math for win/loss logic: Rock Paper Scissors follows a consistent mathematical pattern for outcomes. For choices mapped to 0 (Rock), 1 (Paper), 2 (Scissors):
- If
userChoice == computerChoice: It's a draw - If
(userChoice - computerChoice + 3) % 3 == 1: User wins - Otherwise: User loses
This single formula replaces all nested conditional checks.
- If
Refactored Code
import java.util.Scanner; import java.util.Random; class Main { public static void main(String[] args) { GameAction game = new GameAction(); System.out.println("\nYou will now play Rock Paper Scissors with a Computer."); game.getUserChoice(); game.getComputerChoice(); game.determineResult(); } } class GameAction { private static final String[] CHOICES = {"Rock", "Paper", "Scissors"}; private Scanner sc = new Scanner(System.in); private Random rand = new Random(); private int computerChoice; private int userChoice; int getUserChoice() { System.out.println("\nDo you choose (0)Rock, (1)Paper, (2)Scissors?"); userChoice = sc.nextInt(); // Optional: Add input validation here to ensure user picks 0,1,2 return userChoice; } int getComputerChoice() { // Fixed bug: Original nextInt(2) only generated 0/1—computer could never pick scissors! computerChoice = rand.nextInt(3); return computerChoice; } void determineResult() { String userChoiceName = CHOICES[userChoice]; String computerChoiceName = CHOICES[computerChoice]; if (userChoice == computerChoice) { System.out.printf("It's a draw! You both picked %s!\n", userChoiceName); } else if ((userChoice - computerChoice + 3) % 3 == 1) { System.out.printf("You win!\nYou picked %s and the computer picked %s.\n", userChoiceName, computerChoiceName); } else { System.out.printf("You lose!\nYou picked %s and the computer picked %s.\n", userChoiceName, computerChoiceName); } } }
What Changed & Why
- Renamed
actiontoGameAction: Meaningful class names make code far more readable for anyone (including future you). - Added
CHOICESconstant array: Centralizes the choice labels so we don't repeat the same string text across multiple print statements. - Fixed a critical bug: Your original
getComputerChoice()usedrand.nextInt(2), which only generates 0 and 1—this meant the computer could never pick scissors! Switching torand.nextInt(3)fixes this. - Simplified result logic: The
determineResult()method replaces dozens of conditional lines with a single mathematical check, making the code shorter and easier to update (if you ever wanted to add more choices like Lizard/Spock, for example). - Encapsulated fields: Marking class fields
privateis good practice—this prevents accidental modification from outside the class and keeps your code robust.
内容的提问来源于stack exchange,提问作者ThatOneSpartan
相关产品推荐
相关产品推荐

