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.屬性);
}
}
當然,也可采用存入資料庫的方式,在資料庫里實作排序,這里不做詳細介紹,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/355700.html
標籤:其他
下一篇:mybatis的配置優化
