How do I calculate someone's age in Java?

前端 未结 28 2318
渐次进展
渐次进展 2020-11-22 02:20

I want to return an age in years as an int in a Java method. What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)):



        
28条回答
  •  既然无缘
    2020-11-22 03:12

    import java.io.*;
    
    class AgeCalculator
    {
        public static void main(String args[])
        {
            InputStreamReader ins=new InputStreamReader(System.in);
            BufferedReader hey=new BufferedReader(ins);
    
            try
            {
                System.out.println("Please enter your name: ");
                String name=hey.readLine();
    
                System.out.println("Please enter your birth date: ");
                String date=hey.readLine();
    
                System.out.println("please enter your birth month:");
                String month=hey.readLine();
    
                System.out.println("please enter your birth year:");
                String year=hey.readLine();
    
                System.out.println("please enter current year:");
                String cYear=hey.readLine();
    
                int bDate = Integer.parseInt(date);
                int bMonth = Integer.parseInt(month);
                int bYear = Integer.parseInt(year);
                int ccYear=Integer.parseInt(cYear);
    
                int age;
    
                age = ccYear-bYear;
                int totalMonth=12;
                int yourMonth=totalMonth-bMonth;
    
                System.out.println(" Hi " + name + " your are " + age + " years " + yourMonth + " months old ");
            }
            catch(IOException err)
            {
                System.out.println("");
            }
        }
    }
    

提交回复
热议问题