Reputation:
I am trying to accept a multidimensional matrix as input, such as
1 2 3
3 1 5
1 9 7
This is just an example, the one I'm using is a lot larger and different inputs may be different row lengths, row columns.
In my input, each row and column will be of equal length.
How do I go about storing the input as it appears, perhaps a two dimensional arraylist. I know that I will have to take the input as Strings and later parse them back into integers by Integer.parseInt(string)
and I know Scanner's method .split(" ")
splits an input by spaces, but how do i seperate lines so that the next row can be extracted.
Upvotes: 1
Views: 867
Reputation: 191701
Assuming you have a scanner that reads lines of input, here's one way
List<List<String>> matrix = new ArrayList<>();
while (sc.hasNextLine()) {
matrix.add(Arrays.asList(sc.nextLine().split(" "));
}
Of course, change datatypes as you want
You could also store a flat Arraylist. Using the width of the matrix, you can translate rows and columns into the index
matrix[row][col] == list.get(col + row*matrix.width);
Upvotes: 0
Reputation: 124646
Since you talk about splitting strings by spaces and parsing integers, it seems your input is matrix data as a string. You could first split to lines, then to columns, and parse to integers and collect in a 2D array or in a list of list.
String input = "1 2 3\n" +
"3 1 5\n" +
"1 9 7";
int[][] matrix = Arrays.stream(input.split("\n"))
.map(s -> Arrays.stream(s.split(" "))
.mapToInt(Integer::parseInt)
.toArray())
.toArray(int[][]::new);
List<List<Integer>> listOfLists = Arrays.stream(input.split("\n"))
.map(s -> Arrays.stream(s.split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList()))
.collect(Collectors.toList());
Here's the same thing in good old-fashioned iterative way, if it's easier to understand:
String[] lines = input.split("\n");
int[][] matrix = new int[lines.length][];
for (int i = 0; i < lines.length; i++) {
String[] columns = lines[i].split(" ");
matrix[i] = new int[columns.length];
for (int j = 0; j < columns.length; j++) {
matrix[i][j] = Integer.parseInt(columns[j]);
}
}
Upvotes: 2