java - 分割坐标从文件 Java 中读入

标签 java string file

我无法将从 txt 文件读取的一行分成两点。该文件具有如下坐标列表:

(0, 0) (1, 2)
(0, 1) (-3, 4)
....

我想做的是将它们分成两个单独的点,以便我可以计算它们之间的距离。我遇到的问题是将它们分成几个点,然后我认为我的一切都是正确的。任何帮助将不胜感激。

这是我的代码:

public static void main(String[] args) {

    File file = new File(args[0]);
    BufferedReader br;
    try {
        br = new BufferedReader(new FileReader(file));
        String line;
        String point1, point2;
        int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
        while((line = br.readLine()) != null) {
            point1 = line.substring(0, line.indexOf(")"));
            point2 = line.substring(line.indexOf(")"), line.length());

            x1 = Integer.parseInt(point1.substring(1, point1.indexOf(",")));
            y1 = Integer.parseInt(point1.substring(point1.indexOf(",") + 2, point1.length() - 1));

            x2 = Integer.parseInt(point2.substring(2, point2.indexOf(",")));
            y2 = Integer.parseInt(point1.substring(point2.indexOf(",") + 2, point2.length() - 1));

            double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
            System.out.println((int)distance);
        }
        System.exit(0);
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }

}

最佳答案

我想你可以尝试这样的事情。虽然算法不是很有效。

public class Main {
public static void main(String[] args) {
    String s = "(0, 0) (1, 2)";
    String[] rawCoords = s.split("\\) \\(");
    Point p1 = parsePoint(rawCoords[0]);
    Point p2 = parsePoint(rawCoords[1]);
    System.out.println(p1.distance(p2));

}

private static Point parsePoint(String s) {
    //remove all brackets and white spaces and split by comma
    String[] rawXY = s.replaceAll("[\\)\\(\\s]", "").split(",");
    return new Point(Integer.parseInt(rawXY[0]), Integer.parseInt(rawXY[1]));
}

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

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

    public double distance(Point another) {
        return Math.sqrt(Math.pow(x - another.x, 2) + Math.pow(y - another.y, 2));
    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

}

关于java - 分割坐标从文件 Java 中读入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23154391/

相关文章:

java - 如何在 java swing 库中浏览文件?

java - jsp 表单的字段验证

java - 从 java netbeans 使用 Runtime.getRuntime().exec 时没有结果

c# - Java 字 rune 字到 C# 字 rune 字

java - 使用文件中的字符串的建议

python - 在 Python 中随机化字符串列表的最佳方法

java - 从控制台写入文本文件,文件数据未保存

JavaFX,外部类扩展 Pane ,将其添加到主类将不起作用

string - 如何从字符串中获取单个 Unicode 字符

Javascript 文件验证总是返回 false