java定义一个Person类,里面有姓名、性别、年龄,年龄必须只能是0到150岁,性别只能是男或者女,然后在mian方法里面测试
时间: 2023-05-24 19:04:42 浏览: 411
java代码-使用java构造Person类。包括姓名(name),性别和年龄(age)的源代码
5星 · 资源好评率100%
下面是一个例子:
```
public class Person {
private String name;
private String gender;
private int age;
public Person(String name, String gender, int age) {
this.name = name;
setGender(gender);
setAge(age);
}
// Getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
if(gender.equalsIgnoreCase("男") || gender.equalsIgnoreCase("女")) {
this.gender = gender;
} else {
throw new IllegalArgumentException("性别必须为'男'或'女'");
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age >= 0 && age <= 150) {
this.age = age;
} else {
throw new IllegalArgumentException("年龄必须为0到150岁之间");
}
}
}
```
你可以在main方法里面测试这个类,例如:
```
public class Main {
public static void main(String[] args) {
Person person1 = new Person("张三", "男", 20);
Person person2 = new Person("李四", "女", 180); // 这里会抛出异常,因为年龄超过了150岁
Person person3 = new Person("王五", "未知", 30); // 这里会抛出异常,因为性别不是男或女
System.out.println("person1: " + person1.getName() + " " + person1.getGender() + " " + person1.getAge());
}
}
```
阅读全文