【Java[类的创建与使用]】7-1 教师类

设计一个教师类Teacher,要求:
属性有编号(int no)、姓名(String name)、年龄(int age)、所属学院(String seminary),为这些属性设置相应的get和set方法。
为Teacher类重写equals方法,要求:当两个教师对象的no相同时返回true。
重写Teacher类的toString方法,通过该方法可以返回“no: , name:, age: **, seminary: **”形式的字符串。

输入格式:
两个教师对象的编号,姓名,年龄,学院

输出格式:
教师的信息
两个教师是否相等

输入样例:
在这里给出一组输入。例如:

1 Linda 38 SoftwareEngineering
2 Mindy 27 ComputerScience

输出样例:
在这里给出相应的输出。例如:

no: 1, name:Linda, age: 38, seminary: SoftwareEngineering
no: 2, name:Mindy, age: 27, seminary: ComputerScience
false

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int no1 = sc.nextInt();
        String name1 = sc.next();
        int age1 = sc.nextInt();
        String semi1 = sc.next();
        Teacher teacher1 = new Teacher(no1,name1,age1,semi1);
        System.out.println(teacher1);
        int no2 = sc.nextInt();
        String name2 = sc.next();
        int age2 = sc.nextInt();
        String semi2 = sc.next();
        Teacher teacher2 = new Teacher(no2,name2,age2,semi2);
        System.out.println(teacher2);
        System.out.println(teacher1.equals(teacher2));
    }
}
class Teacher
{
    private int no;
    private String name;
    private int age;
    private String seminary;
    public Teacher(int no,String name,int age,String seminary)
    {
        this.no = no; 
        this.name = name;
        this.age = age;
        this.seminary = seminary;
    }
    public void setNo(int no)
    {
        this.no = no; 
    } 
    public void setName(String name)
    {
        this.name = name;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public void setSeminary(String seminary)
    {
        this.seminary = seminary;
    }
    public int getNo()
    {
        return no;
    }
    public String getName()
    { 
        return name;
    }
    public int getAge()
    { 
        return age; 
    }
    public String getSeminary()
    {
        return seminary; 
    } 
    public boolean equals(Object obj)
    {
            Teacher o= (Teacher)obj; 
        if(this.no==o.no)
            return true;
        else
            return false;
    }
    public String toString() {
        return "no: "+this.no +", name:"+this.name+", age: "+this.age+", seminary: "+this.seminary;
    }
}
posted @ 2022-10-25 20:19  卞彦秋euReKa  阅读(259)  评论(0编辑  收藏  举报