【问题标题】:Iterating through an array and checking each item, printing error if no match遍历数组并检查每个项目,如果不匹配则打印错误
【发布时间】:2013-11-03 19:03:15
【问题描述】:

我设置了一个 for 循环,它遍历对象数组中的每个项目。我有一个 if 语句,用于检查某个项目中的值是否与特定的字符串值匹配。如果是这样,我想将其打印到屏幕上。我这样做没有问题。但是,如果循环一直执行而没有找到匹配项,我希望程序打印一条错误消息。我现在将它设置为 if else 语句的方式,如果每个项目不匹配,程序将打印一条错误消息。我想不出只有在循环完成后才能做到这一点的方法。任何指导将不胜感激。

【问题讨论】:

  • 在循环前将boolean matchFound设置为false,如果有发现则设置为true,如果在循环后为false则打印错误信息。
  • @Keppil 能否请您给出一个答案,以便对其进行投票和(可能)接受?

标签: java arrays object if-statement for-loop


【解决方案1】:

在您的代码中使用以下模式:

boolean matchFound = false;
for (item: objects) {
    if (item.equals(stringValue) {
        //print item the same way as you did
        matchFound = true;
    }
}
if (!matchFound) {
    System.out.println("No match found!");
}

【讨论】:

  • 具有讽刺意味的是,我们的答案如此相似以至于最终看起来像是我抄袭了你:D
【解决方案2】:

创建一个布尔变量来存储是否找到匹配项。在循环运行之前将其设置为 false,如果在循环中找到匹配项,则将其设置为 true。如果循环结束后仍然为假,则打印错误信息。

【讨论】:

    【解决方案3】:
    boolean matchFound = false; // dont be so eager that there is a match
    for(String each : lotOfStrings){
        if(each.equals(someOtherStrings)){
            matchFound = true;
            // break; // optionally, you may break out
        }
    }
    
    if(!matchFound){ // no match found?
        System.out.println("Error");
    }else{
        System.out.println("Found a match");    
    }  
    

    上面的代码 sn-p 显示了您如何实现您想要的。

    基于 Keppil 的评论

    【讨论】:

      【解决方案4】:

      按照 Keppil 的建议,进行了一些优化:

      boolean matchFound = false;
      for (int i = start; i < max && boolean == false; i++) {
          if (foundElement()) {
              matchFound = true;
          }
      }
      if (!matchFound) {  
          log.error = "";
      }
      

      或者你可以这样做

      int i = start;
      for (; i < max; i++) {
          if (foundElement()) {
              break;
          }
      }
      if (i == max) {
          log.error = "";
      }
      

      【讨论】:

        【解决方案5】:

        Keppil 和 Little Child 有很好的解决方案,但是让我建议进行重构,以便随着您的规范更改使这个问题更容易处理。也许矫枉过正。分解算法的步骤。 首先,获取一个匹配列表。 然后,决定如何处理它们。例如(你最终也想分解这段代码)

        ArrayList<T> matches = new ArrayList<T>;   // T is your object type, e.g. String
        for (T item : myObjects) {
           if (item.equals(thingToMatch))
              matches.add(item);
        }
        

        // 现在,决定如何处理列表...

        if (matches.size() > 0) {
           for (T t : matches)
              // print it here
              // but in the future could log them, store in a database, convert to XML, etc...
        }
        else
           System.out.println("no matches were found to " + thingToMatch);
        

        【讨论】:

          【解决方案6】:

          如果您不需要匹配的特定对象,那么解决您的问题的最简洁方法是编写一个辅助方法来进行查找。这样我们就可以避免局部变量的赋值和重新赋值,代码变得更加简洁:

          boolean find(List<?> list, Object toFind) {
             for (Object o : list) if (o.equals(toFind)) return true;
             return false;
          }
          

          这适用于字符串列表以及任何其他对象。在main方法中可以写

          System.out.println((find(list, toFind)? "A" : "No") + " match was found");
          

          如果您确实需要所有匹配的对象,那么我再次推荐一个帮助方法,它返回所有匹配项的列表,以便您打印或处理任何其他方式:

          <T> List<T> getMatches(List<T> list, Object toFind) {
             final List<T> ret = new ArrayList<>();
             for (T x : list) if (t.equals(toFind)) ret.add(x);
             return ret;
          }
          

          现在,在调用方法中,你可以有

          final List<MyType> matches = find(inputList, toFind);
          if (matches.isEmpty()) System.out.println("No match was found");
          else { ... process the list as needed ... }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-05-08
            • 1970-01-01
            • 1970-01-01
            • 2014-02-03
            • 1970-01-01
            相关资源
            最近更新 更多