Java Reference
In-Depth Information
public static void main(String[] args) {
FormattedInput in = new FormattedInput();
// Get the date of birth from the keyboard
System.out.println("Enter your birth date as dd mm yyyy: ");
int day = in.readInt();
int month = in.readInt();
int year = in.readInt();
// Create birth date calendar - month is 0 to 11
GregorianCalendar birthdate = new GregorianCalendar(year, month-1,day);
GregorianCalendar today = new GregorianCalendar(); // Today's date
// Create this year's birthday
GregorianCalendar birthday = new GregorianCalendar(
today.get(today.YEAR),
birthdate.get(birthdate.MONTH),
birthdate.get(birthdate.DATE));
int age = today.get(today.YEAR) - birthdate.get(birthdate.YEAR);
String[] weekdays = new DateFormatSymbols().getWeekdays(); // Get day names
System.out.println("You were born on a " +
weekdays[birthdate.get(birthdate.DAY _ OF _ WEEK)]);
System.out.println("This year you " +
(birthday.after(today) ?"will be " : "are ") +
age + " years old.");
System.out.println("This year your birthday "+
(today.before(birthday)? "will be": "was")+
" on a "+ weekdays[birthday.get(birthday.DAY _ OF _ WEEK)]);
}
}
I got the output:
Enter your birth date as dd mm yyyy:
5 12 1964
You were born on a Saturday
This year you will be 34 years old.
This year your birthday will be on a Saturday
How It Works
We start by prompting for the day, month, and year for a date of birth to be entered through the keyboard as
integers. We then create a Calendar object corresponding to this date. Note the adjustment of the month -
the constructor expects January to be specified as 0 . We need a Calendar object for today's date so we use
the default constructor for this. To compute the age this year, we just have to subtract the year of birth from
this year, both of which we get from the GregorianCalendar objects.
Search WWH ::




Custom Search