我希望程序打印如下:
矩阵元素:
2
4 6
8 10 12
14 16
18
但是我被卡住了。这是我的代码:
int[][] matrix = new int [5][];
matrix[0] = new int[1];
matrix[1] = new int[2];
matrix[2] = new int[3];
matrix[3] = new int[2];
matrix[4] = new int[1];
System.out.println("\n\n Matrix elements: ");
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println("\t");
}
程序只打印如下:
矩阵元素:
0
0 0
0 0 0
0 0
0
感谢您的帮助!
答案 0 :(得分:3)
它不会工作,因为你忘记了第二项任务。你的代码只是说:&#34;嘿Java,我需要一个二维数组,它应该有5行&#34;,然后你添加&#34;啊,第1行应该有一列,第2行两列,......&#34;但是你并没有考虑你想拥有的价值观。
以下是您可以做的事情:
int[][] matrix = new int [5][];
// one by one assignment
matrix[0] = new int[1];
matrix[0][0] = 0;
matrix[1] = new int[2];
matrix[1][0] = 2;
matrix[1][1] = 4;
//...
或者:
int[][] matrix = new int [5][];
// This way you just say what you want to have inside the array and java will
// evaluate the size needed
matrix[0] = new int[]{ 0 };
matrix[1] = new int[]{ 2, 4 };
//...
或者:
// like the previous one, but in a two dimensional way.
int[][] matrix = new int[][] {
{ 0 },
{ 4, 6 },
{ 8, 10, 12 },
{ 14, 16 },
{ 18 }
};
这些方法会产生相同的结果,但我强烈建议使用第三种方法,因为它提高了可读性。
答案 1 :(得分:1)
首先,您必须为每个数组元素赋值。如下面的代码所述。
int temp=0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
temp=temp+2;
matrix[i][j] = temp;
}
}
for(int k = 0; k < matrix.length; k++) {
for(int l = 0; l < matrix[k].length; l++) {
System.out.print(matrix[k][l] + " ");
}
System.out.println("\t");
}
希望这会对你有所帮助。
答案 2 :(得分:-1)
为元素赋值。您打印0值因为int [i] [j]为0。
int [][] matrix = new int[5][];
matrix[0] = new int[1];
matrix[1] = new int[2];
matrix[2] = new int[3];
matrix[3] = new int[2];
matrix[4] = new int[1];
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
matrix[i][j]= j+i+2;
}
}
System.out.println("\n\n Matrix elements: ");
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println("\t");
}
或......
int [][] matrix = new int[5][];
matrix[0] = new int[1];
matrix[1] = new int[2];
matrix[2] = new int[3];
matrix[3] = new int[2];
matrix[4] = new int[1];
System.out.println("\n\n Matrix elements: ");
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
System.out.print(i+j+2 + " ");
}
System.out.println("\t");
}