import java.io.*;
import java.text.*;
import java.util.*;
public class FindAge
{
public static void main(String args[])
{
Person person
= new Person ();
person.getData();
person.displayData();
}
} // FindAge
/* The Person class gets the current date using a GregorianCalendar
class, reads in the birth date using a StringTokenizer, checks to see that
the read in date is valid, and then calculates and displays the age. */
class Person
{
private String name;
private int currentYear, currentMonth, currentDay,
birthYear, birthMonth, birthDay;
void getData()
{
getCurrentDate
(); // Gets the current date using a GregorianCalendar class.
String dataString;
StringTokenizer
tokenizer;
BufferedReader
stdin = new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter name, birth day, birth month and birth year on
a single line.");
dataString = stdin.readLine();
tokenizer = new StringTokenizer(dataString);
// Use the tokens to get the name and birthday of a person.
name = tokenizer.nextToken();
birthDay = Integer.parseInt (tokenizer.nextToken ());
birthMonth = Integer.parseInt (tokenizer.nextToken ());
birthYear = Integer.parseInt (tokenizer.nextToken ());
// Verify that the date read in is valid.
boolean validDate = verifyDate (birthDay, birthMonth, birthYear, currentYear);
if (!validDate) System.out.println ("Date invalid");
}catch (NumberFormatException
e){System.out.println("Number Format Error");}
catch (IOException
e){System.out.println("IO Error");}
}//End getData
// Use a GregorianCalendar class to get the
current date.
private void getCurrentDate ()
{
GregorianCalendar
now = new GregorianCalendar ();
currentDay =
now.get (Calendar.DATE);
currentMonth
= now.get (Calendar.MONTH);
currentMonth
++;
currentYear
= now.get (Calendar.YEAR);
} // getCurrentDate
// Use the current date and the birth date
to calculate a person’s age.
private int calculateAge ()
{
int age = currentYear
- birthYear;
if (currentMonth
< birthMonth) age --;
else
if ((currentMonth == birthMonth) && (currentDay < birthDay))
age --;
return age;
} // calculateAge
//Display the age on the screen.
void displayData()
{
int age = calculateAge
();
System.out.println
(name + "'s age is " + age);
} //End displayData
// Verify that the date given is a valid date.
private boolean verifyDate (int day, int month,
int year, int currentYear)
{
if (year > currentYear)
return false;
else
if ((month <=
0) || (month > 12) || (day <= 0) || (day > 31)) return false;
else
if ((month ==
2) && (day > 29)) return false; // February
else // April,
June, September, November
if (((month
== 4) || (month == 6) || (month == 9) || (month == 11) ) && (day
> 30)) return false;
else return
true;
} // verifyDate
}//end class Person