我无法将从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);
}
}
答案 0 :(得分:2)
我认为你可以尝试这样的事情。但算法不是很有效。
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 +
'}';
}
}
}
答案 1 :(得分:0)
你可以使用Tokenizer
(来自API)字符串tokenizer类允许应用程序将字符串分解为标记
了解详情:http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html