In: Computer Science
In this exercise, you’ll write a program that accepts a person’s
birth date from the console and displays the person’s age in years.
To make that easier to do, we’ll give you a class that contains the
code for accepting the birth date. The console output for the
program should look something like this:
f Welcome to the age calculator. j
Enter the month you were born (1 to 12) : 5 Enter the day of the
month you were born: 16 Enter the year you were born (four digits):
1959
Your birth date is May 16, 1959 Today's date is Feb 9, 2012 Your
age is: 52
1. Open the project named chl3_ex2_AgeCalculator that’s in the
ex_starts directory. Then, review the code in the AgeCalculatorApp
class.
2. Add code to this class that gets the current date and then uses
the current year to validate the birth year the user enters. The
user should not be allowed to enter a year after the current year
or more than 110 years before the current year.
3. Add code to create, format, and print the user’s birth date and
to format and print the current date.
4. Add code to calculate and print the user’s age.
5. Test this project with a variety of dates to be sure it
works.
CODE:-
// Importing Modules
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Scanner;
public class AgeCalculatorApp {
public static void main(String[] args) {
Date d = new Date(); //Date Object
Scanner in = new Scanner(System.in);
int month,day,year;
String months[] =
{"Jan","Feb","Mar","Apr","May","June","July",
"Aug","Sept","Oct","Nov","Dec"};
//Taking Inputs From User
System.out.print("Enter the month you were born (1 to 12) :
");
month = in.nextInt();
System.out.print("Enter the day of the month you were born:
");
day = in.nextInt();
int currentyear = d.getYear()+1900;
year = currentyear+1;
//Year Conditions
while(year>currentyear) // Year > Currentyear Condition
{
System.out.print("Enter the year you were born (four digits):
");
year = in.nextInt();
if(currentyear-110 > year) // More Than 110 Condition
year = currentyear+1;
}
// Present Date Calculations
String pmonth = months[d.getMonth()];
int pday = d.getDate();
int pyear = d.getYear()+1900;
//Extracting Users Month Name
String umonth = months[month-1];
//Age Calculation
LocalDate user_date = LocalDate.of(year,month,day);
LocalDate present_date = LocalDate.now();
long age = ChronoUnit.YEARS.between(user_date, present_date);
//Printing Output
System.out.println("Welcome to the age calculator.j");
System.out.println("Your birth date is "+umonth+" "+day+",
"+year);
System.out.println("Today's date is "+pmonth+" "+pday+",
"+pyear);
System.out.println("Your age is: "+age);
}
}
Code Screenshots:-
Sample Outputs:-
Here I Attached Code And Sample Output
For Indentation Please Go Through Screenshots
For Any Queries Please Comment
Please Do Like