【java】教師類及查找等 經典考題

package javatutorial.chapter3.lab.teacher;

public class Teacher implements Comparable<Teacher>{
	private int no;
	private String name;
	private int age;
	private String seminary;
	
	public Teacher(){
		
	}
	
	public Teacher(int no, String name, int age, String seminary) {
		this.no = no;
		this.name = name;
		this.age = age;
		this.seminary = seminary;
	}
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	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 String getSeminary() {
		return seminary;
	}
	public void setSeminary(String seminary) {
		this.seminary = seminary;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Teacher other = (Teacher) obj;
		
		if (no != other.no){
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		return "編號爲"+this.no+"、姓名爲"+this.name+"、年齡爲"+this.age+"的"+this.seminary+"老師";
	}

	@Override
	public int compareTo(Teacher t) {
		int res;
		if(this.no<t.no){
			res = -1;
		}else if(this.no>t.no){
			res = 1;
		}else{
			res = 0;
		}
		return res;
	}

}
package javatutorial.chapter3.lab.teacher;

import java.util.Comparator;

public class TeacherComparator implements Comparator<Teacher>{

	@Override
	public int compare(Teacher t1, Teacher t2) {
		int res;
		if(t1.getNo()<t2.getNo()){
			res = -1;
		}else if(t1.getNo()>t2.getNo()){
			res = 1;
		}else{
			res = 0;
		}
		return res;
	}

}

package javatutorial.chapter3.lab.teacher;

public class TeacherManagement {
	public static String search(Teacher[] teachers, String name){
		Teacher t = null;
		for(int i=0;i<teachers.length;i++){
			if(teachers[i]!=null && teachers[i].getName().equals(name)){
				t = teachers[i];
				break;
			}
		}
		
		if(t!=null){
			return t.toString();
		}else{
			return "沒有符合條件的教師";
		}
		
	}
	
	public static String search(Teacher[] teachers, int age){
		Teacher t = null;
		for(int i=0;i<teachers.length;i++){
			if(teachers[i]!=null && teachers[i].getAge()==age){
				t = teachers[i];
				break;
			}
		}
		
		if(t!=null){
			return t.toString();
		}else{
			return "沒有符合條件的教師";
		}
	}

}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章