Skip to content
On this page

其他知识

随机字符

java
UUID.randomUUID().toString() // 3db9d630-aff6-4d57-bd70-5a36e919154d

随机数字

java
Random random = new Random();
int x1 = random.nextInt(10);

switch

不需要 break 语法

java
String s = "hello";
 switch (s){
    case "hello" -> System.out.println("aa");
    case "world" -> System.out.println("cc");
    default -> System.out.println("defautl");
}

如果只有一行,可以赋值

java
String fruit = "apple";

int opt = switch (fruit) {
    case "apple" -> 1;
    case "pear", "mango" -> 2;
    default -> 0;
}; // 注意赋值语句要以;结束

System.out.println(opt);

如果有多行,使用 yield

java
String fruit = "apple";
int opt = switch (fruit) {
    case "apple" -> {
        System.out.println("aaaaa");
        yield 10;
    } // 这里没有符号 [!code hl]
    case "pear", "mango" -> 2;
    default -> 0;
};
System.out.println(opt);