6-3 父子年龄比较 (10分)

该题目要求实现一个Age类,包括year,month,day三个变量,并有相应的构造方法和set方法,父亲的出生日期已经确定为1980年2月18日,然后输入儿子的出生日期,得到岁数的差异值,如果儿子和父亲的年龄差小于20岁抛出异常“too young”,大于70岁也抛出异常“too old”。注:1、年龄差取整。2、不用考虑年份,月份,日期输入的异常,只需要考虑都是合理值即可。
函数接口定义:

请仔细阅读题目提供代码。
裁判测试程序样例:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int y,m,d;
    y=sc.nextInt();
    m=sc.nextInt();
    d=sc.nextInt();
    sc.close();
    Age father=new Age(1980);
    father.setMonth(2);
    father.setDay(18);
    Age son=new Age(y,m,d);
    try{System.out.print(father.Compare(son));
    }
    catch(AgeException e){
        System.out.println(e.toString());
    }
}

}
/* 请在这里填写答案 */

输入样例:

在这里给出一组输入。例如:

2008 2 19

输出样例:

在这里给出相应的输出。例如:

28

class Age{
	int year,month,day;
	Age(int a)
	{
		this.year=a;
	}
	Age(int a,int b,int c)
	{
		this.year=a;
		this.month=b;
		this.day=c;
	}
	public void setMonth(int a)
	{
		this.month=a;
	}
	public void setDay(int b)
	{
		this.day=b;
	}
	public int Compare(Age a) throws AgeException
	{if(a.year-this.year<20)
	{
		throw new  AgeException("too young");
	}
	if(a.year-this.year>70)
	{
		throw new AgeException("too old");
	}
		return a.year-this.year;
	}
}
class AgeException extends Exception{
	String a;
	AgeException(String a)
	{
		this.a=a;
	}
	public String toString()
	{
		return a;
	}
}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值