Discuss / Java / 打卡

打卡

Topic source
package src;
/** @title Switchdemo.java* @description 练习使用switch实现一个简单的石头剪子布游戏* */public class SwitchDemo {
    public static void main(String[] args) {
        // 练习使用switch实现一个简单的石头剪子布游戏        // 1.提示用户输入要出的拳:石头(1)/剪刀(2)/布(3)        // 2.电脑随机出拳        // 3.比较胜负        // 4.显示本局结果        // 5.询问是否继续游戏        // 6.统计并显示用户的总成绩        // 7.结束游戏        int userScore = 0;
        int computerScore = 0;
        while (true) {
            System.out.println("请出拳:石头(1)/剪刀(2)/布(3)");
            int userFist = new java.util.Scanner(System.in).nextInt();
            int computerFist = (int) (Math.random() * 3 + 1);
            if (userFist < 1 || userFist > 3) {
                System.out.println("输入错误");
                break;
            }
            System.out.println("电脑出拳:" + computerFist);
//            if (userFist == computerFist) {//                System.out.println("平局");//            } else if ((userFist == 1 && computerFist == 2) || (userFist == 2 && computerFist == 3) || (userFist == 3 && computerFist == 1)) {//                System.out.println("用户胜利");//                userScore++;//            } else {//                System.out.println("电脑胜利");//                computerScore++;//            }            // if语句用switch代替            switch (userFist - computerFist) {
                case 0 -> System.out.println("平局");
                case -1, 2 -> {
                    System.out.println("用户胜利");
                    userScore++;
                }
                case -2, 1 -> {
                    System.out.println("电脑胜利");
                    computerScore++;
                }
                default -> System.out.println("输入错误");
            }
            System.out.println("用户得分:" + userScore);
            System.out.println("电脑得分:" + computerScore);
            System.out.println("是否继续?(y/n)");
            String answer = new java.util.Scanner(System.in).next();
            if (answer.equals("n")) {
                break;
            }
        }
    }
}

  • 1

Reply