第十六天,java之斜着遍历二维数组

package rectangle;

class Test0 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[][] rectangle = {
				{1,2,3,4,5},
				{1,2,3,4,5},
				{1,2,3,4,5},
				{1,2,3,4,5},
				{1,2,3,4,5},
				{1,2,3,4,5},
				{1,2,3,4,5},
		};
		
		printRectangle(rectangle);
	}
	
	public static void printRectangle(int[][] a) {
		
		int j = 0;
		
		for(int num = 0 ;num < a.length+a[0].length-1;num++) {
			
			for(int i = 0;i < a.length ;i++) {
				
				j = num - i;
				
				if((j >= 0) && (j < a[0].length)) {
					
					System.out.print(a[i][j]);
				}
			}
			
			System.out.println();
		}
	}

}

num是遍历的次数,i是二维数组的长度,j是二维数组中每个小数组的长度(这里默认的是小数组的长度都相等)。

这其实是一个有意思的规律,大家可以自行列出所有a[i][j],就会发现这个规律了,哈哈哈。

猜你喜欢

转载自blog.csdn.net/qq_38006520/article/details/81155545