Using Java program Write a method that takes a date of birth via Calendar object
ID: 3700938 • Letter: U
Question
Using Java programWrite a method that takes a date of birth via Calendar object and returns your age. If it is your birthday, print the Happy Birthday song!
Using Java program
Write a method that takes a date of birth via Calendar object and returns your age. If it is your birthday, print the Happy Birthday song!
Write a method that takes a date of birth via Calendar object and returns your age. If it is your birthday, print the Happy Birthday song!
Write a method that takes a date of birth via Calendar object and returns your age. If it is your birthday, print the Happy Birthday song!
Explanation / Answer
Below is your code. Let me know in comments if you have any issues: -
public class AgeCalculator {
// main method to run the application
public static void main(String[] args) throws Exception {
// date as String
String inputDate = "1992-04-05";
// parsing it as Calendar object
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar dob = Calendar.getInstance();
dob.setTime(sdf.parse(inputDate));
// printing age
System.out.println("Age is:" + getAge(dob));
String hbdSong = "Happy Birthday to You, Happy Birthday to You, Happy Birthday Dear, Happy Birthday to You.";
// printing happy birthday song.
Calendar today = Calendar.getInstance();
if ((today.get(Calendar.MONTH) == dob.get(Calendar.MONTH))
&& (today.get(Calendar.DAY_OF_MONTH) == dob.get(Calendar.DAY_OF_MONTH))) {
System.out.println(hbdSong);
}
}
// Returns age given the date of birth
public static int getAge(Calendar dob) throws Exception {
Calendar today = Calendar.getInstance();
int curYear = today.get(Calendar.YEAR);
int dobYear = dob.get(Calendar.YEAR);
int age = curYear - dobYear;
// if dob is month or day is behind today's month or day
// reduce age by 1
int curMonth = today.get(Calendar.MONTH);
int dobMonth = dob.get(Calendar.MONTH);
if (dobMonth > curMonth) { // this year can't be counted!
age--;
} else if (dobMonth == curMonth) { // same month? check for day
int curDay = today.get(Calendar.DAY_OF_MONTH);
int dobDay = dob.get(Calendar.DAY_OF_MONTH);
if (dobDay > curDay) { // this year can't be counted!
age--;
}
}
return age;
}
}
Output
Age is:26
Happy Birthday to You,
Happy Birthday to You,
Happy Birthday Dear,
Happy Birthday to You.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.