2. 编写一个学生类,包括学号、姓名、年龄属性和一个构造方法,toString方法。2)主方法种键盘输入信息创建n个学生对象,将学生对象存放在集合中,按照年龄的高低排序输出. 要求: 1) 如果年龄不是整数,则抛出输入错误异常; 2)如果年龄小于3,抛出年龄低异常;如果年龄大于35,则抛出年龄高异常;3) 如果姓名或学号为空,则抛出空异常。编写测试程序。编写自定义异常类,包括空异常类、年龄低异常类和年龄高异常类。
时间: 2024-02-22 11:55:30 浏览: 26
好的,我会根据您的要求来编写这个学生类以及异常类。以下是代码:
```java
//自定义空异常类
class NullException extends Exception {
public NullException(String message) {
super(message);
}
}
//自定义年龄低异常类
class AgeLowException extends Exception {
public AgeLowException(String message) {
super(message);
}
}
//自定义年龄高异常类
class AgeHighException extends Exception {
public AgeHighException(String message) {
super(message);
}
}
//学生类
class Student implements Comparable<Student>{
private String studentId;
private String name;
private int age;
//构造方法
public Student(String studentId, String name, int age) throws Exception {
if (studentId == null || name == null) {
throw new NullException("学号或姓名为空");
}
this.studentId = studentId;
this.name = name;
if (age < 3) {
throw new AgeLowException("年龄太低");
} else if (age > 35) {
throw new AgeHighException("年龄太高");
}
this.age = age;
}
//重写toString方法
public String toString() {
return "学号:" + studentId + ", 姓名:" + name + ", 年龄:" + age;
}
//按年龄排序
public int compareTo(Student s) {
return this.age - s.age;
}
}
//测试类
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入学生人数:");
int n = sc.nextInt();
List<Student> list = new ArrayList<Student>();
for (int i = 0; i < n; i++) {
try {
System.out.println("请输入第" + (i+1) + "个学生的信息:");
System.out.print("学号:");
String studentId = sc.next();
System.out.print("姓名:");
String name = sc.next();
System.out.print("年龄:");
int age = sc.nextInt();
list.add(new Student(studentId, name, age));
} catch (NullException e) {
System.out.println("空异常:" + e.getMessage());
i--;
} catch (AgeLowException e) {
System.out.println("年龄低异常:" + e.getMessage());
i--;
} catch (AgeHighException e) {
System.out.println("年龄高异常:" + e.getMessage());
i--;
} catch (InputMismatchException e) {
System.out.println("输入错误异常:年龄必须为整数");
sc.next();
i--;
}
}
Collections.sort(list);
System.out.println("按年龄排序后的学生信息:");
for (Student s : list) {
System.out.println(s);
}
}
}
```
在测试类中,我们先输入学生的人数,然后循环输入每个学生的信息,如果输入的信息不符合要求,捕获对应的异常并打印异常信息。最后将学生按年龄排序输出。