java - 如何从文件中读取 ArrayLists 列表?
问题描述
我正在尝试读取包含图形邻接列表的文件。该文件如下所示:
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();
}
推荐阅读
- python - 如何过滤元组列表(或列表列表)以删除= 0的所有值?
- javascript - 如何从对象中删除数组?
- sql - Oracle:从列中选择总和作为两者:YTD(年初至今),Fiscal YTD
- angular - 以角度在许多组件中共享功能的最佳解决方案
- vue.js - Heroku 在部署 MEVN 应用程序时出现构建错误,为什么 heroku 显示 babel-loader 和 vue-loader 错误?
- r - 如何在 R 中测试预测变量的所有子集
- r - httr 有时会在 URL 中将“%”替换为“%25”
- python - algorithm - 通过特定顶点的路径查找
- javascript - 如何在 django forms.DateInput 值中获取更新的当前日期
- python - 将 numpy 记录保存和加载为多部分文件