我在将从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 +
'}';
}
}
}
您可以使用Tokenizer
(来自API)字符串标记器类允许应用程序将字符串分解为标记
阅读更多:http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html