定义一个Birthday类,其成员变量有3个整形变量(出生的年月日):year,month,day;提供构造方法对这3个成员变量进行初始化;提供成员变量的get、set方法;成员函数有getAge(),功能是实现计算到2017年12月25日时该Birthday对象的年龄。编写程序测试这个类。
输入格式:
输入出生的年、月、日(注:输入的年月日以换行隔开)
输出格式:
计算得到年龄
样例">输入样例:
在这里给出一组输入。例如:
1995
12
23
输出样例:
在这里给出相应的输出。例如:
age=22
源代码如下
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
Birthday nl=new Birthday(a,b,c);
System.out.println("age="+nl.getAge());
}
}
class Birthday{
int year;
int month;
int day;
Birthday(int year,int month,int day){
this.year=year;
this.month=month;
this.day=day;
}public int getAge(){
if(this.month<12){
return (2017-this.year);
}else if(this.month==12&&this.day<25){
return (2017-this.year);
}else {
return (2018-this.year);
}
}
}
注意事项:本题要去分析月和日与所设定年龄的大小,如果比所设定的年龄小,可以直接减得到年龄,如果比所设年龄大,则要在相减的基础上加一。