Daily Practice

5 Mins of Code - Loops and ArrayLists!

The code below defines the PartyPlanner class that simulates a planning service for a party.  How would you implement the invitePerson method? 

You are not allowed to use the contains method of ArrayLists. No person may be invited twice. 

Hints: 

class PartyPlanner {

ArrayList<String> invitees;

public PartyPlanner() {

invitees = new ArrayList<String>();

}

public void invitePerson(String invitee) {

//invites the person by adding the person to invitees if the person is not already invited.

//if the person is already invited, output a sentence saying so. 

//after inviting the person, output a sentence stating the invitee (name) was successfully invited.

}

}

Solution & Explanation

The implementation is as follows:

public void invitePerson(String invitee) {

for (int i = 0; i < invitees.size(); i++) {

if (invitees.get(i).equals(invitee)) {

System.out.println(invitee + " has already been invited!");

break;

}

if (i == invitees.size() - 1) {

invitees.add(invitee);

System.out.println(invitee + " has been successfully invited!");

}

}

}

We need to loop through our existing invitees, which are stored in an ArrayList. 

If we find the invitee in our ArrayList, we tell the user that the person has already been invited. 

But if we checked the last index (last invitee, which is at position invitees.size() - 1 since indices start at 0) and we still did not find the person we're trying to invite, we can safely say that they have never been invited before. Then, we add the person to our ArrayList and tell the user the person has been successfully invited.

Please note that alternate solutions are possible with while loops and enhanced for loops (for-each loops.)