BlueJ 中的开关盒

Switch Case In BlueJ

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 语句的信息。