gpt4 book ai didi

java - 搜索ArrayList对象: object's

转载 作者:行者123 更新时间:2023-12-02 02:45:17 25 4
gpt4 key购买 nike

我努力寻找解决方案,或者至少为我指明正确的方向......

这是我的 ArrayList: books = new ArrayList();

我必须搜索包含标题(字符串)的 Book 对象。这是我所拥有的..

问题是我只想在找不到第二条语句时打印它。但它似乎在搜索列表中的每个对象时打印它?

public void searchBookInCollection(String title) 
{
for (Book book : books)
{
if(book.getTitle().equalsIgnoreCase(title))
{
book.displayBookInformation();
}
else
{
System.out.println("Nope we don't have it");
}
}
}

最佳答案

将其更改为 boolean 值已找到标志

public void searchBookInCollection(String title) 
{
boolean found = false;
for (Book book : books)
{
if(book.getTitle().equalsIgnoreCase(title))
{
book.displayBookInformation();
found = true;
break; // no point to keep going?
}
}
if (!found)
{
System.out.println("Nope we don't have it");
}
}

关于java - 搜索ArrayList对象: object's,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44666806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com