2012-05-01 83 views
0

我有兩個搜索循環來執行不同的操作,但我對這看起來多麼重複感到不滿。任何人都可以想出一種方法來重構這個以避免重複的代碼?

用於刪除項目的第一種方法如下:

public void RemovePlayer(int theID){ 
    boolean matchFound = false; 

    if (playerObjects.size() != 0){ 
     for (int i = 0; i < playerObjects.size(); i++){ 
      Person playerToRemove = (Person) playerObjects.get(i); 
      if (playerToRemove.getID() == theID){ 
       playerObjects.remove(i); 
       System.out.println("Player with ID # " + theID + " removed"); 
       matchFound = true; 
       // As ID is unique, once a player is found it is unnecessary to continue looping 
       break; 
      } 

      // If matchFound is never set to true then show appropriate error 
      if (matchFound == false) { 
       System.out.println("Player with ID # " + theID + " not found"); 
      } 
     } 
    } 
    else { 
     System.out.println("No players have been added.");  
    } 
} 

而第二個方法,該方法基本上是相同的碼,但是,如果發現匹配是如下執行不同的動作:

public void RetrievePlayer(int theID){ 
    boolean matchFound = false; 

    if (playerObjects.size() != 0){ 
     for (int i = 0; i < playerObjects.size(); i++){ 
      Person playerToRetrieve = (Person) playerObjects.get(i); 
      if (playerToRetrieve.getID() == theID){ 
       System.out.println("PLAYER FOUND:"); 
       playerToRetrieve.GetDetails(); 
       matchFound = true; 
       break; 
      } 

      // If matchFound is never set to true then show appropriate error 
      if (matchFound == false) { 
       System.out.println("Player with ID # " + theID + " not found"); 
      } 
     } 
    } else { 
     System.out.println("No players have been added.");  
    } 
} 

我該如何重構這個?

回答

3

如何返回索引i玩家的方法「FindPlayer」? RemovePlayer和RetrievePlayer那麼就應該是:

public void RemovePlayer(int theID){ 
    int playerId = FindPlayer(theID); 
    if (playerId >= 0) { 
     playerObjects.remove(playerId); 
    } 
} 

public void RetrievePlayer(int theID){ 
    int playerId = FindPlayer(theID); 
    if (playerId >= 0) { 
     Person player = (Person) playerObjects.get(playerId); 
     player.getDetails(); 
    } 
} 

那「FindPlayer」的方法是有點像這樣:

protected int FindPlayer(int theID){ 
    if (playerObjects.size() != 0){ 
     for (int i = 0; i < playerObjects.size(); i++){ 
      Person player = (Person) playerObjects.get(i); 
      if (player.getID() == theID){ 
       return i; 
      } 
     } 

     System.out.println("Player with ID # " + theID + " not found"); 
    } else { 
     System.out.println("No players have been added.");  
    } 

    return -1; 
} 
+0

謝謝,這就是我的編程語言尖端的解決方案,可以這麼說! –

0

如果然後分手了,你可以有一個find方法返回一個Playerremove以玩家爲參數的方法。由於索引可能是暫時的(例如,如果其他人添加到列表中,索引可能會失效),我寧願這樣做。

還有更多你可以做(​​也許是findAllfilter方法與謂語),但我不會看這些,直到你有充分的理由這樣做(你不會需要它)

1

將球員放入Map<Integer,Player>。然後使用Map的基本方法(put,remove),而不是在列表中循環。

相關問題