题目:写一个学生类,包括属性: 学号,班号,姓名,年龄,性别;要求用无参构造, 方法获得:学号,班号,姓名,年龄(只能小于100岁,大于1,否则重新输入) , 性别(只能男或者女,否则重新输入),构造程序并验证。
class Student {
private String studentId, classId, name, sex;
private int age;
public Student(String studentId, String classId, String name, String sex, int age) throws Exception {
setStudentId(studentId);
setClassId(classId);
setName(name);
setSex(sex);
setAge(age);
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getClassId() {
return classId;
}
public void setClassId(String classId) {
this.classId = classId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
if (sex != "男" && sex != "女") {
throw new RuntimeException("性别不合法");
}
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age < 0 || age > 100) {
throw new RuntimeException("年龄不合法");
}
this.age = age;
}
@Override
public String toString() {
return "学号:" + getStudentId() + ", 班号:" + getClassId() + ", 姓名:" + getName() + ", 年龄:" + getAge() + ", 性别:" + getSex();
}
}
public class Test {
public static void main(String[] args) throws Exception {
Student[] students = new Student[]{
new Student("******1", "20*****", "张三", "男", 20),
new Student("******2", "20*****", "李四", "女", 22)
};
for (Student s : students) {
System.out.println(s);
}
}
}