我在读取多组值时遇到问题,这些值将保存为x,y坐标,然后存储为节点。我用Java编写这个程序。文本文件中的某些输入行如下所示:
(220 616) (220 666) (251 670) (272 647) # Poly 1
(341 655) (359 667) (374 651) (366 577) # Poly 2
(311 530) (311 559) (339 578) (361 560) (361 528) (336 516) # Poly 3
我需要读取每个坐标并将它们存储为格式node(x,y)中的节点。完成此任务的最佳方法是什么?到目前为止,我正在使用扫描程序,在下一行时读取输入文件。我将行保存在字符串s中,并尝试解析它,就像这样
while (scanner.hasNextLine()) {
String s = nextLine();
//parse code goes here
//Currently this is what I have, but I think I'm going about it in a weird way
String newS = s.substring(s.indexOf("(" + 1, s.indexOf(")"));
String newX = newS.substring(0, newS.indexOf(" "));
String newY = newS.substring(newS.indexOf(" ") + 1);
int x = Integer.parseInt(newX);
int y = Integer.parseInt(newY);
}
我已经阅读了几个分隔符以上的帖子,但我仍然有点迷失。基本上我需要能够循环并将每个x,y坐标保存为我将存储在数组中的节点。
任何帮助都有帮助! 谢谢!
答案 0 :(得分:1)
一种可能的解决方案是使用字符串的.split()方法。假设您的所有行都以相同的方式格式化
String s ="(220 616) (220 666) (251 670) (272 647)";
String[] arr = s.split("\\)\\s*");
每次遇到一个右括号“\\)”时会生成一个新的数组条目,后跟一个任意长度的空格“\\ s *”
1:“(220 616”
2:“(220 666”
3:“(251 670”
4:“(272 647”
然后可能使用substring()来挑选你需要的数字,把它变成一个点,然后把它添加到一个点的arraylist。
例如
String s ="(220 616) (220 666) (251 670) (272 647)";
String[] arr = s.split("\\)\\s*");
List<Point> points = new ArrayList<Point>();
for (String anArr : arr){
int x = Integer.parseInt(anArr.substring(1,anArr.indexOf(" ")));
int y = Integer.parseInt(anArr.substring(anArr.indexOf(" ") + 1, anArr.length()));
Point p = new Point(x,y);
points.add(p);
System.out.println(p);
}
给出输出
java.awt.Point[x=220,y=616]
java.awt.Point[x=220,y=666]
java.awt.Point[x=251,y=670]
java.awt.Point[x=272,y=647]
答案 1 :(得分:1)
您可以使用正则表达式来隔离坐标
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
Pattern myPattern = Pattern.compile("[0-9][0-9][0-9] [0-9][0-9][0-9]");
Matcher myMatcher = myPattern.matcher(currentLine);
while (myMatcher.find()) {
String[] coordinatesSplit = myMatcher.group().split(" ");
int x = Integer.parseInt(coordinatesSplit[0]);
int y = Integer.parseInt(coordinatesSplit[1]);
}
}