I'm trying to read a file which contains adjacency list of a graph. The file looks like this:
1 2 3 5
2 4
3 1 5
4
5 2 4
Each line is a linked list with some length different than other lines. So far I tried this:
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!");
}
but it doesn't work, because it shows an error (NullPointerException) when I try to print the whole matrix. How can I read this file properly?
rows = new ArrayList<String>();afteradj.add(rows);private static List<ArrayList<String>> adj;withprivate static List<ArrayList<String>> adj = new ArrayList<>();