Discuss / Java / 猜拳

猜拳

Topic source

Junes_99994

#1 Created at ... [Delete] [Delete and Lock User]

import java.util.Scanner;

import java.util.Random;

public class CaiQuan {

    public static void main(String[] args) {

        char go = 'Y';

        Scanner scanner = null;

        while (go == 'Y' || go == 'y') {

            scanner = new Scanner(System.in);

            System.out.print("剪刀为1,石头为2,布为3:");

            var choice = scanner.nextInt();

            Random rd = new Random();

            var rand_num = rd.nextInt(1, 4);

            String opt = switch (choice) {

                case 1 -> rand_num == 1 ? "平局" : (rand_num == 2 ? "输" : "胜");

                case 2 -> rand_num == 2 ? "平局" : (rand_num == 3 ? "输" : "胜");

                case 3 -> rand_num == 3 ? "平局" : (rand_num == 1 ? "输" : "胜");

                default -> "输入异常";

            };

            System.out.println("结果:" + map(choice) + " vs " + map(rand_num) + " " + opt);

            scanner = new Scanner(System.in);

            System.out.print("继续?:");

            try{

                go = (char) System.in.read();

            }

            catch(Exception e)

            {}

            // go = scanner.next().toUpperCase().charAt(0);

        }

        scanner.close();

    }

    public static String map(int choice){

        return

            switch(choice){

                case 1 -> "剪刀";

                case 2 -> "石头";

                case 3 -> "布";

                default -> "输入异常";

            };

    }

}


  • 1

Reply