有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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的记录,我希望同时显示这两条记录。有人能指导我在上面的代码中修改什么吗?提前谢谢


共 (3) 个答案

  1. # 1 楼答案

    您应该从for-each循环中删除else语句,而不需要break语句

    以下是代码:

    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();
                        int i = 0;
    
                        for(Student stu : studentInfo)
                        {
                           if(stu.getName().equalsIgnoreCase(searchName))
                            {
                               System.out.println("Match found: "+stu);
                               i++;
    
                            }
                         }
                         if(i == 0)
                             System.out.println("No Match found");
            }
            break;
    
  2. # 2 楼答案

          StringBuilder result = new StringBuilder();
           for(Student stu : studentInfo)
           {        
             if(stu.getName().equalsIgnoreCase(searchName))
                 result = result.append(stu.getName()+ " ");  
            }
           System.out.println(result.toString());
    
  3. # 3 楼答案

    为此,您需要遍历整个列表。您需要从for循环中删除break;语句。有了这个break语句,只要给定的student name有匹配项,它就会跳出for循环。它没有搜索列表的其余部分