gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:55:20 25 4
gpt4 key购买 nike

我无法将从 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/

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