简体   繁体   English

我该如何解决这个问题呢?

[英]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. 由于您要将String与Object进行比较,因此无法正常工作。 you need to compare two objects. 你需要比较两个对象。

so what you do is ask input from user, create Contact object and call equals. 所以你要做的是询问用户的输入,创建Contact对象并调用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.");
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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