Reputation: 61
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.");
}
}
}
Upvotes: 1
Views: 43
Reputation: 5148
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.");
}
}
}
Upvotes: 3