问题条件: 程序接收一个整数N作为输入,后跟N对值x,y——当前点的坐标。有必要通过增加与原点的距离来排列所有点,并以以下格式在屏幕上显示点的排序列表:(1; 2) (2: 7) ...
样本输入 1:
5
12
3 7
-2 3
十一
3 5
样本输出 1:
(十一)
(12)
(-2; 3)
(3; 5)
(3; 7)
有一个公式可以确定点到原点的距离:(x^2 + y^2) 的平方根。似乎(但不完全是),我在代码中正确地重现了公式本身,但排序并没有按预期进行。最重要的是,我不明白排序是如何发生的。网上有很多关于 lambda 和比较器的文章,但例子都是一些简单的,而且一般都是关于其他的。因此,如果可能的话,我真的很想用我的例子来“咀嚼”使用 lambda 表达式进行排序的机制。这是我的代码:
public class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + "; " + y + ")";
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ArrayList <Integer> list = new ArrayList<>();
ArrayList <Point> points = new ArrayList<>();
int count = 0;
while (count != n * 2){
list.add(in.nextInt());
count++;
}
count = 0;
int count2 = 0;
while (count != n){
points.add(new Point(list.get(count2),list.get(count2 + 1)));
count ++;
count2 += 2;
}
Collections.sort(points, (o1, o2) -> (int) Math.sqrt((o1.x)^2 + (o1.y)^2));
for (Point p:points) {
System.out.println(p);
}
正如我所看到的:o1 是第一个对象,o2 是第二个对象,应该将它们进行比较。好的,我有一个包含五个对象的数组( (1 2) - 第一个,(3 7) - 第二个等)但是我需要在数组的对象之间执行计算(根据公式),它原来,但在 x 和 y 之间,即 在一个对象的参数之间......如果是这样,为什么我需要在表达式的参数中使用两个对象(o1和o2)。而且我不确定 o1.x 是否为 x(1, 3, -2, 1, 3) 而 o1.y 是否为 y(2, 7, 3, 1, 5)。总的来说,正如你所看到的,我在这里什么都不懂,我完全糊涂了。
1 个回答