如何从Java中读取格式化的图形数据文件
我正在读取adj矩阵的图形数据,其格式如下:如何从Java中读取格式化的图形数据文件,java,input,graph,format,Java,Input,Graph,Format,我正在读取adj矩阵的图形数据,其格式如下: 0 176 67 665 185 1129 26 1414 114 1748 205 1 140 248 591 175 1920 68 2229 31 2 778 476 825 447 888 258 1179 .... 单个数字线是起始顶点,后面是具有边长度的结束顶点线 0-起始顶点 176
0
176 67
665 185
1129 26
1414 114
1748 205
1
140 248
591 175
1920 68
2229 31
2
778 476
825 447
888 258
1179 ....
单个数字线是起始顶点,后面是具有边长度的结束顶点线
0-起始顶点
176-结束顶点
67-边缘长度
665-结束顶点
185-边缘长度
等等
这就是我尝试过的:
public void ValueAssign()
throws IOException {
Scanner inFile = new Scanner(new File("list1.txt"));
String s = inFile.nextLine();
int NofV = Integer.parseInt(s); // number of vertices
int NofE = Integer.parseInt(s); // number of edges
int v1,v2, edge; // v1 - vertex 1, v2 - vertex 2
while ((s = inFile.nextLine()) != null) {
Scanner in = new Scanner(s);
in.useDelimiter(" ");
v2 = in.nextInt();
edge = in.nextInt();
}
}
如何读取它?请尝试此代码
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new File("list1.txt"));
int startingVertex, endingVertex, edgeLength;
while (inFile.hasNextLine()) {
String trimmedLine = inFile.nextLine().trim();
//Skip empty lines
if(trimmedLine.isEmpty()){
continue;
}
String values[] = trimmedLine.split("\\s+");
if(values.length > 1){
endingVertex = Integer.parseInt(values[0]);
edgeLength = Integer.parseInt(values[1]);
//Do necessary operations
}else if(values.length > 0){
startingVertex = Integer.parseInt(values[0]);
//Do necessary operations
}
}
}
到目前为止,您尝试过什么?我尝试过使用scanner和split(),但我不知道代码应该是什么样子。请发布您的代码。@BlackPearl发布,我不知道如何区分带有一个或两个数字的行<代码>while在另一个
while
中?您可以拆分行并检查拆分数组是否有多个元素。欢迎使用堆栈溢出。请注意,在这里说“谢谢”的首选方式是投票选出好的问题和有用的答案(一旦你有足够的声誉这么做),并接受对你提出的任何问题最有用的答案(这也会给你的声誉带来一点提升)。