编写类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);
}
}

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

2389





