2011-07-19 86 views
0

我有節點的名單,我遍歷:Java的枚舉和循環問題

for (int i = 0; i < aNodes.getLength(); i++) { 
    // 
} 

例如,假設該列表包含12個項目,而且我知道3項表中的代表一行,接下來的3個屬於下一行。這意味着我的12個節點列表來源於包含4行的HTML表格。

每一行我想要做的事,例如,創建一個新的對象,並填充它......或任何之後。我有一個解決方案:

ArrayList<Account> mAccounts = new ArrayList<Account>(); 
Account account = new Account(); 

for (int i = 0; i < aNodes.getLength(); i++) { 

      String nodeValue = aNodes.item(i).getNodeValue(); 
      boolean isNewRow = (i % COLS_PER_ROW == 0); 

      if (isNewRow) { 
       account = new Account(); 
       mAccounts.add(account); 
      } 

      switch (i % COLS_PER_ROW) { 
      case ACCOUNT_POS: 
       account.setAccount(nodeValue); 
       break; 
      case BALANCE_POS: 
       account.setBalance(nodeValue); 
       break; 
      case DATE_POS: 
       account.setDate(nodeValue); 
       break; 
      } 
     } 

但也有很多東西我不喜歡這樣的解決方案:

  1. 的帳戶實例,因爲創建的兩次第一次,一旦外循環,然後一旦新行被檢測到。
  2. 它使用整型常量ACCOUNT_POS = 0,BALANCE_POS = 1,DATE_POS = 2 ......這並不覺得很不錯,我想我應該用枚舉。
  3. 我不能在循環變量'i'中使用枚舉。
  4. 我不能使用for each循環,因爲節點沒有實現正確的接口,

任何人都可以表明,解決的事情,我不喜歡它的名單這樣做的更好的辦法?

謝謝。

回答

1

您可以通過COLS_PER_ROW而不是1遞增我,然後寫:

for (int i = 0; i < aNodes.getLength(); i += COLS_PER_ROW) { 
    account = new Account(); 
    String account = aNodes.item(i).getNodeValue(); 
    account.setAccount(account); 
    String balance = aNodes.item(i+1).getNodeValue(); 
    account.setBalance(balance); 
    String date = aNodes.item(i+2).getNodeValue(); 
    account.setDate(date); 
    mAccounts.add(account); 
} 
1

我不能使用枚舉與循環變量「我」。

沒有,但你可以使用:

for(SomeEnum item : SomeEnum.values()){ 
    // code here 
} 
+0

事實上,你可以用做它以某種方式: '開關(SomeEnum。values()[i%COLS_PER_ROW])' – gastush

1

你是一個基於位置的文件工作,所以,如果我理解正確的話,你就其內容如下結構:

  • account;
  • 平衡,
  • 日期;

認識到這一點,也許你可以更好地應對while循環指數,而不是使用一個for循環,如下:

int i = 0; 
while (i < aNodes.getLength()) { 
    account = new Account(); 
    account.setAccount(aNodes.item(i).getNodeValue()); 
    account.setBalance(aNodes.item(i+1).getNodeValue()); 
    account.setBalance(aNodes.item(i+2).getNodeValue()); 
    mAccounts.add(account) 
    i += 3; 
} 

我還建議提取帳戶filling-代碼放在一個新的方法中,比如'extractAccountFromNodes',然後在循環中調用它;所以循環將變成:

int i = 0; 
while (i < aNodes.getLength()) { 
    mAccount.add(extractAccountFromNodes(aNodes, i)); 
    i += 3; 
} 

與方法extractAccountFromNodes這樣的:

private Account extractAccountFromNodes(Nodes nodes, int position) { 
    account = new Account(); 
    account.setAccount(nodes.item(i).getNodeValue()); 
    account.setBalance(nodes.item(i+1).getNodeValue()); 
    account.setBalance(nodes.item(i+2).getNodeValue()); 
    return account; 
} 
+0

謝謝你的這個例子。好的命名也是如此。我選擇了使用@Daniel提供的代碼的代碼,它在循環的for(...)部分中增加循環變量。 – Jack