排序坐标系

时间:2019-05-29 02:40:07

标签: java

我要在两个单独的数组列表中输入x和y,然后将它们像(x,y)坐标系放到另一个数组列表中。然后尝试使用Collections.sort(arraylist);将该新的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]

1 个答案:

答案 0 :(得分:2)

您可以创建实现Coordinate的{​​{1}}类:

Comparable

输出:

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);
  }
}