我有两个搜索循环来执行不同的操作,但我对它看起来的重复性不满意。
用于删除项目的第一种方法如下:
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.");
}
}
我该如何重构呢?