1、自定义异常类:年龄异常 输出错误提示:非正常学生年龄 2、学生类:姓名,性别,年龄 Setter年龄,检查小于15,大于80,抛出“年龄异常”给上级 3、测试类 录入学生信息,输入年龄 捕捉非数字异常,异常时显示信息:输入年龄不是数字 捕捉年龄异常,异常时显示信息:非正常学生年龄 如果正常,getter方法输出学生信息
时间: 2023-11-28 12:49:18 浏览: 46
以下是实现该功能的代码示例:
```java
// 自定义年龄异常类
class AgeException extends Exception {
public AgeException() {
super("非正常学生年龄");
}
}
// 学生类
class Student {
private String name;
private String gender;
private int age;
public Student(String name, String gender, int age) throws AgeException {
this.name = name;
this.gender = gender;
setAge(age);
}
public void setAge(int age) throws AgeException {
if (age < 15 || age > 80) {
throw new AgeException();
}
this.age = age;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
public String toString() {
return "姓名:" + name + ",性别:" + gender + ",年龄:" + age;
}
}
// 测试类
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入学生姓名:");
String name = sc.nextLine();
System.out.print("请输入学生性别:");
String gender = sc.nextLine();
System.out.print("请输入学生年龄:");
try {
int age = Integer.parseInt(sc.nextLine());
Student student = new Student(name, gender, age);
System.out.println(student.toString());
} catch (NumberFormatException e) {
System.out.println("输入年龄不是数字");
} catch (AgeException e) {
System.out.println(e.getMessage());
}
}
}
```
使用示例:
```
请输入学生姓名:张三
请输入学生性别:男
请输入学生年龄:20
姓名:张三,性别:男,年龄:20
请输入学生姓名:李四
请输入学生性别:女
请输入学生年龄:100
非正常学生年龄
请输入学生姓名:王五
请输入学生性别:男
请输入学生年龄:abc
输入年龄不是数字
```