2013-03-11 44 views
2

我在遍歷ArrayList時遇到了一些麻煩。我有一個名爲的課程,它延伸到ArrayList<String>。我有另一個名爲Table的課程,它延伸到ArrayList<Row>通過ArrayList迭代<對象<String>>

我想遍歷Table類來將行的ArrayList轉換爲字符串的二維數組。

這裏是我的Table類代碼:

public class Table extends ArrayList<Row> 
{ 
public Row[] appArray; //Array of single applicant details 
public String tableArray[][]; //Array of every applicant 
private ArrayList<Row> ar; 
private Row r; 

public Table() 
{ 
} 

public void addApplicant(Row app) 
{ 
    add(app); 
    displayable(); 
} 

public void convertToArray() 
{ 
    int x = size(); 
    appArray=toArray(new Row[x]); 
} 

public void displayable() 
{ 
int i,j; 
for (Row r: ar) 
    i=0; 
    for(String s: r){ 
     j=0; 
     tableArray[i][j]=s; 
     j++; 
    } 

}} 

這裏是類:

public class Row extends ArrayList<String> 
{ 
public Row(String appNumber, String name, String date, String fileLoc, String country, Table table) 
{ 
    addDetails(appNumber,name,date,fileLoc,country); 
    table.addApplicant(this); 
} 

public void addDetails(String appNumber, String name, String date, String fileLoc, String country) 
{ 
    add(appNumber); 
    add(name); 
    add(date); 
    add(fileLoc); 
    add(country); 
}} 

我有麻煩的方法是在Tabledisplayable()。它告訴我i may not have been initialized但是,如果我在每個循環的第二個初始化它,它將只遍歷我的​​中的第一個元素?

在此先感謝任何指針。

+0

設置'i'和'j'爲'0' * *內各自'for'循環似乎是一個可能的邏輯錯誤給我。 – 2013-03-11 15:39:51

+1

沒有'ArrayList >'這樣的事情,因爲'Object'類沒有類型參數('Object '無效)。 – Jesper 2013-03-11 15:40:24

回答

3

可顯示方法有兩個錯誤:

  • 第一for循環不具有{}
  • 我不遞增(I ++;失蹤)

代碼:

public void displayable() 
{ 
    int i,j; 
    for (Row r: ar){ 
    i=0; 
    for(String s: r){ 
     j=0; 
     tableArray[i][j]=s; 
     j++; 
    } 
    i++; 
    } 
} 
+2

我認爲這樣的增量不是我們想要的,因爲在下一次迭代中每個計數器都會變成零。 因此,還需要將'i = 0'和'j = 0'向上移一層 – alno 2013-03-11 15:51:24

+0

它的工作原理!感謝所有幫助的人。愚蠢的錯誤可以是這樣的麻煩。再次感謝。 – Hoggie1790 2013-03-11 15:54:58

4

你剛剛錯過了for (Row r: ar)循環中的塊。

此外,由於Fortega指出,您永遠不會在您的代碼中增加i,並且我認爲您將計數器歸零錯誤。

因此,而不是:

for (Row r: ar) 
    i=0; 
    for(String s: r){ 
    j=0; 
    tableArray[i][j]=s; 
    j++; 
    } 

你應該寫類似:

i=0; 
for (Row r: ar) { 
    j=0; 
    for(String s: r){ 
    tableArray[i][j]=s; 
    j++; 
    } 
    i++; 
} 

或者更好的縮小計數器的可視區域,並加入聲明與初始化:

// Remove previous declarations 

int i=0; 
for (Row r: ar) { 
    int j=0; 
    for(String s: r){ 
    tableArray[i][j]=s; 
    j++; 
    } 
    i++; 
} 
+0

以及'i ++;'? – Fortega 2013-03-11 15:44:16

+0

哦,你說得對。 '我'從來沒有在代碼中增加。 – alno 2013-03-11 15:47:01

2

更改爲:

for (Row r : ar) 
      i = 0; 
     for (String s : r) { 
      j = 0; 
      tableArray[i][j] = s; 
      j++; 
     } 

到:

for (Row r : ar) { 
      i = 0; 
      for (String s : r) { 
       j = 0; 
       tableArray[i][j] = s; 
       j++; 
      } 
      i++; 
     } 
相關問題