Reputation: 433
Can anybody please help me with reading a graph data from a file and save the data into a java 2D array or List? I have been struggling
Here is the code I have so far:
Scanner matrix = new Scanner(new File("graph_input.txt"));
String[][] arr = new String[8][];
while(matrix.hasNextLine()){
String[] data = matrix.nextLine().split("\\s+");
for (int i = 0; i < arr.length; i++){
for (int j = 0; j < arr[i].length; j++){
arr[i][j] = Arrays.toString(arr[j]);
}
}
}
Thank you very much for any help you can provide.
Upvotes: 1
Views: 541
Reputation: 1772
You have a while
and 2 for
s. You need only one for
Scanner matrix = new Scanner(new File("graph_input.txt"));
// Base on this you have 8 line in the matrix
String[][] arr = new String[8][];
// Read all 8 lines
for (int i = 0; i < arr.length; i++) {
// Get the elements of line i
arr[i] = matrix.nextLine().split("\\s+");;
}
Upvotes: 2
Reputation: 658
Try the below code:
Scanner matrix = new Scanner(new File("graph_input.txt"));
ArrayList<ArrayList<String>> matrixArray = new ArrayList<ArrayList<String>>();
while(matrix.hasNextLine()){
String[] data = matrix.nextLine().split("\\s+");
ArrayList<String> innerList = new ArrayList<String>();
innerList.add(data[0]);
innerList.add(data[1]);
matrixArray.add(innerList);
}
System.out.println(matrixArray);
Upvotes: 1