编写一个学生类,包括学号、姓名、年龄属性和一个构造方法,toString 方法。2) 主方法种键盘输入信息创建口个学生对象,将学生对象存放在集合中,按照年龄的高低排序输出. 要求:1) 如果年龄不是整数,则抛出输入错误异常;2)如果年龄小于了,拋出年龄低异常:如果年龄大于 35,则拋出年龄高异常;3) 如果姓名或学号为空,则抛出空异常。编写测试程序。编写自定义异常类,包括空异常类、年龄低异常类和年龄高 异常类。
时间: 2024-02-22 12:58:50 浏览: 15
好的,我可以为您提供相关的Java代码来实现这个功能。首先是学生类及其异常类的代码:
```java
class Student {
private String id;
private String name;
private int age;
public Student(String id, String name, int age) throws InputErrorException {
if (id == null || name == null) {
throw new InputErrorException("学号和姓名不能为空");
}
if (age < 0) {
throw new AgeLowException("年龄不能小于0");
}
if (age > 35) {
throw new AgeHighException("年龄不能大于35");
}
if (age != (int) age) {
throw new InputErrorException("年龄必须为整数");
}
this.id = id;
this.name = name;
this.age = age;
}
public String toString() {
return "学号:" + id + ", 姓名:" + name + ", 年龄:" + age;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class InputErrorException extends Exception {
public InputErrorException(String message) {
super(message);
}
}
class AgeLowException extends Exception {
public AgeLowException(String message) {
super(message);
}
}
class AgeHighException extends Exception {
public AgeHighException(String message) {
super(message);
}
}
```
然后是主程序的代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
try {
System.out.print("请输入学号:");
String id = scanner.nextLine();
System.out.print("请输入姓名:");
String name = scanner.nextLine();
System.out.print("请输入年龄:");
double age = Double.parseDouble(scanner.nextLine());
students.add(new Student(id, name, (int) age));
} catch (InputErrorException | AgeLowException | AgeHighException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println("年龄必须为数字");
}
System.out.print("是否继续添加学生信息?(Y/N)");
String answer = scanner.nextLine();
if (!answer.equalsIgnoreCase("Y")) {
break;
}
}
scanner.close();
Collections.sort(students, (s1, s2) -> s2.getAge() - s1.getAge());
System.out.println("按年龄从大到小排序输出:");
for (Student student : students) {
System.out.println(student);
}
}
}
```
此代码将首先创建一个学生类及其异常类,并在主程序中创建一个学生集合。然后,使用Scanner从键盘输入学生信息,并将学生对象添加到集合中。在输入过程中,如果出现空异常、年龄低异常、年龄高异常和输入错误异常,将会捕获并打印错误消息。输入完成后,将集合中的学生对象按年龄从大到小排序,并输出到控制台。