写一个学生类,包括学号、姓名、年龄属性和一个构造方法,toString方法。2)主方法种键盘输入信息创建n个学生对象,将学生对象存放在集合中,按照年龄的高低排序输出. 要求: 1) 如果年龄不是整数,则抛出输入错误异常; 2)如果年龄小于3,抛出年龄低异常;如果年龄大于35,则抛出年龄高异常;3) 如果姓名或学号为空,则抛出空异常。编写测试程序。编写自定义异常类,包括空异常类、年龄低异常类和年龄高异常类。
时间: 2024-02-15 10:01:54 浏览: 70
写一个类Student,包含三个属性学号id,姓名name和年龄age;要求覆盖基类Object中的ToString()方法和Equals()方法,使得直接输出Student对象时输出的是对象的id,name和age信息;并且当两个对象的学号相同时认为它们相等;
4星 · 用户满意度95%
好的,下面是代码实现:
```java
import java.util.*;
class Student {
private String id;
private String name;
private int age;
public Student(String id, String name, int age) throws Exception {
if (id == null || name == null || id.equals("") || name.equals("")) {
throw new EmptyException();
}
if (age < 3) {
throw new AgeLowException();
}
if (age > 35) {
throw new AgeHighException();
}
if (age != (int) age) {
throw new InputErrorException();
}
this.id = id;
this.name = name;
this.age = age;
}
public String toString() {
return "学号:" + id + ",姓名:" + name + ",年龄:" + age;
}
public int getAge() {
return age;
}
}
class AgeLowException extends Exception {
public AgeLowException() {
super("年龄低异常");
}
}
class AgeHighException extends Exception {
public AgeHighException() {
super("年龄高异常");
}
}
class InputErrorException extends Exception {
public InputErrorException() {
super("输入错误异常");
}
}
class EmptyException extends Exception {
public EmptyException() {
super("空异常");
}
}
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生个数:");
int n = scanner.nextInt();
List<Student> students = new ArrayList<>();
for (int i = 0; i < n; i++) {
try {
System.out.println("请输入第" + (i + 1) + "个学生的信息:");
System.out.print("学号:");
String id = scanner.next();
System.out.print("姓名:");
String name = scanner.next();
System.out.print("年龄:");
int age = scanner.nextInt();
Student student = new Student(id, name, age);
students.add(student);
} catch (InputErrorException | AgeLowException | AgeHighException | EmptyException e) {
System.out.println(e.getMessage());
i--;
} catch (Exception e) {
System.out.println("未知异常");
i--;
}
}
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s2.getAge() - s1.getAge();
}
});
System.out.println("按照年龄排序输出:");
for (Student student : students) {
System.out.println(student);
}
}
}
```
运行程序,输入学生个数和每个学生的信息,程序会按照学生年龄的高低排序输出,如果输入有误则会抛出相应的异常。
阅读全文