Discuss / Java / switch练习

switch练习

Topic source

*花前

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

import java.util.Scanner;

/**

 * switch实现石头/剪子/布并判断胜负

 */

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("please choice:");

        System.out.println(" 1: Rock");

        System.out.println(" 2: Scissors");

        System.out.println(" 3: Paper");

        // 用户输入:

        int choice = sc.nextInt();

        String result = switch (choice) {

            case 1, 2, 3 -> {

                // 计算机随机数 1, 2, 3:

                int random = 1 + (int) (Math.random() * 3);

                System.out.printf("系统:%s,玩家:%s,结果:",random,choice);

                yield switch (choice - random) {

                    case 0 -> "平局";

                    case -2, 1 -> "玩家失败";

                    case -1, 2 -> "玩家胜利";

                    default -> "";

                };

            }

            default -> "无效输入";

        };

        System.out.println(result);

    }

}


  • 1

Reply