Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- class Point {
- private double x;
- private double y;
- public Point(double x, double y){
- setX(x);
- setY(y);
- }
- public void setX(double x){
- this.x = x;
- }
- public void setY(double y){
- this.y = y;
- }
- public double getX(){
- return this.x;
- }
- public double getY(){
- return this.y;
- }
- public double getDistance(){
- return Math.sqrt(x*x + y*y);
- }
- public String toString(){
- return "" + this.x + " " + this.y;
- }
- }
- class PointList {
- private ArrayList<Point> pList = new ArrayList<>();
- public PointList(File file) throws FileNotFoundException {
- Scanner sc = new Scanner(file);
- while(sc.hasNextLine()){
- double x = Double.parseDouble(sc.nextLine());
- double y = Double.parseDouble(sc.nextLine());
- Point point = new Point(x, y);
- pList.add(point);
- }
- sc.close();
- }
- public void print(){
- for(int i = 0; i < pList.size(); ++i){
- Point p = pList.get(i);
- double d = p.getDistance();
- System.out.println(p + " d=" + d);
- }
- System.out.println();
- }
- public void sort(){
- Collections.sort(pList, new Comparator<Point>(){
- public int compare(Point p1, Point p2){
- return Double.compare(p1.getDistance(), p2.getDistance());
- }
- }
- );
- }
- public void sort(Comparator<Point> cmp){
- Collections.sort(pList, cmp);
- }
- }
- class MyComparator implements Comparator<Point> {
- public int compare(Point p1, Point p2){
- int xCmp = Double.compare(p1.getX(), p2.getX());
- int yCmp = Double.compare(p1.getY(), p2.getY());
- return (xCmp != 0) ? xCmp : yCmp;
- }
- }
- public class Sandbox {
- public static void main(String[] args) {
- try {
- PointList pList = new PointList(new File("points.txt"));
- pList.sort();
- pList.print();
- Comparator<Point> cmpX = new Comparator<Point>(){
- public int compare(Point p1, Point p2){
- return Double.compare(p1.getX(), p2.getX());
- }
- };
- pList.sort(cmpX);
- pList.print();
- pList.sort(new Comparator<Point>(){
- public int compare(Point p1, Point p2){
- return Double.compare(p1.getY(), p2.getY());
- }
- }
- );
- pList.print();
- pList.sort(new MyComparator());
- pList.print();
- } catch(Exception e){
- e.printStackTrace();
- System.out.println("Unexpected error, sorry!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement