BirthDate.java A calendar date, as you know, is composed of a day, a month and a
ID: 3623495 • Letter: B
Question
BirthDate.java A calendar date, as you know, is composed of a day, a month and a year. Create a BirthDate class with a contructor with int day, int month and int year as parameters. YourBirthDate class must also have a getAge() method that will compute the age based on the given birth date.Suggestion: The statement
String today = new.Date().toString();
instantiates a String containing the current date in a particular format (print it to see) from which you can extract today's day, month, and year. Given these, you should be able to compute for the age based on the BirthDate. Test it by creating a main method that will ask the user to enter his/her birth date in dd-mm-yyyy and your program should be able to print the current age of the user.
> java BirthDate
Please enter your birth date (dd-mm-yyyy) : 23-02-1978
birth day: 23
birth month: 2
birth year: 1978
age: 32 years old
Explanation / Answer
please rate - thanks
import java.util.*;
public class BirthDateTest
{static String dob;
public static void main(String[] args)
{Scanner in=new Scanner(System.in);
int emonth,eday,eyear;
String sday,smonth,syear;
System.out.println("enter birth date mm-dd-yyyy: ");
String dob=in.next();
smonth=dob.substring(0,2);
sday=dob.substring(3,5);
syear=dob.substring(6,10);
emonth=Integer.parseInt(smonth);
eday=Integer.parseInt(sday);
eyear=Integer.parseInt(syear);
BirthDate date=new BirthDate(emonth,eday,eyear);
System.out.println("age: "+date.getAge()+" years old ");
}
}
-------------------------------------------------------
import java.util.*;
public class BirthDate
{private int month,day,year;
public BirthDate(int m,int d,int y)
{month=m;
day=d;
year=y;
}
public int getAge()
{Calendar cal = Calendar.getInstance();
int d,m,y,emonth,eday,eyear;
d = cal.get(Calendar.DATE);
m = cal.get(Calendar.MONTH) + 1;
y = cal.get(Calendar.YEAR);
if(m>month)
return y-year;
if(m==month&&d>=day)
return y-year;
return y-year-1;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.