如何在数组列表中搜索新类中的字符串?

问题描述 投票:0回答:1

我正在为一个 Java 类编写一个程序,该程序创建一个新类人员的空数组,其中包含其姓名字符串,然后让您添加新人员并搜索他们。问题是我编写的搜索函数总是说搜索到的名称不在数组中,即使它们应该在数组中。

import java.util.*;
public class ArrayOfPeople {

public static void main(String[] args) {
    System.out.println("Hello");
    boolean running = true;
    while (true){
    ArrayList<person> people = new ArrayList<>();
    System.out.println("press 1 to add people");
    System.out.println("press 2 to search people");
    System.out.println("press 3 to exit program");
    Scanner scanner = new Scanner(System.in);
    int input = scanner.nextInt();
    
        
    switch (input) {
        
        //add people
        case 1:
            System.out.println(" how many people would you like to add?");
            int quantityOfNames = (scanner.nextInt());
            for(int i=0; i<quantityOfNames; i++){
                System.out.println(" what is the new person's first name?");
                person newPerson = new person();
                newPerson.fName = scanner.next();
                people.add(newPerson);
            }
            break;
            
        //search people
        case 2:
            System.out.println("what is the persons first name?");
            String searchedName = scanner.next();
            person searchedPerson = new person();
            searchedPerson.fName = searchedName;
            
            boolean found = people.contains(searchedPerson);
            if (found){
                System.out.println(searchedName + " IS in the system");
            }else{
                System.out.println(searchedName + " is NOT in the system");
            }       
            break;
        }
    }
}

我尝试将两个字符串与 for 循环内的 if 语句进行比较,但这只给了我成功的搜索消息,然后我尝试了 Arraylist 的 .contains 方法,这就是现在只给我不成功的消息。但我需要它告诉我该名称是否在数组中,如果不在数组中,则告诉我“是”。

任何帮助将不胜感激,谢谢。

这也是我在这里发表的第一篇文章,所以请让我知道是否有我遗漏的礼仪或其他什么。

java class search arraylist
1个回答
0
投票

正如评论中所述,覆盖等于。像这样的东西。

class Person {
   String name;
   public Person(String name) {
     this.name = name;
   }
   @Override
   public boolean equals(Object ob) {
       if (ob == null) {
           return false;
       if (ob == this) 
          return true;
       }
        
       if(ob instanceof Person p) {
            return p.name.equals(name));
       }
       return false;
   }
}

请注意,您可能有更多字段可以构成真正的比较,因此应修改 equals 方法以满足您的要求。

© www.soinside.com 2019 - 2024. All rights reserved.