繁体   English   中英

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

[英]How can i fix this method

我希望有人帮我改写这种方法,以便能够找到匹配而不能

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

暂无
暂无

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

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