Java实验十一

1、定义一个品牌电脑的枚举类,其中只有固定的几个电脑品牌。

枚举:

public enum Computer {
    Lenovo,Mac,Dell,Huawei;
}

测试:

public class Main {
    public static void main(String[] args) {
        for (Computer computer : Computer.values()) {
            System.out.println(computer);
        }
    }
}

Java实验十一_第1张图片

2、定义一个 Person 类,其中包括姓名、年龄、生日、性别的属性,其中性别只能是“男”或“女”。

枚举:

public enum Sex {
    Boy,Girl;
}

Person类:

import java.util.Date;

public class Person {
    private String name;
    private int age;
    private Date birthday;
    private Sex sex;

    public Person(String name, int age, Date birthday, Sex sex) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                ", sex=" + sex +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Sex getSex() {
        return sex;
    }

    public void setSex(Sex sex) {
        this.sex = sex;
    }
}

测试:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws Exception {
        Person per1 = new Person("张三", 29, (new SimpleDateFormat("yyyy-MM-dd")).parse("2000-1-1"), Sex.Boy);
        System.out.println(per1);
        Person per2 = new Person("李四", 27, (new SimpleDateFormat("yyyy-MM-dd")).parse("2002-3-1"), Sex.Girl);
        System.out.println(per2);
    }
}

Java实验十一_第2张图片

你可能感兴趣的:(Java实验,java)