For part 1, it returns 3 instead of 2. For part 2, it doesnt return true when th
ID: 3707287 • Letter: F
Question
For part 1, it returns 3 instead of 2. For part 2, it doesnt return true when the name being tested is "Red", "Hat",. How do i fix this
-----------------Test method 1_-------------------------------
public void testRemoveContacts() {
Contact[] cs = new Contact[3];
cs[0] = new Contact(new Name("White", "Snow", ""));
cs[0].addPhoneNumber("300-000-9999");
cs[1] = new Contact(new Name("White", "Hat", ""));
cs[1].addPhoneNumber("300-000-9999");
cs[2] = new Contact(new Name("Red", "Hat", ""));
cs[2].addPhoneNumber("000-000-0000");
ContactManager cMgr = new ContactManager(cs);
cMgr.removeContact(new Name("Red", "Hat", ""));
assertEquals(2, cMgr.countContacts());
}
/********************************my code part 1
* Remove the Contact with Name n from your List. Make no changes if it doesn't
* exist.
*
* @param n
*/
@SuppressWarnings("unlikely-arg-type")
public void removeContact(Name n) {
for(int i = 0; i < contacts.size(); ++i) {
if(contacts.get(i).equals(n)) {
contacts.remove(i);
}
}
}
---------------**********part 2******------------------------test method
public void testContainContacts() {
Contact[] cs = new Contact[3];
cs[0] = new Contact(new Name("White", "Snow", ""));
cs[0].addPhoneNumber("300-000-9999");
cs[1] = new Contact(new Name("White", "Hat", ""));
cs[1].addPhoneNumber("300-000-9999");
cs[2] = new Contact(new Name("Red", "Hat", ""));
cs[2].addPhoneNumber("000-000-0000");
ContactManager cMgr = new ContactManager(cs);
assertTrue(cMgr.contains(new Name("Red", "Hat", "")));
}
----------------------------------------my code------------------------------
public boolean contains(Name n) {
for(int i = 0; i < contacts.size(); ++i) {
if(!contacts.get(i).equals(new Contact(n))) {
return false;
}
}
return true;
}
---------------------------------------------------------
Explanation / Answer
The last stub of your mentioned code goes like this
public boolean contains(Name n) {
for(int i = 0; i < contacts.size(); ++i) {
if(!contacts.get(i).equals(new Contact(n))) {
return false;
}
}
return true;
}
Here in contains function, you are taking in a Name object as argument and you are searching for it in your ArrayList named contacts. The problem is in the line if(!contacts.get(i).equals(new Contact(n))) .
Here you have created an entirely new object of Contact class and initialized it with the Name argument you recieved. The equals method needs to be overridden properly to compare the Name n with The Name stored inside your Contacts ArraList.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.