Java 计算年龄

定义一个Birthday类,其成员变量有3个整形变量(出生的年月日):year,month,day;提供构造方法对这3个成员变量进行初始化;提供成员变量的get、set方法;成员函数有getAge(),功能是实现计算到2017年12月25日时该Birthday对象的年龄。编写程序测试这个类。

输入格式:
输入出生的年、月、日(注:输入的年月日以换行隔开)

输出格式:
计算得到年龄

输入样例:
在这里给出一组输入。例如:
1955
12
23
输出样例:
在这里给出相应的输出。例如:
age=22

import java.util.Scanner;
class Birthday{
    private int year;
    private int month;
    private int day;    
    public Birthday(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public int getYear() {
        return year;
    }
    public void setYear(int year) {
        this.year = year;
    }
    public int getMonth() {
        return month;
    }
    public void setMonth(int month) {
        this.month = month;
    }
    public int getDay() {
        return day;
    }
    public void setDay(int day) {
        this.day = day;
    }
    public static void getAge(int year,int month,int day){
        int age=0;
        age = 2017-year;
        if(month==12 && day>=25){
        age--;
        }
        System.out.println("age="+age);
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner scan =new Scanner(System.in);
        int year=scan.nextInt();
        int month=scan.nextInt();
        int day=scan.nextInt();
        Birthday.getAge(year,month,day);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_41611106/article/details/80291124