gpt4 book ai didi

java - 排序坐标系

转载 作者:行者123 更新时间:2023-11-30 01:50:11 24 4
gpt4 key购买 nike

我在两个单独的数组列表中输入 x 和 y,并将它们像 (x,y) 坐标系一样放在不同的数组列表中。然后尝试使用 Collections.sort(arraylist); 将新的数组列表从最小到最大排序。然而,当我输入两位数(例如(10,11))时,它会识别出小于(6, 7)的值

for(int x = 0; x <=5; x ++) {  
System.out.print("Enter X coordinate: ");
int playerturnColumn = playerinput.nextInt();
System.out.print("Enter Y Coordinate: ");
int playerturnRow = playerinput.nextInt();
playerturnCoordinate.add(playerturnColumn + "," + playerturnRow);
}
Collections.sort(playerturnCoordinate);
System.out.println(playerturnCoordinate);

轮到你了输入X坐标:10输入 Y 坐标:11输入X坐标:2输入 Y 坐标:1输入X坐标:3输入 Y 坐标:5输入X坐标:2输入 Y 坐标:8输入X坐标:0输入 Y 坐标:1输入 X 坐标:9输入 Y 坐标:7[0,1, 10,11, 2,1, 2,8, 3,5, 9,7]

最佳答案

您可以创建一个实现 ComparableCooperative 类:

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

class Coordinate implements Comparable<Coordinate> {
private final int x;
private final int y;

public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}

public int getX() {
return this.x;
}

public int getY() {
return this.y;
}

public String toString() {
return String.format("[%d, %d]", getX(), getY());
}

public double distanceFromOrigin(Coordinate c) {
return Math.sqrt(Math.pow(c.getX(), 2) + Math.pow(c.getY(), 2));
}

public int compareTo(Coordinate other) {
return Double.compare(distanceFromOrigin(this), distanceFromOrigin(other));
}
}

class Test {
public static void main(String[] args) {
List<Coordinate> playerTurnCoordinates = new ArrayList<>();
playerTurnCoordinates.add(new Coordinate(10, 11));
playerTurnCoordinates.add(new Coordinate(2, 1));
playerTurnCoordinates.add(new Coordinate(3, 5));
playerTurnCoordinates.add(new Coordinate(2, 8));
playerTurnCoordinates.add(new Coordinate(0, 1));
playerTurnCoordinates.add(new Coordinate(9, 7));
playerTurnCoordinates.add(new Coordinate(6, 7));
System.out.println("Before sorting: " + playerTurnCoordinates);
Collections.sort(playerTurnCoordinates);
System.out.println("After sorting: " + playerTurnCoordinates);
}
}

输出:

Before sorting: [[10, 11], [2, 1], [3, 5], [2, 8], [0, 1], [9, 7], [6, 7]]
After sorting: [[0, 1], [2, 1], [3, 5], [2, 8], [6, 7], [9, 7], [10, 11]]

关于java - 排序坐标系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56352367/

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