我能够编写一个打印2D数组的方法:
{a,b,c},
{d,e,f},
{g,h,i},
所以:
a db gec hf i
方法如下:
public static void d2(int[][] b){
for( int k = b.length - 1 ; k > 0; k-- ) {
for( int j = 0 ; j < b.length ; j++ ) {
int i = k - j;
if( i < b.length && j < b.length ) {
System.out.print(b[i][j] + " " );}
}
System.out.println();}
}
}
现在我想写一个方法,以对角线向负方向打印,它将是:
g dh aei bf c
我需要对原来的方法做什么改变才能使它以另一种对角线的方式打印出来?
谢谢
没有得到您提到的输出,而是得到了ArrayIndexOutOfBoundsException
。下面是同一个程序的修改版本,它给出了预期的输出:
int b[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// for (int i = (b.length * 2) - 1; i >= 0; i--) {
for (int i = 0; i < (b.length * 2); i++) {
for (int j = i, k = 0; j >= 0; j--, k++)
if (j < b.length && k < b.length)
System.out.print(b[j][k] + " ");
System.out.println();
}
要反转,只需取消/注释另一个i
循环。i
循环充当计数器或水平跟踪器(就像我们现在正在穿越的对角线一样)。因此,根据i
值,j
&k
初始化自己&沿对角线方向绕一圈。
由于方向相同&你只想要一个相反的顺序,它足以改变i
循环单独。所以,它不是从0th
到nth
的对角线,而是相反的;nth
到0th
对角线