gpt4 book ai didi

java - 如何对类型为 "NameOfClass"的数组进行排序

转载 作者:行者123 更新时间:2023-12-01 08:53:14 25 4
gpt4 key购买 nike

我有一个程序可以找到一对点之间的最大距离:这是类点:

public class Point {

private int x;
private int y;
public Point (int a, int b) {
x=a; y=b;
}
public double distance (Point p){
int tempx , tempy;
tempx=(x-p.x)*(x-p.x);
tempy=(y-p.y)*(y-p.y);
return Math.sqrt(tempx+tempy);
}
public void show(){
System.out.println("(" + x + "," + y + ")");
}
}

这是主程序:

public static void main(String[] args) {
// TODO Auto-generated method stub
Point[] allPoints=new Point[5];
int k=0;
int rx,ry;
while (k<=allPoints.length-1){
rx=(int)(1+Math.random()*10);
ry=(int)(1+Math.random()*10);
allPoints[k]=new Point(rx, ry);
k++;
}

int i,j,mi,mj;
double mDis=0,cDis;
mi=mj=0;
i=0;
while ( i<allPoints.length-1) {
j=i+1;
while (j<allPoints.length) {
cDis= allPoints[i].distance(allPoints[j]);
if (cDis>mDis){
mDis=cDis;
mj=j;
mi=i;}
j++;
}
i++;
}

allPoints[mj].show();
allPoints[mi].show();
System.out.print("max dis is " + mDis +" first point: " + mi + " second point: " + mj);
}
//////////


}

正如您所看到的,程序有一个包含 5 个“单元格”的数组,并且它找到了最大距离的对,我想知道如何更改程序,以便它根据距离对点进行排序和打印它们之间。例如: 点 1:2,2 点 2:6,6 点 3:1,1所以Point3和Point 1之间的距离最小所以程序应该输出:1,1 2,2 6,66,6 之所以排在最后,是因为 6,6 和 2,2 之间的距离最大,我是 Java 新手,所以如果您能向我解释一下,这将是一个很大的帮助。

最佳答案

创建一个消耗一对点的新 Line 对象。将所有点组合放入​​线列表中,并根据这些线的长度(点之间的距离)对该列表进行排序。

public static void main(String[] args) {
...
List<Line> lines = new ArrayList<>();
while (i < allPoints.length - 1) {
...
while (j < allPoints.length) {
lines.add(new Line(allPoints[i], allPoints[j]));
...
}
...
}
...
Collections.sort(lines, Comparator.comparingDouble(Line::getLength));
System.out.println("Lines: ");
for (Line line : lines) {
System.out.println(line);
}
}

class Point {
private int x;
private int y;

public Point (int a, int b) {
x=a; y=b;
}

public double distance (Point p){
int tempx , tempy;
tempx=(x-p.x)*(x-p.x);
tempy=(y-p.y)*(y-p.y);
return Math.sqrt(tempx+tempy);
}

public void show(){
System.out.println(this);
}

@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}

class Line {
private final Point a;
private final Point b;
private double length;

public Line(Point a, Point b) {
this.a = a;
this.b = b;
this.length = a.distance(b);
}

public double getLength() {
return length;
}

@Override
public String toString() {
return "Line{" +
"a=" + a +
", b=" + b +
", length=" + length +
'}';
}
}

关于java - 如何对类型为 "NameOfClass"的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42233486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com