2015-09-14 89 views
1

所以即时通讯诚实地卡在这里,a2 [行] [列]是错误的,但我不知道为什么。我只是想念一些近距离视线?在java中获取二维数组的错误

public class ArrayHW { 
public static void main(String[] args){ 
    int [][] a2 = {{10,20,30,40}, 
      {50, 60, 70 , 80}, 
      {90, 100, 110, 120}}; 
    display2DArray(); 
} 

public static void display2DArray() { 
    for (int row = 0; row < 3; row++){ 
     for (int column = 0; column < 4; column++){ 
      System.out.println(a2[row][column]); 
     } 
    } 
} 
+1

什么错误?请不要让我们猜 - 发布完整的错误信息。 –

回答

2

你已经有了一个范围问题,因为a2 2D int数组已经在main方法内部声明过了,因此只在同一个main方法中可见。 display2DArray方法不能看到也不能操作这个变量。一个体面的解决方案是给display2DArray方法一个int[][]参数并将数组传递给方法。请注意,参数名称可以是任何有效的变量名称,但是您需要在display2DArray方法中使用相同的变量名称。

public static void display2DArray(int[][] foo) { 
    // avoid use of "magic" numbers and instead use the array's length field 
    for (int row = 0; row < foo.length; row++){ 
     for (int column = 0; column < foo[row].length; column++){ 
      System.out.println(foo[row][column]); 
     } 
    } 
} 

然后调用方法:

display2DArray(a2); 

另一种可行的解决方案是通过声明它的类,而不是在main方法,使A2类的静态字段。

+0

ahhh好的!现在明白了。有没有办法做同样的事情,但没有给它的参数?就像我离开它的方式一样,我能够像静态无效一样改变为某种东西吗? – ThePyroMark

+0

@ThePyroMark:是的,我在回答结束时已经告诉过你如何在不使用参数的情况下做到这一点。 –