gpt4 book ai didi

java - BlueJ 开关盒

转载 作者:行者123 更新时间:2023-12-01 21:25:49 25 4
gpt4 key购买 nike

public class Hello {
public static void main(int a) {
switch (a) {
case 1:
System.out.println("Hi");
}

switch (a) {
case 2:
System.out.println("Hello");
}
}
}

嗨,我想知道我是否可以对同一个变量使用 Switch Case 两次,就像我在附加的代码片段中所做的那样。谢谢。

最佳答案

您提供的代码有效。只要变量 a 在作用域内,您就可以将它用于任意数量的 switch 语句。

如果您想在同一个 switch 中检查 a 的多个值,那么您应该使用不同的情况。例如:

switch (a) {
case 1:
System.out.println("a was 1");
break; // if we did not break, then execution would "fall-through" to the next case
case 2:
System.out.println("a was 2");
break;
default:
System.out.println("a was not 1 or 2");
}

Java Documentation 中了解有关 switch 语句的更多信息.

关于java - BlueJ 开关盒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38162610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com