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/