java在列表中搜索名称并显示所有匹配项
case 4: if(studentInfo.isEmpty())
{
System.out.println("No student record exists!");
}
else
{
System.out.println("Enter the name of the student you want to search for: ")
searchName = sc2.next();
for(Student stu : studentInfo)
{
if(stu.getName().equalsIgnoreCase(searchName))
{
System.out.println("Match found: "+stu);
}
else
{
System.out.println("No match found for the given name!");
}
break;
}
}
break;
这是我的案例块,其中我从用户处获取一个字符串,该字符串将是一个名称,并搜索列表是否包含该名称(最初的记录添加到以前的案例块中)。我想显示所有与用户给定名称匹配的名称。 例如:如果列表中有两条名为John的记录,我希望同时显示这两条记录。有人能指导我在上面的代码中修改什么吗?提前谢谢
# 1 楼答案
您应该从for-each循环中删除else语句,而不需要break语句
以下是代码:
# 2 楼答案
# 3 楼答案
为此,您需要遍历整个列表。您需要从
for
循环中删除break;
语句。有了这个break
语句,只要给定的student name
有匹配项,它就会跳出for循环。它没有搜索列表的其余部分