This is related to a question I asked earlier: Iterating through hashmap and creating unique objects - trying to prevent duplicates
And while I assumed I could apply a similar logic for my remove method that I had for my add method, the exception I have to check for a non existent record is getting thrown even though I know very well the record exists and should be removed. My delete method is as follows:
public boolean removePatron(int libraryCardNumber) throws PatronException {
boolean patronRemoved = false;
int keyToRemove = 0;
for (Map.Entry<Integer, Patron> entry : patrons.entrySet()) {
if (entry.getValue().getCardNumber() != libraryCardNumber) {
throw new PatronException("This record does not exist");
}
keyToRemove = entry.getKey();
}
patrons.remove(keyToRemove);
patronRemoved = true;
return patronRemoved;
}
For reference, the Patron objects look like this:
public class Patron {
//attributes
private String name = null;
private int cardNumber = 0;
//operations
public Patron (String name, int cardNumber){
this.name = name;
this.cardNumber = cardNumber;
}
public String getName(){
return name;
}
public int getCardNumber(){
return cardNumber;
}
}
My test simply adds three patrons first, and then tries to remove it by a card number that I know would exist. I added a println of the Patron's number in my add method so I could see them easily while messing with this in eclipse as they get added.
@Test
public void testRemovePatron() {
boolean exceptionThrown = false;
try {
testLibrary.addPatron("TestName");
testLibrary.addPatron("TestName2");
testLibrary.addPatron("TestName3");
testLibrary.removePatron(1);
} catch (PatronException e) {
System.out.println(e.getMessage());
exceptionThrown = true;
fail("what the hell is going on");
}
assertFalse(exceptionThrown);
}
I get the exception from the remove method thrown every time.
Edit: I made a small change to the provided answer, to account for needing to throw an exception if there was no match found:
public boolean removePatron(int libraryCardNumber) throws PatronException {
boolean patronRemoved = false;
int keyToRemove = 0;
for (Map.Entry<Integer, Patron> entry : patrons.entrySet())
{
if (entry.getValue().getCardNumber() == libraryCardNumber)
{
keyToRemove = entry.getKey();
patronRemoved = true;
}
}
if (patronRemoved)
{
patrons.remove(keyToRemove);
} else {
throw new PatronException("This record did not exist");
}
return patronRemoved;
}