Day 2 - Java

Problem Statement: Age Calculation

You have to write a Java program that calculates the age of a person based on the given year, month, and day. You need to complete the program to read the birth year, month, and day from the input, calculate the age, and print it in the format "years - months - days old".

Input Format:

The input consists of three integers separated by space:

The first integer represents the birth year (1900 ≤ year ≤ Current Year).

The second integer represents the birth month (1 ≤ month ≤ 12).

The third integer represents the birth day (1 ≤ day ≤ 31).

Output Format:

Print the age in the format "years - months - days old".

Sample Input:

1981    7    7

2015    2    6

Sample Output:

42 years - 8 months - 17 days old

9 years - 1 months - 18 days old


SOLUTION:

import java.time.LocalDate;

import java.time.Period;

import java.util.Scanner;

public class Program {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int year = scanner.nextInt();

        int month = scanner.nextInt();

        int day = scanner.nextInt();

        calculateAge(year, month, day);

    }

    public static void calculateAge(int year, int month, int day) {

        LocalDate today = LocalDate.now();

        LocalDate birthday = LocalDate.of(year, month, day);

        Period period = Period.between(birthday, today);

        int years = period.getYears();

        int months = period.getMonths();

        int days = period.getDays();

        System.out.println(years + " years - " + months + " months - " + days + " days old");

    }

}


Insights:
  1. Explore util and time modules. Have a look at the other sub packages related to date and time respectively.
  2. Understand the difference in getting user input as arrays and getting the numbers separated by space. Have a keen observation. 
  3. Carefully note the difference between the variables year vs years, month vs months and day vs days. See which is the local variable in function and which are user input variables. Some variables are test case and question oriented, carefully notice the differences. 
  4. Know the difference between Date and LocalDate class. Here there is no need of time difference, so timezone is not incorporated and GMT is used. Explore how to use IST.
  5. Read about Period class and the parameters passed.
  6. Try including try catch blocks to avoid out of range inputs like negative numbers and values > 31 for days and > 12 for months.
  7. Be cautious in the output format. Even an extra space will not pass the hidden test cases.
Advance Happy Birthday for the learners whose birthdays are yet to come and belated wishes for the Jan, Feb and March people! 

Enjoy coding with a piece of cake and as a piece of cake! Cake and Coding is a great combo! 
Tasty Learning! :)

Comments