大家好,又见面了,我是你们的朋友全栈君。
Description
设计一个教师类Teacher,要求:
属性有编号(int no)、姓名(String name)、年龄(int age)、所属学院(String seminary),为这些属性设置相应的get和set方法。
为Teacher类重写equals方法,要求:当两个教师对象的no相同时返回true。
重写Teacher类的toString方法,通过该方法可以返回“no: **, name:**, age: **, seminary: **”形式的字符串。
Input
两个教师对象的编号,姓名,年龄,学院
Output
教师的信息
两个教师是否相等
Sample Input
1 Linda 38 SoftwareEngineering
2 Mindy 27 ComputerScience
Sample Output
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 scan = new Scanner(System.in);
int no1 = scan.nextInt();
String name1 = scan.next();
int age1 = scan.nextInt();
String semi1 = scan.next();
Teacher teacher1 = new Teacher(no1,name1,age1,semi1);
System.out.println(teacher1);
int no2 = scan.nextInt();
String name2 = scan.next();
int age2 = scan.nextInt();
String semi2 = scan.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 n) {
no = n;
}
public void setName(String na) {
name = na;
}
public void setAge(int a) {
age = a;
}
public void setSeminary(String s) {
seminary = s;
}
public int getNo() {
return no;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getSeminary() {
return seminary;
}
public boolean equals(Object o) {
if(o == null)
{
return false;
}
else if(o instanceof Teacher)
{
Teacher t = (Teacher)o;
if(this.no == t.no && this.age == t.age && this.name.equals(t.name) && this.seminary.equals(t.seminary))
{
return true;
}
}
return false;
}
public String toString() {
return "no: "+this.no +", name:"+this.name+", age: "+this.age+", seminary: "+this.seminary;
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/157155.html原文链接:https://javaforall.cn