Asked By
Ruth E Tran
80 points
N/A
Posted on - 09/11/2012
Hi,
I have a project which is related to simple age calculator in java programming language. And I want to download a sample codes from the internet. How would I do that? Inform me a step by step process. Thanks
Simple age calculator in java sample code download.
Hi,
First of all you will need an IDE (Integrated Development Environment), this is where you are going to put and compile the JAVA code. One of the easiest IDE to use is Netbeans. You may download the latest version of it in the link below.
https://netbeans.org/downloads/
After downloading it, click File —-> New Project. In the box, select Java —–> Java Application. Click next then type AgeCalculation as filename and then click Finish.
Copy the code from the link below. Make sure you copy everything in the box.
https://www.roseindia.net/java/example/java/util/AgeCalculation.shtml
Delete everything below "package AgeCalculation;", and paste the code that you copied from the website above. Select Run Main Project above. The code should compile and run, and you will see in the output "Enter year of your date of birth : ", just input your answer whenever it is needed (input should be in number format. example: July should be 7) and it will calculate your age.
Hope this helps. Good luck!
Â
Simple age calculator in java sample code download.
Â
Hi Ruth E Tran,
Â
Please find the below code for Age Calculation in Java.
Â
import java.util.*;
Â
public class AgeCalc {
  public static void main(String[] args) {
    String dateOfBirth = "02/09/1983";//Hard coded for easiness. Need to get user input
    int age = calculateAge(dateOfBirth);
    System.out.println(age);
  }
  public static int calculateAge(String dateOfBirth){
    Calendar calendar = Calendar.getInstance();
    int currentYear = calendar.get(Calendar.YEAR);
    int currentMonth = calendar.get(Calendar.MONTH);
    currentMonth = currentMonth+1;
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
Â
int birthYear = Integer.parseInt(dateOfBirth.substring(dateOfBirth.lastIndexOf("/")+1));
    int birthMonth = Integer.parseInt(dateOfBirth.substring(0,dateOfBirth.indexOf("/")));
    int birthDay = Integer.parseInt(dateOfBirth.substring(dateOfBirth.indexOf("/")+1,
                        dateOfBirth.lastIndexOf("/")));
    int age = 0;
    if(currentMonth > birthMonth){
        age = currentYear – (birthYear);
    }
    else if(currentMonth == birthMonth && currentDay >= birthDay){
        age = currentYear – (birthYear);
    }
    else age = currentYear – (birthYear + 1);
    return age;
  }
}
Â
Â
Hope it helps.