请用java编写一个石头剪刀布的程序

2024-11-20 08:39:32
推荐回答(1个)
回答(1):

import java.util.Random;
import java.util.Scanner;
 
public class FingerGuessingGame {
    private static Scanner sc;
    private static Random rad;
    private static final String[] FINGERS = {"剪刀", "石头", "布"};
    private static int win = 0, loose = 0, draw = 0;
 
    public static void main(String[] args) {
        sc = new Scanner(System.in);
        rad = new Random();
        while(true) {
            System.out.println("~~~~~~~~~~~~剪刀石头布游戏,输入E可以退出~~~~~~~~~~~");
            System.out.println("请选择你要出什么?Z——剪刀,X——石头,C——布");
            String command = sc.nextLine();
            int playerFinger = getValue(command);
            if(playerFinger == -1) {
                break;
            } else if(playerFinger == 3) {
                System.out.println("输入错误,请参考说明!");
                continue;
            }
            System.out.println("你出的是" + FINGERS[playerFinger]);
            int cpuFinger = rad.nextInt(3);
            System.out.println("计算机出的是" + FINGERS[cpuFinger]);
            int result = playerFinger - cpuFinger;
            if(0 == result) {
                System.out.println("平局!");
                draw ++;
            } else if(-1 == result) {
                System.out.println("你输了!");
                loose ++;
            } else {
                System.out.println("你赢了!");
                win ++;
            }
        }
         
        System.out.println("游戏结束!\r\n游戏统计次数");
        System.out.println(String.format("赢:%d\r\n输:%d\r\n平局:%d", win, loose, draw));
    }
 
    private static int getValue(String command) {
        if(command.equalsIgnoreCase("E")) {
            return -1;
        }
        if(command.equalsIgnoreCase("Z")) {
            return 0;
        }
        if(command.equalsIgnoreCase("X")) {
            return 1;
        }
        if(command.equalsIgnoreCase("C")) {
            return 2;
        }
        return 3;
    }
}