2012-11-30 22 views
-1
class B { 
    public static void main(String a[]) 
    { 
     int x; 
     String aa[][]= new String[2][2]; 
     aa[0]=a; 
     x=aa[0].length; 
     for(int y=0;y<x;y++) 
      System.out.print(" "+aa[0][y]); 
    } 
} 

和命令行調用是更改多維數組的一行的長度?

>java B 1 2 3

和選擇是

1)0 0

2.)1 2

3.)0 0 0

4)1 2 3

我告訴第二個選項是正確的,因爲陣列與[2][2]聲明的,因此它不能像[0][2]。但是,答案是1 2 3。任何人解釋這一點,這是怎麼發生的

+1

你在調試器中試過它,看看這是怎麼發生的? – djechlin

+0

我使用命令提示符執行此操作 – Ravi

+1

@coders然後在調試器中運行它並查看它在做什麼。低調的研究努力。 – djechlin

回答

7

程序的參數存儲在aa[0]這是一個數組,因爲aa是一個數組數組。

所以程序只是真正迭代main方法的參數。它打印1, 2, 3(它不關心aa[1])。

int x; 
String aa[][]= new String[2][2]; // create an matrix of size 2x2 
aa[0]=a; // store the program arguments into the first row of aa 
x=aa[0].length; // store the length of aa[0] which is the same as a 
for(int y=0;y<x;y++) // iterate over aa[0] which is the same as a 
    System.out.print(" "+aa[0][y]); 

是相同的功能爲:

for (int i = 0; i < a.length; ++i) 
    System.out.print(" " + a[i]); 
// or even 
for (String str: a) 
    System.out.print(" " + str); 

編輯

如前所述有人自刪除他的回答(你不應該有,我upvoting它,而你刪除它),java多維數組是鋸齒形數組,這意味着多維數組不必具有相同的大小,您可以使行1和行2具有2種不同的大小。因此,這意味着聲明String[2][2]並不意味着在重新分配行時該行只需限制在兩列中。

String[][] ma = new String[3][2]; 
ma[0] = new String[] {"a", "b"}; 
ma[1] = new String[] {"a", "b", "c", "d"}; // valid 
String[] foo = new String {"1", "3", "33", "e", "ff", "eee"}; 
ma[2] = foo; // valid also 
+0

好的。這是一段非常奇怪的代碼。 – jrajav

+0

回答錯誤的人是誰?你介意解釋......嗎? – Alex

+0

是的..請!!! – Ravi

0

變量aa被聲明爲一個字符串數組的數組,而不是簡單的多維數組。當您設置aa[0] = a時,您將數組數組的第一個元素設置爲作爲參數傳遞的字符串數組。因此,當您遍歷aa[0]的項目時,您正在遍歷aa[0] = a語句中放置的項目。