java - for 循环内的 if else 语句与 Hashmap 相关

标签 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.

最佳答案

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

    }
}

关于java - for 循环内的 if else 语句与 Hashmap 相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062725/

相关文章:

java - 修改META-INF中的属性文件

C++ STL unordered_map问题与疑惑

java - 在 Java 中初始化 HashMap 的良好设计模式选择

java如何区分文件编码ISO-8859-1和UTF-8?

java - 使用 httpClient 和 cert.em 的 https post 请求

java - isDisplayed 对于特定元素始终返回 false

java - 哪个订单? ProGuard + JWrapper + Launch4J

angularjs - 在 spring mvc 中通过 angularjs $http.get 发送 HashMap

C 表示任意对象(类型 void *)作为整数(计算出的标识符)

android - JSON 数组到 GridView 中的 ImageView