有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java嵌套for循环只读取第一个“if”语句

我有一个嵌套的for循环。它起作用了,有点。它只将第一个if语句读取为true。在那之后,它忽略了所有可能的真实陈述

for(int i = 0; i < inGroups.length; i++)
{
    for(int g = 0; g < theGroups.length; g++)
    {
        if( inGroups[i].equals(theGroups[g]) )
        {
            gLV.setItemChecked(g, true);
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    你的代码看起来不错。正如@Hot-Licks提到的,您应该使用调试器和/或添加print语句来查看发生了什么

    关于代码的几点一般性评论:

    • 您应该确保Group对象或数组中的任何对象具有implemented an ^{} method,否则它将始终为false
    • 你确定setItemChecked可以处理多个值吗?如果set被调用两次,它是否会覆盖上一个值
    • 你的代码效率很低(O(N^2))。你可以考虑做如下的事情,那就是O(n)。当然,阵列是否小并不重要。如果使用此方法,则需要implement ^{} and ^{} methods

      Set<Group> inGroupsSet = new HashSet<Group>();
      // load inGroups into a set
      for (Group group : inGroups)
          inGroupsSet.add(group);
      // look up each Group in theGroups in the set
      for (int g = 0; g < theGroups.length; g++)
          if (inGroupsSet.contains(theGroups[g]))
              gLV.setItemChecked(g, true);
      

    希望这里能有所帮助