您可以尝试先用分号分割输入以获得矩阵的行,然后用逗号分割每一行以获得一行的单个值。
以下示例正是这样做的:
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);
}
}
打印矩阵的方法将int[][]
输入作为输入,如下所示:
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("—————————————");
}
}
执行此代码并1,1,1,1;2,2,2,2;3,3,3,3;4,4,4,4
在输出中输入值
1 | 1 | 1 | 1
—————————————
2 | 2 | 2 | 2
—————————————
3 | 3 | 3 | 3
—————————————
4 | 4 | 4 | 4