我试图弄清楚如何从文件中读取有关旅行商问题的一些数据。我已经包含了文件的前几行(其余13503行的格式相同,因此我将其删除了)。该文件如下所示:
NAME : usa12
COMMENT : Cities with population at least 500 in
TYPE : TSP
DIMENSION : 13509
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 245552.778 817827.778
2 247133.333 810905.556
3 247205.556 810188.889
4 249238.889 806280.556
5 250111.111 805152.778
6 254475.000 804794.444
我对两件事感兴趣。尺寸值和城市坐标。显示了编号为
1,..,6
的城市(但其中有13509个城市),它们的x
和y
坐标均相邻。例如。城市4具有x=249238.889
和y=806280.556
。基本上,我想读取我的文件并像这样存储数据:
int dimension = read dimension of 13509
Coordinate[] xy = create coordinates array, with coordinates of each city
coordinate
对象的定义如下:public class Coordinate {
double x;
double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
}
我想我需要使用缓冲读取器,一些IO异常和字符串标记器。我对此并不陌生,所以我不确定如何实现它。我不知道如何具体读取尺寸值以及x和y坐标。有没有人建议一些实现?
最佳答案
因此,这是一个基本示例。如有更改,将进行更新。
import java.util.*;
import java.io.*;
class SO{
public static void main(String...a)throws Exception{
System.out.println("Start");
//Read thing
File f = new File("so_data.txt");
Scanner s = new Scanner(f);
int counts = 0;
s.nextLine();//skip 1
s.nextLine();//skip 2
s.nextLine();//skip 3
counts = Integer.parseInt(s.nextLine().split(" ")[2]);//use 4th
s.nextLine();//skip 5
s.nextLine();//skip 6
System.out.println(counts+" : counts");
counts = 6;//DUMMY DATA FOR TEST FILE - REMOVE FOR ACTUAL FILE
Coordinate[] xy = new Coordinate[counts];
int i = 0;
while(i<counts){ // picking exactly the required number of items.
String line = s.nextLine();
String[] vals = line.split(" ");
double x = Double.parseDouble(vals[1]);
double y = Double.parseDouble(vals[2]);
Coordinate c = new Coordinate(x,y);
// System.out.println(c);
xy[i++] = c;
}
for( i = 0;i<xy.length;i++)
System.out.println("for index "+i+") "+xy[i]);
}
}
class Coordinate {
double x;
double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
public String toString(){
return "Coord:: "+x+" , "+y;
}
}
so_data.txt
NAME : usa12
COMMENT : Cities with population at least 500 in
TYPE : TSP
DIMENSION : 13509
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 245552.778 817827.778
2 247133.333 810905.556
3 247205.556 810188.889
4 249238.889 806280.556
5 250111.111 805152.778
6 254475.000 804794.444