Problem C: 异常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());}
}
}
Output Description:
John's age is valid!
peter's age is invalid!
peter's age is invalid!
我的代码:
1 class Person{ 2 String name; 3 int age; 4 public Person(){} 5 public Person(String a,int b){ 6 name = a; 7 age = b; 8 } 9 String invalid() 10 { 11 return name+"'s age is invalid!"; 12 } 13 String valid() 14 { 15 return name+"'s age is valid!"; 16 } 17 void isValid() throws AgeException 18 { 19 if( age>=200 ){ 20 //如果年龄异常则抛出异常,并创建一个异常类,传入消息 21 throw new AgeException(invalid()); 22 }else{ 23 throw new AgeException(valid()); 24 } 25 } 26 27 } 28 class AgeException extends Exception{ 29 String message; 30 public AgeException(){} 31 public AgeException( String message ){ 32 this.message = message; 33 } 34 public String getMessage() 35 { 36 return message; 37 } 38 }