2015-11-21 118 views
0

對於一個實踐問題,爲我的編程類,我們有:錯誤輸出二維String數組轉換成一維字符串數組

「定義返回字符串的二維數組具有的第一行的方法字符串名稱爲「John」。「

public class TwoDimensionalStringArrayI { 

public static void main(String[] args) { 
    String[][] b = {{"John", "Abby"}, 
        {"Sally", "Tom"}}; 

    System.out.println(firstRow(b)); // line 8 
} 

public static String[] firstRow(String[][] a) { 
    String[] name = new String[a[0].length]; 
    int counter = 0; 

    for (int row = 0; row < a.length; row++) { 
     for (int col = 0; col < a[row].length; col++) { 
      name[counter++] = a[row][col]; // line 17 
     } 
    } 
    return name; 
    } 
} 

通過Eclipse的調試過程後,我的String數組name設置爲{"John", "Abby"},但我在8號線和17嘗試運行程序時得到一個ArrayIndexOutOfBoundsException錯誤。

困惑於如何讓程序輸出名稱「John」和「Abby」。

回答

0

因爲這條線的線;

for (int row = 0; row < a.length; row++) { 

firstRow(String[][] a)方法的目標是返回所述陣列的第一行,因此,上面的線應如下;

for (int row = 0; row < 1; row++) { 

因爲它遍歷所有數組的元素的,它超過了name陣列僅具有[0]。長度室,數值,2(String[] name = new String[a[0].length];

在大小爲了使你的代碼有效,有兩種方法;

第一個解決方案

更新for循環條件如上所述,測試代碼是;

public class TwoDimensionalStringArrayI { 
    public static void main(String[] args) { 
     String[][] b = {{"John", "Abby"}, 
         {"Sally", "Tom"}}; 

//  System.out.println(firstRow(b)); // line 8 
     String[] result = firstRow(b); 
     for(int i = 0; i < result.length; i++) 
      System.out.print(firstRow(b)[i] + " "); 
    } 

    public static String[] firstRow(String[][] a) { 
     String[] name = new String[a[0].length]; 
     int counter = 0; 

//  for (int row = 0; row < a.length; row++) { 
     for (int row = 0; row < 1; row++) { 
      for (int col = 0; col < a[row].length; col++) { 
       name[counter++] = a[row][col]; // line 17 
      } 
     } 
     return name; 
    } 
} 

輸出如下;

John Abby 

您已經注意到(您應該),我也更新了打印行。

第二種解決

使你的代碼功能的第二種方法是,對於一個[] [],這實際上是爲返回容易只返回第一行[1]。測試代碼是;

public static void main(String[] args) { 
     String[][] b = {{"John", "Abby"}, 
         {"Sally", "Tom"}}; 

//  System.out.println(firstRow(b)); // line 8 
     String[] result = firstRow(b); 
     for(int i = 0; i < result.length; i++) 
      System.out.print(firstRow(b)[i] + " "); 
    } 

    public static String[] firstRow(String[][] a) {  
     return a[0]; 
    } 

而輸出是;

John Abby 

希望它有幫助。

0

我想你應該切換變量ROW和COL在17

+0

我試過了,但它只是將名稱數組更改爲「John」和「Sally」。此外,我仍然得到錯誤。 – derpt34