我希望有人帮助我重写此方法,使其能够在找不到匹配项时找到匹配项

public boolean equals(Object otherObject)    {
      if (otherObject ==null)
      {
         return false;
      }
      else if (getClass() != otherObject.getClass())
      {
         return false;
      }
      else
      {
         Contact otherContact = (Contact)otherObject;
         return (first.equals(otherContact.first) &&
               last.equals(otherContact.last)&&
               phone.equals(otherContact.phone)&&
               email.equals(otherContact.email));
      }    }


它显示我没有匹配项,而我的输入中有匹配项

public void displayMatch()
{

    System.out.println("Enter keyword: ");
    Scanner input = new Scanner(System.in);
    String in = input.next();

        for (Contact c : contacts)
        {
            if (in.equals(c)) {
                System.out.println(c);
            } else {
                System.out.println("No matches.");
            }
        }  
}

最佳答案

由于您将String与Object进行比较,因此无法正常工作。您需要比较两个对象。

因此,您要做的是询问用户的输入,创建Contact对象并调用equals。见下文

    public void displayMatch() {

        System.out.println("Enter keyword: ");
        Scanner input = new Scanner(System.in);
        String firstName = input.nextLine();
        String lastName = input.nextLine();
        String phone = input.nextLine();
        String email = input.nextLine();

        Contact inputContact = new Contact(firstName, lastName, phone, email);


        for (Contact c : contacts) {
            if (c.equals(inputContact)) {
                System.out.println(c);
            } else {
                System.out.println("No matches.");
            }
        }
    }

10-06 04:12