Reputation: 1
I can't put numbers taken froma text file inside a matrix.
The text file is this:
4
0 24 12 52
24 0 16 23
12 16 0 18
52 23 18 0
I tried this:
public class Siti {
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("C://Users//dbruschi//Java-projects//NodiTelefonici//nodi.txt"));
String line = null;
ArrayList<Integer> numbers = new ArrayList<>();
while ((line = reader.readLine()) != null) {
StringTokenizer token = new StringTokenizer(line);
while (token.hasMoreTokens()) {
int num = Integer.parseInt(token.nextToken());
numbers.add(num);
}
}
System.out.println(numbers);
int dimension = numbers.get(0);
System.out.println("The dimension is: " + dimension);
ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
for(int j = 0; j < dimension; j++) {
ArrayList<Integer> matrixRow = new ArrayList<Integer>();
for (int i = 1; i < dimension+1; i++) {
int elem = numbers.get(i);
matrixRow.add(elem);
}
matrix.add(matrixRow);
}
System.out.println(matrix);
}
}
And of course the output is this:
[[0, 24, 12, 52], [0, 24, 12, 52], [0, 24, 12, 52], [0, 24, 12, 52]]
I tried without arraylist but I want to manage rows and columns and so i think that arraylist is the best way
Upvotes: 0
Views: 48