【问题标题】:Validation for seaching arrayLists验证搜索数组列表
【发布时间】:2014-12-14 15:13:12
【问题描述】:

您好,我创建了搜索数组列表的代码,如果没有找到,我需要能够打印一行,这就是我所拥有的。

            for (int i = 0; i < trackNum.size(); i++) { //looping arrayList trackNum
            if(trackNum.get(i).equals(trackNumber)){ //searching for matches to trackNumber
                System.out.println(trackNum.get(i) + ": " + name.get(i) + " " + duration.get(i)); //printing out the matches            
            } else{
                System.out.println("Not Tracks Found for " + trackNumber);
            }
        }

目前它没有打印出 else 行,它只是保持空白。

【问题讨论】:

  • 您确定这是符合您问题的代码吗?因为在我看来,它应该为列表中的每个项目显示else 部分,而不是只显示一次,这与您所说的问题不同。如果它保持空白,我相信该列表只是空的。
  • 例如,您可以编写一个函数来迭代轨道并在找到某些内容时返回。只有在函数没有返回时才会执行循环之后的代码,因此您可以在该点输出未找到的消息。但是,如果您使用哈希映射,则不需要循环。

标签: java validation search arraylist


【解决方案1】:

您应该只在遍历整个列表后打印“未找到”消息:

        boolean found = false;
        for (int i = 0; i < trackNum.size(); i++) { //looping arrayList trackNum
            if(trackNum.get(i).equals(trackNumber)){ //searching for matches to trackNumber
                System.out.println(trackNum.get(i) + ": " + name.get(i) + " " + duration.get(i)); //printing out the matches            
                found = true;
                break;
            }
        }   
        if (!found) {
            System.out.println("Not Tracks Found for " + trackNumber);
        } 

【讨论】:

    【解决方案2】:

    最好使用containsindexOf 进行此类搜索:

        if (trackNum.contains(trackNumber)) {
            int i = trackNum.indexOf(trackNumber);
            System.out.println(trackNum.get(i) + ": " + name.get(i) + " " + duration.get(i)); //printing out the matches            
        } else {
            System.out.println("Not Tracks Found for " + trackNumber);
        }
    

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      相关资源
      最近更新 更多