Discuss / Java / 新语法且较为合理

新语法且较为合理

Topic source

import java.util.Scanner;

public class Shitoujiandaobu {

    //使用switch实现一个简单的石头、剪子、布游戏。

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("输入石头剪刀布:");  //1石头2剪刀3布

        String opt = scanner.nextLine();

        int random = 1+(int)(Math.random()*3);   //math.random生成(0,1)随机数

        System.out.printf("PC的选择是:%s\n",random == 1?"石头":random == 2? "剪刀":"布");

        switch (opt){

            case "石头" -> System.out.print(random == 1?"平局":random == 2? "胜利":"失败");

            case "剪刀" -> System.out.print(random == 1?"失败":random == 2? "平局":"胜利");

            case "布" -> System.out.print(random == 1?"胜利":random == 2? "失败":"平局");

            default -> System.out.print("请正确输入选项");

        }

    }

}

我感觉这个是最好的方案

烈火庄主

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

看了一圈这个方案最好

虚心学习。

 int random = 1+(int)(Math.random()*3); //math.random生成(0,1)随机数

有点搞不懂这个语句 函数随机生成0-1之间的数 那么后面乘以三 它的范围就是0到3加一 random的值范围不就是1到4嘛 是这样理解嘛?

大佬,我用你的代码,没有运行,在写好之后,就在switch(opt)的opt上提示:

Cannot switch on a value of type String. Only convertible int values, strings or enum variables are permitted

这是怎么回事呢?


  • 1

Reply