You can try something like splitting the input by semicolon first in order to get the rows of the matrix and then split each row by comma in order to get the single values of a row.
The following example does exactly that:
public static void main(String[] args) {
System.out.println("Please enter the matrix values");
System.out.println("(values of a row delimited by comma, rows delimited by semicolon, example: 1,2;3,4 for a 2x2 matrix):\n");
// fire up a scanner and read the next line
try (Scanner sc = new Scanner(System.in)) {
String line = sc.nextLine();
// split the input by semicolon first in order to have the rows separated from each other
String[] rows = line.split(";");
// split the first row in order to get the amount of values for this row (and assume, the remaining rows have this size, too
int columnCount = rows[0].split(",").length;
// create the data structre for the result
int[][] result = new int[rows.length][columnCount];
// then go through all the rows
for (int r = 0; r < rows.length; r++) {
// split them by comma
String[] columns = rows[r].split(",");
// then iterate the column values,
for (int c = 0; c < columns.length; c++) {
// parse them to int, remove all whitespaces and put them into the result
result[r][c] = Integer.parseInt(columns[c].trim());
}
}
// then print the result using a separate static method
print(result);
}
}
The method that prints the matrix takes an int[][]
as input and looks like this:
public static void print(int[][] arr) {
for (int r = 0; r < arr.length; r++) {
int[] row = arr[r];
for (int v = 0; v < row.length; v++) {
if (v < row.length - 1)
System.out.print(row[v] + " | ");
else
System.out.print(row[v]);
}
System.out.println();
if (r < arr.length - 1)
System.out.println("—————————————");
}
}
Executing this code and inputting the values 1,1,1,1;2,2,2,2;3,3,3,3;4,4,4,4
results in the output
1 | 1 | 1 | 1
—————————————
2 | 2 | 2 | 2
—————————————
3 | 3 | 3 | 3
—————————————
4 | 4 | 4 | 4