自定义异常类①编写类InsuranceCheck和自定义异常类AgeException②创建Computer类,该类中有一个计算两个整数的最大公约数的方法,如果向该方法传递小于等于0的整数时,则该方法

本文介绍了如何在Java中编写自定义异常类AgeException,用于处理年龄过小的情况。同时,创建了Computer类,其中包含一个计算两个整数最大公约数的方法,当输入数值小于等于0时,会抛出自定义异常。

编写类InsuranceCheck和自定义异常类AgeException。用2010年减去某人的出生年份计算其年龄。然后用年龄减去16计算其驾龄。驾龄小于4年的驾驶员,每年需要缴纳2000元保险费,其他人支付1000元;未满16周岁,则不需保险,并且引发异常(年龄太小,不用保险)

package TopicSix;

import java.util.Scanner;

public class InsuranceCheck {
     public static void main(String[] args){
    	 Scanner scanner=new Scanner(System.in);
    	 int year=scanner.nextInt();
    	 int age=2010-year;
      	 try{
    		  int dage=age-16;
    		  int value=divide(dage);
    		  System.out.println("缴费:"+value);
    	 }catch(AgeException ex){
    		 System.out.println(ex.getMessage());
    		 ex.printStackTrace();
    	 }
    	 scanner.close();
     }
     
     public static int divide(int dage)throws AgeException{
    	 if(dage<0){
    		 throw new AgeException("年龄太小不用保险");
    	 }
    	 else if(dage<4)
    		 return 2000;
    	      else return 1000;
     }
}
package TopicSix;

public class AgeException extends Exception{
public AgeException(){
     super();
    }
public AgeException(String msg){
     super(msg);
    }
public AgeException(Throwable cause){
super(cause);
}
}

创建Computer类,该类中有一个计算两个整数的最大公约数的方法,如果向该方法传递小于等于0的整数时,则该方法就会抛出自定义的异常,请实现。

package ch006;

import java.util.Scanner;

public class Computer {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int x = scan.nextInt();
        int y = scan.nextInt();
        try {
            int mDivisor = measure(x, y);
            System.out.println(mDivisor);
        } catch (DivException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        scan.close();
    }

    public static int measure(int x, int y) throws DivException {
        if (x <= 0 || y <= 0) {
            throw new DivException("输入错误,xy应为大于零的整数");
        } else {
            int z = y;
            while (x % y != 0) {
                z = x % y;
                x = y;
                y = z;
            }
            return z;
        }
    }
}
package ch006;

public class DivException extends Exception {
    public DivException() {
    }

    public DivException(String msg) {
        super(msg);
    }
}
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值