我希望有人帮我改写这种方法,以便能够找到匹配,但不能
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.");
}
}
}
答案 0 :(得分:3)
由于您正在将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.");
}
}
}