import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.ArrayList;

/**
 * Allows the user to enter the names and years of birth of various
 * people.  This program stores the entered information and then
 * prints it all when the user is done entering info.
 *
 * @author Zach Tomaszewski
 * @version 15 Oct 2008
 */
public class Rolodex {

  //Scanner delared as a global variable; can be used by any method in this class
  private static Scanner keybd = new Scanner(System.in);

  public static void main(String[] args) {

    ArrayList<Person> list = new ArrayList<Person>();
    System.out.println("This program will (temporily) keep track of people you know.");

    //keep getting name and year-of-birth until user enters nothing for the name
    String input = "start";
    while (!input.equals("")) {
      System.out.print("Enter a person's full name (or nothing to quit): ");
      input = keybd.nextLine();
      input = input.trim();

      if (input.length() > 0) {
        //really entered a name
        Person p = new Person(); //Person to load with data
        int lastSpace = input.lastIndexOf(" ");
        if (lastSpace > 0) {
          //name contains a space, so divide it on that
          p.firstName = input.substring(0, lastSpace);
          p.lastName = input.substring(lastSpace + 1);
        }else {
          //only a single word, so treat as firstname
          p.firstName = input;
          p.lastName = "";
        }

        //now need to get the year of birth
        int yob = 0;
        boolean gotYob = false;
        while (!gotYob) {
          System.out.print("Enter " + input + "'s year of birth: ");
          try {
            yob = keybd.nextInt();
            gotYob = true;
          }catch (InputMismatchException ime) {
            System.out.println("Year of birth must be an integer.  Please try again.");
          }
          keybd.nextLine(); //clear \n (and any other garbage) from stream
        }
        p.age = Person.CURRENT_YEAR - yob;

        //done; add this person to the list
        list.add(p);
        System.out.println();
      }
    }

    //user is done entering info, so print the list
    System.out.println();
    for (int i = 0; i < list.size(); i++) {
      Person next = list.get(i);
      System.out.print(next.lastName);
      if (!next.lastName.equals("")) {
        System.out.print(", ");
      }
      System.out.print(next.firstName);
      System.out.println("  (Age: " + next.age + ")");
    }

  }

}

