Java: Inputting text from a file using split
- by 00PS
I am inputting an adjacency list for a graph. There are three columns of data (vertex, destination, edge) separated by a single space. Here is my implementation so far:
FileStream in = new FileStream("input1.txt");
Scanner s = new Scanner(in);
String buffer;
String [] line = null;
while (s.hasNext())
{
buffer = s.nextLine();
line = buffer.split("\\s+");
g.add(line[0]);
System.out.println("Added vertex " + line[0] + ".");
g.addEdge(line[0], line[1], Integer.parseInt(line[2]));
System.out.println("Added edge from " + line[0] + " to " + line[1] + " with a weight of " + Integer.parseInt(line[2]) + ".");
}
System.out.println("Size of graph = " + g.size());
Here is the output:
Added vertex a.
Added edge from a to b with a weight of 9.
Exception in thread "main" java.lang.NullPointerException
at structure5.GraphListDirected.addEdge(GraphListDirected.java:93)
at Driver.main(Driver.java:28)
I was under the impression that
line = buffer.split("\\s+");
would return a 2 dimensional array of Strings to the variable line. It seemed to work the first time but not the second. Any thoughts?
I would also like some feedback on my implementation of this problem. Is there a better way?
Anything to help out a novice! :)