【问题标题】:For loop inside the Switch-Case - JavaSwitch-Case 内的 For 循环 - Java
【发布时间】:2021-09-15 05:46:55
【问题描述】:

我想为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 循环?如果不是,那么重写上面的代码最合乎逻辑的方法是什么?

【问题讨论】:

  • 你可以试试if(){...}else if(){...}
  • 您不能使用动态资源来索引切换案例。如果您的代码 sn-p 就是全部,则根本不需要 switch 语句。只需将参数传递给您想要执行的任何操作,或使用它来调用可以处理数据的单独函数。
  • if(event.getController().getName().equals("Area" + str(i))) {println("Button" + i + " Pressed"); if (port != null) port.write(i + "\n");} 怎么样?
  • 使用一些正则表达式,这样你甚至不需要使用循环。

标签: java processing


【解决方案1】:

问题列表在:

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

现在您可以检查您的操作图是否包含所需的 controlName:

      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;
            }
          }
  }
}

【讨论】:

  • 非常感谢您的详细解释。我想再问一些:''final'' 在定义字符串之前代表什么,我们为什么需要它?而且我只是在 switch 案例中使用 ''break'',我是否应该在 for 循环中的 if 语句中也使用它?
  • 该值必须大于final。它必须是常量,可在编译时计算。
  • 感谢您的指出,我已经更新了我的答案。谢谢你。 final 意味着变量值不能改变。如果您要多次比较单个值,建议将其设为最终值,这样就不会改变它。
猜你喜欢
  • 1970-01-01
  • 2014-06-13
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
相关资源
最近更新 更多