获取人的年龄,当年龄小于0时抛出异常,输出 “age<0非法”,否则输出 年龄值 。
根据提供的主类信息,编写Person类和NoAgesException自定义类(继承Exception),以及在Person类的getAge方法中抛出自定义异常对象。
裁判测试程序:
主类如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
String name;
int age;
Scanner sc=new Scanner(System.in);
name=sc.next();
age=sc.nextInt();
Person p=new Person(name,age);
try {
int age1=p.getAge();
System.out.println(p.getName()+" "+age1);
}
catch(NoAgesException e) {
e.print();
}
}
}
输入样例:
在这里给出一组输入。例如:
zhangsan -23
结尾无空行
输出样例:
在这里给出相应的输出。例如:
age<0非法
结尾无空行
代码如下:
class Person extends Exception{
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() throws NoAgesException {
if(age>=0) {
return age;
}else {
throw new NoAgesException();
}
}
public void setAge(int age) {
this.age = age;
}
}
class NoAgesException extends Exception{
public void print() {
System.out.println("age<0非法");
}
}



