
import javax.swing.JOptionPane;
import java.util.Calendar;
import java.io.*;

/**
 * Stupid program that asks the user for their name and year they were born,
 * and then reports their age.  Also stores a record in a text file.
 * 
 * @author Zach Tomaszewski
 * @version 28 Nov 07
 */
public class AgeCalculator {

  public static final String SAVE_FILE = "ages.txt";
  
  public static void main(String[] args) {

    //get user's name
    String name  = JOptionPane.showInputDialog("Enter your name: ");

    //construct age prompt
    String prompt;
    if (name == null  || name.equals("")) {
      //anonymous prompt
      prompt = "Please enter the year your were born: ";
    }else {      
      prompt = name + ", enter the year you were born: ";  
    }

    //get user's age
    String yearString = JOptionPane.showInputDialog(prompt);
    int age;
    try {
      int year = Integer.parseInt(yearString);
      Calendar rightNow = Calendar.getInstance(); //gets current time
      age = rightNow.get(Calendar.YEAR) - year;
    }catch (NumberFormatException nfe) {
      //if they didn't enter a valid year, just treat age as 0
      age = 0;
    }
    
    //give results to user
    JOptionPane.showMessageDialog(null, "Your age is " + age + "."); 
    
    //now save data to output file
    try {
      //open (or create) file to write to; append = true
      PrintWriter fileOut = new PrintWriter(
                            new BufferedWriter(new FileWriter(SAVE_FILE, true)));
      fileOut.println(name + " is " + age + " years old.");
      fileOut.close();
    }catch (IOException ioe) {
      JOptionPane.showMessageDialog(null, "Could not save age to file.");
    }
  }

}
