日期:2014-05-20  浏览次数:20653 次

java 二维数组的问题
小弟有个小问题求教一下:代码如下:
int[][] a = new int[2][2];
int[][] b = new int[2][2];
int temp = 45;
int temp2 = 55;
for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 2; j++) {
      a[i][j] = 10;
      b[i][j] = 11;
      System.out.println( "a1[" + i + "][" + j + "]==== " + a[i][j] + "   temp=== " + temp + "   temp2=== "+temp2);
      temp = a[1][1];           
      temp2 = b[1][1];
              System.out.println( "a2[" + i + "][" + j + "]==== " + a[i][j] + "   temp=== " + temp + "   temp2=== "+temp2);
      System.out.println("-------------------------------");
     }
}

运行之后打印出来的值为:
a1[0][0]==== 10   temp=== 45  temp2=== 55
a2[0][0]==== 10   temp=== 0   temp2=== 0
-------------------------------
a1[0][1]==== 10   temp=== 0   temp2=== 0
a2[0][1]==== 10   temp=== 0   temp2=== 0
-------------------------------
a1[1][0]==== 10   temp=== 0   temp2=== 0
a2[1][0]==== 10   temp=== 0   temp2=== 0
-------------------------------
a1[1][1]==== 10   temp=== 0   temp2=== 0
a2[1][1]==== 10   temp=== 10  temp2=== 11
-------------------------------
一直没有想明白,为什么在
a2[0][0]==== 10   temp=== 0   temp2=== 0
-------------------------------
a1[0][1]==== 10   temp=== 0   temp2=== 0
a2[0][1]==== 10   temp=== 0   temp2=== 0
-------------------------------
a1[1][0]==== 10   temp=== 0   temp2=== 0
a2[1][0]==== 10   temp=== 0   temp2=== 0
这中间,temp和temp2的值会变成0呢?
求教各位高手。
------最佳解决方案--------------------
temp = a[1][1];  因为你的数组a定义时没有初始化,所以a[1][1]就是默认的0.

为什么a1[0][0]等于10,因为for循环时,赋值了。

就这么直观的解释。 
------其他解决方案--------------------
谢谢.明白了.