作业 给一组教师数列排序(按年龄)
源代码:
测试类代码:
public class TestCallBack {
public static void main(String[] args) {
Teacher[] t = new Teacher[]{new Teacher("mike",20),new Teacher("annie",19),new Teacher("jack",21)};
Tools.tool(t);
for(int i=0;i<t.length;i++){
System.out.println(t[i].age+"\t"+t[i].name);
}
}
}
class Teacher implements Comparable{
String name;
int age;
public Teacher(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int compareTo(Teacher o) {
if(this.age>o.age){
return 1;
}else if(this.age<o.age){
return -1;
}
return 0;
}
}
接口代码:
public class Interface {
interface Comparable{
//比较老师的年龄,this与传入的teacher比较
//this大输出整数 互换位置 传入的teacher大 输出负数 相等 输出0
public abstract int compare(Teacher teacher);
}
}
工具代码:
public class Tools {
public static void tool(Teacher[] t1){
for(int i=0;i<t1.length-1;i++){
Comparable currentT1=(Comparable)t1[i];
int a=currentT1.compareTo(t1[i+1]);
if(a>0){
Teacher temp=t1[1];
t1[1]=t1[0];
t1[0]=temp;
}
}
}
}
运行效果图:
附加: 哥德巴赫猜想 用接口知识实现:
源代码:
测试类
package day19.t2;
import day19.t2.Interface.MathTools;
public class TestCallBack1 {
public static void main(String[] args) {
Tools.check(64,new Mythink());
}
}
class Mythink implements MathTools{
@Override
public boolean isPrime(int n) {
for(int i =2;i<n;i++){
if(n%i==0){
return false;
}
}
return true;
}
}
接口:
package day19.t2;
public class Interface {
interface MathTools{
// 输入一个整数n 判断n是否为质数
public abstract boolean isPrime(int n);
}
}
工具类:
package day19.t2;
import day19.t2.Interface.MathTools;
public class Tools {
public static void check(int num,MathTools tool){
for(int i =2;i<num/2;i++){
int b=num-i;
if(tool.isPrime(i) && tool.isPrime(b)){
System.out.println(num+"="+i+"+"+b);
}
}
}
}