0

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?

8
  • You need to add rows = new ArrayList<String>(); after adj.add(rows); Commented Nov 9, 2018 at 19:55
  • @Ivan I tried that. But there was no change. Still can't print the whole matrix. Commented Nov 9, 2018 at 20:06
  • Then please add code that you use to print. And also exception stack trace. Commented Nov 9, 2018 at 20:09
  • 1
    The problem is that you need to initialize "adj". Commented Nov 9, 2018 at 20:15
  • 2
    As @paulsm4 said replace private static List<ArrayList<String>> adj; with private static List<ArrayList<String>> adj = new ArrayList<>(); Commented Nov 9, 2018 at 20:16

3 Answers 3

1

Edited I reproduced your code, made the initializtion of the list, added try/catch and added the printing code and this is working fine:

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You really should use methods from the "new" Java NIO (introduced in Java 7) together with streams (introduced in Java 8) for this:

public void readLinesExample(String fileName) throws IOException {
  List<List<String>> adj = Files.readAllLines(Paths.get(fileName)).stream()
      .map(row -> row.split(" "))
      .map(Arrays::asList)
      .collect(toList());

  System.out.println(adj.stream().flatMap(Collection::stream).collect(joining(" ")));
}

These few lines does all the job, wrapped in a main() method.

It is pretty straightforward:

  • First read all the lines, which returns a list. Create a stream from the rows of the file. This call throws the IOException so you might want to wrap this in an example if you truly want to handle the exception by printing to standard out.
  • The second line splits each row to an array.
  • The third line, map(Arrays::asList) creates a List from each array.
  • Finally the lists are collected to a list of lists.

The print part is equally simple. It streams over the list of lists, and uses flat map to "flatten" the sub lists to one stream. It then joins the elements to a string, separated by " ", and prints it.

This is much less error prone than your original code, you can hardly do wrong. Of course, it differs in some minor ways, like toList() not guaranteeing that you get an ArrayList, but that is rarely important.

Comments

1

In another approach using Java 8, you can simplify your code and write something like this to read the file containing your adjacency list of a graph or any similar data.

public static void printGraph() throws Exception {
    List<String> numberList = Files.readAllLines(Paths.get("graph.txt")); // reads all lines in one shot into a List<String>

    List<List<Integer>> listOfIntegerList = new ArrayList<List<Integer>>();

    for (String s : numberList) { // for each line containing numbers, stores them into a List<Integer>
        listOfIntegerList.add(Arrays.stream(s.split("\\s+")).map(Integer::parseInt).collect(Collectors.toList()));
    }

    System.out.println(listOfIntegerList);
}

This gives following output as per the data present in your file,

[[1, 2, 3, 5], [2, 4], [3, 1, 5], [4], [5, 2, 4]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.