Dance Guest List - storing in a Vector (collection)

  Download Source Code

/************************************************
Dan is in charge of the school's Halloween dance.  
He stands at the entrance and records the names of people
when they arrive.  When they leave, he crosses out the name.
So at any given time, he has a list of people in the room.
If someone leaves temporarily, to fetch something, their
name is crossed out and then added again when they re-enter.
This program uses a VECTOR to maintain a list of names,
replacing the paper list.
*************************************************/

import java.util.*;

public class DanceVector
{
  Vector names = new Vector();
  
  public DanceVector()
  {
    while(true)                // this loop runs forever
    {
      String n = input("Name");
      if(n.equals("quit")) 
      { System.exit(0); }     // type "quit" to end the program
      if(names.contains(n))
      {
        String ok = input(n + " is leaving? (Y/N)");
        if( ok.equals("Y") || ok.equals("y") || ok.equals("") )
        {
          names.remove(n); 
        }
      }
      else
      { 
        names.add(n); 
      } 
      printAll();
    } 
  }
  
  void printAll()
  {
    Iterator iter = names.listIterator();
    
    while(iter.hasNext())
    {
      System.out.println(iter.next());
    }
    System.out.println("============");
  }
  
  public static void main(String[] args)
  {  new DanceVector(); }
  
  public String input(String prompt)
  { return javax.swing.JOptionPane.showInputDialog(null,prompt); }
  
  public void output(String message)
  {  javax.swing.JOptionPane.showMessageDialog(null,message);  }
} 

Using Collections

A collection is similar to an array, but we do not use an [index] to access the items in the list.  Instead, the
collection provides an iterator which can count through the list, as well as other methods like .contains
to check whether an item is found in the list, .add to add a new item to the list, and .remove to remove
an item from the list.  So a collection is a list of data with lots of useful methods already provided.

Java has several different collection classes.  This program uses the Vector class, which is probably the
most straightforward collection class.  It is also very similar to the Collection object described in the
IB Computer Science pseudocode. 

How the Program Works

This program is used to collect a bunch of names of students attending a dance.  As students enter,
their names are added to the collection.  When they leave, the name is removed from the collection.
The program makes a simple decision based on the contains method - if the name is already contained
in the collection, then it is removed.  Otherwise it is added.  After each change, the printAll( ) method
iterates through the list and prints all the names that are currently in the list.

Programming Practice