1)定义一个运行时异常 StudentException。 2)定义一个学生类 Student,含成员变量姓名 name,年龄 age,性别 sex.一个带三个参数的构造方法。 及一个成员方法 public void show(),用来显示学生信息。在方法 中,判断姓名字符数如果超出 5,抛出 StudentException 异常,消息 为"姓名不合法,太长"; age 如果小于 10 或大于 30,抛出 StudentException 异常,消息为" 年龄不合法,年龄必须为 10~30 之间" sex 如果不等于"男"或“女”,抛出 StudentException 异常,消息 为"性别不合法,性别只能为男或女" 3)定义一个 TestStudent 类,在 main 方法中定义几个 Student 实例, 并调用 show 方法;
时间: 2024-02-26 14:57:28 浏览: 7
以下是代码实现:
```java
// 定义运行时异常
class StudentException extends RuntimeException {
public StudentException(String message) {
super(message);
}
}
// 定义学生类
class Student {
private String name;
private int age;
private String sex;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void show() {
if (name.length() > 5) {
throw new StudentException("姓名不合法,太长");
}
if (age < 10 || age > 30) {
throw new StudentException("年龄不合法,年龄必须为 10~30 之间");
}
if (!sex.equals("男") && !sex.equals("女")) {
throw new StudentException("性别不合法,性别只能为男或女");
}
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
System.out.println("性别:" + sex);
}
}
// 测试类
public class TestStudent {
public static void main(String[] args) {
Student stu1 = new Student("Tom", 18, "男");
stu1.show();
// 姓名过长
Student stu2 = new Student("William", 20, "男");
try {
stu2.show();
} catch (StudentException e) {
System.out.println(e.getMessage());
}
// 年龄不合法
Student stu3 = new Student("Lucy", 8, "女");
try {
stu3.show();
} catch (StudentException e) {
System.out.println(e.getMessage());
}
// 性别不合法
Student stu4 = new Student("Jack", 25, "未知");
try {
stu4.show();
} catch (StudentException e) {
System.out.println(e.getMessage());
}
}
}
```
输出结果为:
```
姓名:Tom
年龄:18
性别:男
姓名不合法,太长
年龄不合法,年龄必须为 10~30 之间
性别不合法,性别只能为男或女
```