java中不等长二维数组的遍历输出 (四种方法)

题目:现有一个不等长的二维数组;其元素值为:

 1  3  5  7  9

 2  4  6  8

0  6

请写出一个java主类,功能为:初始化数据,并遍历输出各行元素的值。

代码如下:

一、第一种

public class Arr{
     public static void main(String args[]) {
    	 int a[][]= {{1,3,5,7,9},{2,4,6,8},{0,6}};
    	 for(int i=0,j=0;i<a.length;)
    	 {
    		 System.out.print(a[i][j]+"  ");
    		 j++;
    		 if(j>=a[i].length) {
    			 System.out.println('\t');
    			 i++;
    			 j=0;
    		 }
    	 }
     }
}

二、第二种 

public class Arr {
	public static void main(String args[]) {
		int a[][]= {{1,3,5,7,9},{2,4,6,8},{0,6}};
		System.out.println(a[0][0]+" "+a[0][1]+" "+a[0][2]+" "+a[0][3]+" "+a[0][4]);
		System.out.println(a[1][0]+" "+a[1][1]+" "+a[1][2]+" "+a[1][3]); 
		System.out.println(a[2][0]+" "+a[2][1]);
	}
}

三、第三种

public class Arr{
	   public static void main(String args[]) {
	   int a[][] = {{1,3,5,7,9},{2,4,6,8},{0,6}};
	   int i,j;
	   for(i=0;i<a.length;i++)
	   {
		   for(j=0;j<a[i].length;j++)
		     System.out.print(a[i][j]+"  ");   
		   if(j>=a[i].length)
			   System.out.println('\t');
	   }
   }
}

 

四、第四种

使用foreach进行遍历(在java中速度快,使用频率高)

public class Arr {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[][]= {{1,3,5,7,9},{2,4,6,8},{0,6}};
		for(int []i:a) {
			for(int j:i)
			System.out.print(j+" ");
			System.out.println();
		}
	}
}

 

 

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值