text file with x y coordinates to empty Point2D[] array in Java

201 views Asked by At

I want to read a file in Java and put the numbers from the file into the (x,y) coordinates of a Point2D[] array. How would I go about doing this?

my file looks like:

5 4
6 2
4 1

which are points (5,4) (6,2) (4,1).

1

There are 1 answers

0
Sash Sinha On BEST ANSWER

Say you have a Point class that looks like something like this (you could also use the java.awt.geom.Point2D class but it is not advisable apparently) :

public class Point {
    private int x;
    private int y;

    public Point() {
        this(0, 0);
    }

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

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

    public void setX(int x) {
        this.x = x;
    }

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

    public void setY(int y) {
        this.y = y;
    }

    public double distance(Point p2) {
        int dx = this.x - p2.x;
        int dy = this.y - p2.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }
        if (!(other instanceof Point p2)) {
            return false;
        }
        return (this.x == p2.x) && (this.y == p2.y);
    }

    public String toString() {
        return String.format("Point(%d, %d)", this.x, this.y);
    }
}

And a file called points.txt that you want to parse with the following contents:

5 4
6 2
4 1

You could use a BufferedReader to read the file line by line:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        List<Point> pointsList = new ArrayList<>();
        String fileName = "points.txt";
        try (BufferedReader reader = Files.newBufferedReader(Path.of(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] coordinates = line.split(" ");
                pointsList.add(new Point(
                    Integer.parseInt(coordinates[0]),
                    Integer.parseInt(coordinates[1])));
            }
        }
        System.out.printf("pointsList: %s%n", pointsList);
        Point[] pointsArray = pointsList.toArray(Point[]::new);
        System.out.printf("pointsArray: %s%n", Arrays.toString(pointsArray));
    }
}

Output:

pointsList: [Point(5, 4), Point(6, 2), Point(4, 1)]
pointsArray: [Point(5, 4), Point(6, 2), Point(4, 1)]