if else语句里面的循环问题与Hashmaps

时间:2016-05-06 01:15:51

标签: java hashmap

基本上我的if语句有问题。我想说“没有为”+ val找到CD,但这是我得到的输出:

    Welcome to the CD Database
    Enter search, add, name, list, or quit:
    name
    Enter the full or partial name:
    asdfa
    Enter search, add, name, list, or quit:

你可以看到它没有返回任何东西。

我的代码:

public void printByName(String val) {

    int i = 0;
    for (CompactDisc values : database.values()) {

        if (values.getArtist().contains(val)) {

            System.out.println(values);

        } else if (i > database.size() && !values.getArtist().contains(val)) {

            System.out.println("No CDs found for " + val);

        }

       i++; 
}
}

由于某种原因,我的计数器没有迭代,这让我疯狂了好几个小时。我希望它在循环遍历hashmap后找不到CD,并且找不到用户输入的字符串的部分匹配

额外输出:

Welcome to the CD Database
Enter search, add, name, list, or quit:
name
Enter the full or partial name:
Mo
Artist:Modest Mouse Title:We Were Dead Before the Ship Even Sank price:5.99
Artist:Thelonious Monk Title:Monk's Dream price:5.99
Enter search, add, name, list, or quit:
list
Artist:Isley Brothers Title:Funky Family price:5.99
Artist:Muddy Waters Title:At Newport price:6.99
Artist:Sly & The Family Stone Title:Greatest Hits price:6.99
Artist:Modest Mouse Title:We Were Dead Before the Ship Even Sank price:5.99
Artist:St. Germain Title:Tourist price:5.99
Artist:Bob Dylan Title:Desire price:6.99
Artist:The Beatles Title:Abbey Road price:6.99
Artist:Los Straitjackets Title:The Velvet Touch of... price:5.99
Artist:The Velvet Underground Title:Peel Slowly and See price:6.99
Artist:Thelonious Monk Title:Monk's Dream price:5.99
Enter search, add, name, list, or quit:
quit
Program ending.

3 个答案:

答案 0 :(得分:1)

条件i > database.size()永远不会成立,因为循环将在i达到数据库大小之前退出。尝试将代码更改为:

public void printByName(String val) {
    for (CompactDisc values : database.values()) {
        if (values.getArtist().contains(val)) {
            System.out.println(values);
        } else {
            System.out.println("No CDs found for " + val);
        }

    }
}

答案 1 :(得分:0)

您的逻辑结构存在问题。 你的“if”在你的“循环”块中。它必须在外面。看看:

public void printByName(String val) {
    int i = 0;
    for (CompactDisc values : database.values()) {
        if (values.getArtist().contains(val)) {
            System.out.println(values);
            i++;
        }  
    }
    if (i==0) {
        System.out.println("No CDs found for " + val);
    }
}

答案 2 :(得分:0)

由于上述原因,它应该是else if (i >= database.size() && !values.getArtist().contains(val))