Write one to get the current year, month and day, and get the date of birth from the keyboard, and calculate the age and age, the specific conditions are as follows:

  1. Define a Birth class with member variables: year, month, and day. Define two constructors. The parameterless construction method initializes the member variables to year=0, month=0, day=0; the parameterized construction method (3 parameters) assigns values ​​to the variables (you may not check the rationality of the assignment).
  2. The method of calculating age, calcuAges(): Its function is to get the current date, calculate the difference between the current date and the member variable year, month, and day, and only need to calculate to the year and print it out. For example, 20 years old and 8 months old will be printed as 20 years old; and 19 years old if one day is less than 20 years old.
    Print format: For example, a person born on December 10, 2000 is 19 years old today.
    Birth.java
import java.util.*;
public class Birth {
    
    
	private int year;
	private int month;
	private int day;
	public Birth() {
    
    
		this.year=0;
		this.month=0;
		this.day=0;
	}							//定义参数
	public Birth(int y,int m,int d) {
    
    
		this.year=y;
		this.month=m;
		this.day=d;
	}							//定义构造函数
	public void calcuAges(int year,int month,int day) {
    
    
		Calendar cal=Calendar.getInstance();
		int ages=0;
		year=cal.get(Calendar.YEAR);
		month=1+cal.get(Calendar.MONTH);
		day=1+cal.get(Calendar.DAY_OF_MONTH);			//获取系统时间
		ages=year-this.year-1;							//默认减一
		if(month>this.month)
			ages++;									//如果生日月小于当前月,自增
		else if((day<this.day)&&(month==this.month))
			ages++;									//当前月与生日月一致时判断日
		System.out.println(this.year+"年"+this.month+"月"+this.day+"日出生的人,今天"+ages+"岁");
	}
}

Test.java

import java.util.Scanner;
public class Test {
    
    
	public static void main(String[] args) {
    
    
		//TODO Auto-generated method stub
		int y,m,d;
		Scanner in=new Scanner(System.in);
		System.out.println("请输入出生年月日:");
		y=in.nextInt();
		m=in.nextInt();
		d=in.nextInt();
		Birth a=new Birth(y,m,d);
		a.calcuAges(y, m, d);
	}
}

Results screenshot
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/The_Handsome_Sir/article/details/108902977