基本上,我的 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/