我正在尝试读取包含图形邻接列表的文件。该文件如下所示:
1 2 3 5
2 4
3 1 5
4
5 2 4
每一行都是一个链表,其长度与其他行不同。到目前为止我尝试过这个:
private static List<ArrayList<String>> adj;
ArrayList<String> rows = new ArrayList<String>();
int i = 0;
try {
Scanner input = new Scanner(new BufferedReader(new FileReader(fileName)));
//BufferedReader input = new BufferedReader(new FileReader(fileName));
String line;
while (input.hasNextLine()){
i++;
String[] cols = input.nextLine().trim().split(" ");
for (String c : cols){
rows.add(c);
}
adj.add(rows);
}
//print the matrix
for (List<String> list : adj) {
for (String str : list) {
System.out.print(str + " ");
}
System.out.println();
}
}
catch (IOException e){
System.out.println("Error reading input file!");
}
但它不起作用,因为当我尝试打印整个矩阵时它显示错误(NullPointerException)。我怎样才能正确读取这个文件?
最佳答案
已编辑 我复制了您的代码,对列表进行了初始化,添加了 try/catch 并添加了打印代码,这工作正常:
List<ArrayList<String>> adj = new ArrayList<>();
int i = 0;
Scanner input = null;
try {
input = new Scanner(new BufferedReader(new FileReader(fileName)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line;
while (input.hasNextLine()) {
ArrayList<String> rows = new ArrayList<String>();
i++;
String[] cols = input.nextLine().trim().split(" ");
for (String c : cols) {
rows.add(c);
}
adj.add(rows);
}
for (ArrayList<String> list : adj) {
for (String s : list) {
System.out.print(s + " ");
}
System.out.println();
}
关于java - 如何从文件中读取ArrayLists列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53232390/