以下是一个简单的Java石头剪刀布游戏的代码示例:

import java.util.Scanner;

public class RockPaperScissors {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] choices = {"石头", "剪刀", "布"};
        
        System.out.println("石头剪刀布游戏开始!");
        System.out.println("请输入你的选择(石头、剪刀、布):");
        String playerChoice = scanner.nextLine();
        
        int randomIndex = (int) (Math.random() * 3);
        String computerChoice = choices[randomIndex];
        
        System.out.println("你的选择:" + playerChoice);
        System.out.println("电脑的选择:" + computerChoice);
        
        if (playerChoice.equals(computerChoice)) {
            System.out.println("平局!");
        } else if ((playerChoice.equals("石头") && computerChoice.equals("剪刀"))
                || (playerChoice.equals("剪刀") && computerChoice.equals("布"))
                || (playerChoice.equals("布") && computerChoice.equals("石头"))) {
            System.out.println("你赢了!");
        } else {
            System.out.println("你输了!");
        }
    }
}

此代码使用了一个字符串数组来存储游戏的选项(石头、剪刀、布)。然后,它通过随机生成一个索引来模拟电脑的选择。接下来,它与玩家的选择进行比较,并根据规则判断胜负关系。最后,它打印出结果(平局、你赢了、你输了)。

注意:此代码仅为示例,没有包含输入验证等错误处理。在实际开发中,应该进行更多的错误处理和边界情况的考虑。


原文地址: https://www.cveoy.top/t/topic/px9R 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录