You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何精简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.

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

  1. Renamed action to GameAction: Meaningful class names make code far more readable for anyone (including future you).
  2. Added CHOICES constant array: Centralizes the choice labels so we don't repeat the same string text across multiple print statements.
  3. Fixed a critical bug: Your original getComputerChoice() used rand.nextInt(2), which only generates 0 and 1—this meant the computer could never pick scissors! Switching to rand.nextInt(3) fixes this.
  4. 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).
  5. Encapsulated fields: Marking class fields private is good practice—this prevents accidental modification from outside the class and keeps your code robust.

内容的提问来源于stack exchange,提问作者ThatOneSpartan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:23:27