简体   繁体   中英

How can i fix this method

I want someone help me to rewrite this method to make it able to find the matches while it can't

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));
      }    }

It shows me there is No matches while there are matches in my input

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.");
            }
        }   
}

Since you are comparing String with an Object, it wont work. you need to compare two objects.

so what you do is ask input from user, create Contact object and call equals. see below

    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.");
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM