我需要构造一个接收矩阵作为参数并打印其行的方法。例如,该方法将接收以下矩阵
int[][] matrix = {
{3, 1, 2, 7, 2, 5, 6, 2},
{2, 10, 20, 12, 13},
{3, 7, 12, 15, 18, 4},
{2, 11, 21, 12, 13}
};
它必须返回
Line 0 : 3 1 2 7 2 5 6 2
Line 1 : 2 10 20 12 13
Line 2 : 3 7 12 15 18 4
Line 3 : 2 11 21 12 13
以下是方法:
public static void displayLines(int[][] matrix){
for (int i = 0; i < matrix.length; ++i){
for (int j = 0; j < matrix[i].length; ++j){
System.out.print("Line nb " + i + " : " + matrix[i][j] + " ");
}
}
}
但它没有以我想要的方式打印。它打印得像那样,我试图弄清楚如何解决它。
Line 0 : 3
Line 0 : 1
Line 0 : 2
Line 0 : 7
Line 0 : 2
Line 0 : 5
Line 0 : 6
Line 0 : 2
// And so on for other lines
答案 0 :(得分:3)
您正在为数组的每个元素而不是数组的每一行调用System.out.print
。修改如下:
public static void displayLines(int[][] matrix){
for (int i = 0; i < matrix.length; ++i){
System.out.print("Line " + i + " :"); // line header
for (int j = 0; j < matrix[i].length; ++j){
System.out.print(" " + matrix[i][j]);
}
System.out.println(""); // end of line
}
}
注意如何在每个元素" " + matrix[i][j]
之前添加一个空格,以避免尾随空格。
另外请记住,您可以像这样编写第二个for循环
for (int n : matrix[i]) {
System.out.print(" " + n);
}
答案 1 :(得分:3)
如下:
int rowNumber = 0;
for (int[] row : matrix){
System.out.println("Line " + (rowNumber++) + " : " + Arrays.toString(row));
}
将生成
Line 0 : [3, 1, 2, 7, 2, 5, 6, 2]
Line 1 : [2, 10, 20, 12, 13]
Line 2 : [3, 7, 12, 15, 18, 4]
Line 3 : [2, 11, 21, 12, 13]
答案 2 :(得分:1)
使用以下代码
public static void displayLines(int[][] matrix){
for (int i = 0; i < matrix.length; ++i){
System.out.print("Line nb " + i + " : " );
for (int j = 0; j < matrix[i].length; ++j){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
答案 3 :(得分:1)
public static void displayLines(int[][] matrix) {
for (int i = 0; i < matrix.length; ++i) {
System.out.print("Line " + i + " : ");
for (int j = 0; j < matrix[i].length; ++j) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
答案 4 :(得分:0)
int[][] matrix = { { 3, 1, 2, 7, 2, 5, 6, 2 }, { 2, 10, 20, 12, 13 },
{ 3, 7, 12, 15, 18, 4 }, { 2, 11, 21, 12, 13 } };
for (int i = 0; i < matrix.length; ++i) {
System.out.print("Line " + i + " :");
for (int j = 0; j < matrix[i].length; ++j) {
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}