[英]Vertical 5x5 2D Array in Java
I want to print an output that looks like this: 我想打印如下输出:
0 5 10 15 20
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
But it just keeps coming out like this: 但是它一直这样出来:
0 0 0 0 0
1 6 0 0 0
2 7 12 0 0
3 8 13 18 0
4 9 14 19 24
This is what I've done so far: 到目前为止,这是我所做的:
public static void main(String[] args) {
int [][]matrix = new int[5][5];
fillSequentialMatrix2D(matrix);
}
public static void fillSequentialMatrix2D(int [][]matrix) {
for(int j=0, k=0; j<matrix[0].length ;j++){
for(int i=0; i<matrix.length ;i++){
matrix[i][j] = k++;
System.out.print("\t"+matrix[j][i]);
}
System.out.println("");
}
}
How do I make it print correctly? 如何正确打印?
As the above comment mentioned you need to remove the output from the loop. 正如上面提到的注释,您需要从循环中删除输出。
public static void fillSequentialMatrix2D(int [][]matrix) {
for(int j=0, k=0; j<matrix.length ;j++){
for(int i=0; i<matrix.length ;i++){
matrix[i][j] = k++;
//System.out.print("\t" + matrix[j][i]);
}
// System.out.println();
}
for(int j = 0; j < matrix.length; j++)
{
for(int i = 0; i < matrix.length; i++)
System.out.print("\t" + matrix[j][i]);
System.out.println();
}
}
Sample output from above. 从上面输出样本。
0 5 10 15 20
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.