2017/12/30Java基础学习——增强型for嵌套遍历在二维数组中的应用

下面主要探究如何在二维数组中使用增强型for嵌套。

[Q]定义一个5X5的二维数组。 然后使用随机数填充该二维数组。找出这个二维数组里,最大的那个值,并打印出其二维坐标。

[A]:

 1 public class HelloWorld {
 2     public static void main(String[] args) {
 3 //        定义一个5X5的二维数组。 然后使用随机数填充该二维数组。
 4 //        找出这个二维数组里,最大的那个值,并打印出其二维坐标
 5         int[][] a = new int[5][5];
 6         int max = -1;
 7         int m = 0;
 8         int n = 0;
 9         
10         for (int i = 0; i < a.length; i++) {
11             for (int j = 0; j < a[i].length; j++) {
12                 a[i][j] = (int)(Math.random() * 100);
13                 System.out.print(a[i][j] + "	");
14                 if (max < a[i][j]) {
15                     max = a[i][j];
16                     m = i;
17                     n = j;
18                 }
19             }
20             System.out.println();
21         }
22         
23         //输出二维数组举证方法二
24         System.out.println("Method 2:");
25         for (int[] row : a) {
26             for (int column : row){
27                 System.out.print(column +"	");
28             }
29             System.out.println();
30         }
31         System.out.println("最大值 = a[" + m +"][" + n + "]= " + max);
32     }
33 }

 下面将对第25~26行代码进行解析:

1 for (int[] row : a) {
2             for (int column : row){

 第25行:『:』右边的a表示二维数组a的第一维<即a[i][j]中的i>地址,row指向了数组a的第一维的引用[即地址],故∵第一维i的地址有两个∴遍历两次

第26行:『:』右边的row代表一维数组int[] row的地址,用基本类型column指向了一维数组row的地址。。。

原文地址:https://www.cnblogs.com/lijiehua/p/8151500.html