1.首先创建一个复数类,具有实部和虚部两个成员变量,获得信息的方法,以及复数的模长。
public class ComplexNumber {
double real;
double image;
public ComplexNumber() { }
public ComplexNumber(double real,double image) {
// TODO Auto-generated constructor stub
this.real = real;
this.image = image;
}
String getinfo() {
String s;
s = real + "+" + image + "i";
return s;
}
public double length() {
return this.real*this.real + this.image*this.image;
}
}
2.在测试类中创建动态对象数组,并实现按对象属性(模长)排序。
public class Test {
public static void main(String[] args) {
int n;
Scanner in = new Scanner(System.in);
ArrayList<ComplexNumber> myList = new ArrayList<>();
System.out.println("test2-请输入要输入的复数个数:");
n = in.nextInt();
System.out.println("请输入复数:");
System.out.println("(格式为实部 虚部)");
for(int i = 0; i < n; i++) {
myList.add(new ComplexNumber(in.nextDouble(), in.nextDouble()));
}
Collections.sort(myList,new Comparator<ComplexNumber>() {
@Override
public int compare(ComplexNumber one, ComplexNumber other) {
return Double.compare(one.length(), other.length());
}
});
System.out.println("after sort:");
for(int i = 0; i < myList.size(); i++)
System.out.println(myList.get(i).getinfo());
}
}
Collections.sort(列表名,匿名对象Comparator);
new Comparator<要实现排序的类>() {
@Override
public int compare(类名 one, 类名 other) {
return Double.compare(one.属性, other.属性);
}
}
当然,也可采用存入数据库的方式,在数据库里实现排序,这里不做详细介绍。