For 循环在 Switch-Case 中 - Java

For loop inside the Switch-Case - Java

我想确定area1、area2等的一些端口写法

  void controlEvent(CallbackEvent event) {
  if (event.getAction() == ControlP5.ACTION_CLICK) {
    for (int i=1; i<13; i++){
      switch(event.getController().getName()) {  
        case "Area" + str(i):
          println("Button" + i + " Pressed");
          if (port != null) port.write(i + "\n");
          break;}
    }
  }
}

但是我得到了 “case 表达式必须是常量表达式” 错误。有没有办法在 switch-case 中使用 for 循环?如果不是,重写上述代码的最合乎逻辑的方法是什么?

问题列表在:

case "Area" + str(i):

正如提到的那样,switch 只需要常量,因此该值必须在编译时已知,而不是动态的。所以

case "Area1":
case "Area2":
... etc

如果您想要更动态,则使用 if 和 else-if 语句;

void controlEvent(CallbackEvent event) {
   if (event.getAction() == ControlP5.ACTION_CLICK) {
   for (int i=1; i<13; i++){ 
      final String controlName = event.getController().getName();
      if(controlName.equals("Area" + str(i))){
         println("Button" + i + " Pressed");
         if (port != null) {
           port.write(i + "\n");
         }
         break;
      } 
   ...
}}}

规范化操作名称并提取代码块是个好主意。有 13 个 if-else 语句的 switch case 很难阅读,所以最好提取方法来处理每个 ControlP5conrtolName

第二种方法(可能有点太复杂,但仍然如此): 创建动作图:

Map<String, Consumer<Integer>> actionMap = new HashMap<>();
actionMap.put("Area1", i ->{
    println("Button" + i + " Pressed");
    if (port != null) {
        port.write(i + "\n");
    }
});
actionMap.put("Area2", i ->{
    println("Button" + i + " Pressed");
    ...
});
.. etc

现在您可以检查您的操作地图是否包含所需的控件名称:

      void controlEvent(CallbackEvent event) {
         if (event.getAction() == ControlP5.ACTION_CLICK) {
            final String controlName = event.getController().getName();
            if(actionMap.hasKey(controlName)){
               actionMap.get(controlName).apply(...)
               break;
            }
          }
  }
}