Calculate age in java

Posted By: Java Examples - 8:13 PM

Share

& Comment

Here, you can calculate the age of a person easily through the given program. This program takes your complete date of birth (year, month and day of month) and gives you the exact age which determines the years, months and days of the calculated age of the person. Following program is fully validated. Because of this you can not enter any invalid year or month or day for your date of birth.


Java version of the  AgeCalculate is given below : 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package age;

import java.util.Scanner;

/**
 *
 * @author ACHCHUTHAN
 */
public class AgeCalculate {

    int month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    String id;
    int d, m, y;

    public AgeCalculate() {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter your day=");
        d = input.nextInt();
        System.out.println("Enter your month=");
        m = input.nextInt();
        System.out.println("Enter your year=");
        y = input.nextInt();
    }

    public void CalculateAge() {
        int date = 0, mon = 0, year = 0;

        if (1 < d && 1 < m) {
            date = ((month[m - 1] + 01) - d);
            mon = (12 - m);
            year = (2012 - y);
        } else if (1 < d && 1 >= m) {
            date = ((month[m - 1] + 01) - d);
            mon = (12 - m);
            year = (2012 - y);
        } else if (d == 1 && 1 < m) {
            date = 1 - d;
            mon = (13 - m);
            year = (2010 - y);
        } else if (d == 1 && m == 1) {
            date = 1 - d;
            mon = (13 - m);
            year = (2012 - y);
        }
        System.out.println(year + " years " + mon + " months " + date + " days");
    }

    public static void main(String args[]) {
        AgeCalculate a = new AgeCalculate();
        System.out.println("Your age calculated on 2012/01/01");
        a.CalculateAge();
    }
}


Output of this program is given bellow :

run:
Enter your day=
12
Enter your month=
2
Enter your year=
1990
Your age calculated on 2012/01/01
22 years 10 months 17 days
BUILD SUCCESSFUL (total time: 8 seconds)



About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .