1.题目描述
检测年龄,其中若为负数或大于等于200岁皆为异常,请将下列代码补充完整。
// 你的代码将被嵌入这里
class Main{
public static void main(String[] args){
Person p1=new Person("John",80);
Person p2=new Person("peter",210);
try{p1.isValid();}catch(AgeException e){System.out.println(e.getMessage());}
try{p2.isValid();}catch(AgeException e){System.out.println(e.getMessage());}
}
}
2.输出描述
John's age is valid!
peter's age is invalid!
3.代码实现
1.提交的代码
class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void isValid() throws AgeException {
if (age < 0 || age >= 200) {
throw new AgeException(this.name + "'s age is invalid!");
} else {
System.out.println(this.name + "'s age is valid!");
}
}
}
2.完整代码
class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void isValid() throws AgeException {
if (age < 0 || age >= 200) {
throw new AgeException(this.name + "'s age is invalid!");
} else {
System.out.println(this.name + "'s age is valid!");
}
}
}
class Main {
public static void main(String[] args) {
Person p1 = new Person("John", 80);
Person p2 = new Person("peter", 210);
try {
p1.isValid();
} catch (AgeException e) {
System.out.println(e.getMessage());
}
try {
p2.isValid();
} catch (AgeException e) {
System.out.println(e.getMessage());
}
}
}