验证用于搜索arrayLists

时间:2014-12-14 15:13:13

标签: java validation search arraylist

您好我创建了搜索数组列表的代码,如果没有找到任何内容,我需要能够打印一行。

            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行,它只是留空。

2 个答案:

答案 0 :(得分:1)

你应该只打印&#34;未找到&#34;迭代整个列表后的消息:

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

答案 1 :(得分:1)

最好使用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);
    }