【问题标题】:How to control the for loop with a if condition in it not to give output till the loop completes如何控制带有if条件的for循环在循环完成之前不给出输出
【发布时间】:2020-06-02 13:22:28
【问题描述】:

我有一个方法,它有一个带有一组规则的 Map,我试图将这些规则应用于带有 if 条件的输入。

当条件匹配时,if 将中断循环并返回匹配的值。如果没有任何条件匹配,我需要返回输入不满足任何给定条件的null 输出。

我当前的代码如下

public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)    
    for (Map.Entry mapElement : hm.entrySet()) { 
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}

假设地图有 5 个条目,满足当前输入的条件出现在第 5 个位置。前四个测试返回null,当第 5 个位置的条件匹配时,它将返回匹配的条件。但我只想在评估地图中的所有条件后返回输出。 我尝试使用continue;else if 放在if 之后的循环中,但结果相同。

请问,我该如何解决这个问题?

【问题讨论】:

  • 请正确格式化您的代码。
  • 你不能从你的函数返回然后再返回执行它。
  • 只是一个评论:它不会解决你的问题,但是breakreturn 语句之后是完全没有必要的。
  • 只需在 for 循环中放置一个临时变量,将其赋值为 null。如果您的 if 语句满意,请将满意的值分配给您的临时变量。在所有迭代完成后,它将返回最后一个满意的值,否则将返回 null。然后你可以说所有条目都迭代了。

标签: java loops for-loop


【解决方案1】:

当您使用return 时,循环将中断并退出函数。 如果您想要评估整个地图,您可以重新调整结果数组;

public static String matching(String input){

    ArrayList<Object> results = new ArrayList<>();
    HashMap<String, String> hm =  new HashMap<String, String>();

    for (Map.Entry mapElement : hm.entrySet()) { 
        String value = mapElement.getValue();
        if(input.equals(condition)){
            results.add(input);
        }
        else {
          results.add(null);
        }
    }

    // return all the result in 1 ArrayList. If your element in position 4 is your match the output will be:
    // [null, null, null, null, <input>]
    return results;
}

【讨论】:

    【解决方案2】:

    如果你在 if 中有返回值,那么 for 循环将中断并返回值。 相反,如果不满足,for 循环将终止并在循环外返回 null 值。

    在一个方法中,return 打破了函数

    【讨论】:

    • 对不起@Francesco Attorre 我没听懂你的意思
    • 当您有返回时,该方法在任何情况下都不会继续,因此您必须仅在完成每项检查后才调用返回,例如@GameDroids answer
    【解决方案3】:

    您的方法只能返回一次,如果您需要存储不成功匹配的值,那么您最好使用 List 或 Array 之类的数据存储。 试试这样的。

    public static String matching(String input){
    
        HashMap<String, String> hm =  new HashMap<String, String>();
        List<String> strList = new ArrayList<>(hm.size()); //same size as the map.
    
        //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)    
        for (Map.Entry mapElement : hm.entrySet()) { 
            String value = mapElement.getValue();
            if(input.equals(condition)){
                strList.add(input);
                break;
            }else{
                strList.add(null);
            }
        }
        return strList;
    }
    

    【讨论】:

    • 我认为 OP 想要返回条件(以防它不是简单的String.equals)。 @YRK,有了这个,你可以确保看到肉的所有条件(以及条件的数量)。但是如果你的值都是字符串并且你的输入也是一个字符串 - 如果你真的只测试 input.equals(condition) 那么你只需要返回 truefalse... 因为你已经知道你的输入(之前调用该方法),当您返回 true 时,您知道输入满足条件(具有完全相同的值 - 两个字符串相等)
    【解决方案4】:

    首先,由于您使用的是 HashMap - 您无法确定顺序。

    其次 - 这取决于,如果您想记录适合输入的所有条件,那么只需制作单独的集合并将它们添加到您的循环中。如果集合为空 - 您只需返回 null。

    看看这个示例代码:

       final String input = "testValue2";
       Map<String, String> conditions = new HashMap<>();
       conditions.put("testKey1", "testValue1");
       conditions.put("testKey2", "testValue2");
    
       Set<Map.Entry> entrySetThatMatches = conditions.entrySet().stream().filter(m -> input.equals(m.getValue())).collect(Collectors.toSet());
       System.out.println(entrySetThatMatches.iterator().next().getValue()); //prints testValue2
    

    【讨论】:

      【解决方案5】:

      对于这些情况,您可以使用“运行”变量。在进入for循环之前声明输出变量(设置为null),然后根据你的条件设置结果。这样,您可以确保遍历每个输入,如果不满足任何条件,您的变量仍然是 null

      public static String matching(String input){
      
        String result = null;  // we declare the result here and return it in the end
      
          HashMap<String, String> hm =  new HashMap<String, String>();
      
          for (Map.Entry mapElement : hm.entrySet()) { 
              String value = mapElement.getValue();
              if(input.equals(condition)){
                  result = input;           // the input is the result if it meats the condition
                  break;                    // the return at this point would make the break obsolete
              }
          }
          return result;                    // if (and only if) the condition is met your result variable has a value - otherwise it will be null
      }
      

      编辑这里是一个更安全的解决方案:

      public static String matching(String input){
      
          String result = null;  // we declare the result here and return it in the end
      
          HashMap<String, String> hm =  new HashMap<String, String>();
      
          for (String key : hm.keySet()) {  // personally I find it easier to read and to follow 
              String value = hm.get(key);   // here the value will still be a String
              if(input.equals(condition)){  // FYI for more precise conditions you can also use input.equalsIgnoreCase(condition)
                  result = input;           // the input is the result if it meets the condition
                  break;                    // the return at this point would make the break obsolete
              }
          }
          return result;                    // if (and only if) the condition is met your result variable has a value - otherwise it will be null
      }
      

      【讨论】:

      • 备注:与@John Doe 的回答不同,这里它只会返回一个结果(最后一个条件肉)
      【解决方案6】:

      您可以用以下代码替换正文:

          for (String value : hm.values()) {
              if (input.equals(value)) {
                  return input;
              }
          }
          return null;
      
      • return 语句后不能有代码
      • .entrySet() 返回 Map.Entry,如果您不使用 运算符 getValue() 返回 Object 而不是 String

      【讨论】:

        猜你喜欢
        • 2018-05-17
        • 1970-01-01
        • 2015-08-24
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多