2010-09-13 71 views
-2

我正在編寫代碼來整理一個慈善足球隊,我要編寫一個名爲addPlayer()的方法,它需要兩個字符串參數,球員名稱以及是否爲名人或專業人員以及char參數性別。該方法不返回任何值。此方法創建具有給定名稱,分類和性別的Player的新實例,並將其添加到合適的玩家集合中,無論是名人還是教授。addPlayer()方法返回沒有值

我有一個populatePlayerLists()方法

public void populatePlayerLists() 
{ 

    this.addPlayer("Robbie Williams","Celebrity",'M'); 
    this.addPlayer("Robbie Fowler","Professional",'M'); 

} 

我的實例變量如下

private List <Player> professionalsList; 
private List<Player> celebritiesList; 

和我addPlayer()方法如下

public void addPlayer(String name, String classification,char gender) 
{ 

    { 
     this.professionalsList.add(new Player(name, classification, gender)); 
     this.celebritiesList.add(new Player(name, classification, gender)); 
    } 
} 

球員和名人添加到名單,但他們添加到這兩個名單,當我希望名人goto一個名單和專業人員得到o請幫助其他人。

回答

1

簡單,如果statment將做到這一點:

public void addPlayer(String name, String classification,char gender) 
{ 
    if (classification.equals("Professional")) 
     this.professionalsList.add(new Player(name, classification, gender)); 
    else 
     this.celebritiesList.add(new Player(name, classification, gender)); 
} 

public void addPlayer(String name, String classification,char gender) 
{ 
    if (classification.equals("Professional")) 
     this.professionalsList.add(new Player(name, classification, gender)); 
    else if (classification.equals("Celebrity")) 
     this.celebritiesList.add(new Player(name, classification, gender)); 
    else 
     throw new RuntimeException("unknown classification: " + classification); 
} 
1

看起來你錯過選擇其中的邏輯來加入到?類似於

if (classification.equals("Celebrity")) { 
    this.celebritiesList.add(new Player(name, classification, gender)); 
} else { 
    this.professionalsList.add(new Player(name, classification, gender)); 
} 
5

您可以使用此字符串系統並使用equals()檢查字符串的值。

Player player = new Player(name, classification, gender); 
if (classification.equals("Celebrity")) { 
    this.celebritiesList.add(player); 
} else if (classification.equals("Professional")) 
    this.professionalsList.add(player); 
} 

或者你可以改變你的系統使用枚舉(方式,方法更好):

public enum Classification{ 
    Professional, 
    Celebrity; 
} 

public enum Gender{ 
    Male, 
    Female; 
} 

public void addPlayer(String name, Classification classification, Gender gender){ 
    Player player = new Player(name, classification, gender); 
    if (classification == Classification.Celebrity) { 
     this.celebritiesList.add(player); 
    } else if (classification == Classification.Professional){ 
     this.professionalsList.add(player); 
    } 
} 

//...  
this.addPlayer("Robbie Williams", Classification.Celebrity, Gender.Male); 
this.addPlayer("Robbie Fowler", Classification.Professional, Gender.Male); 

你甚至可以使用switch(但我不會使用它) :

Player player = new Player(name, classification, gender); 
switch(classification){ 
    case Celebrity : 
     this.celebritiesList.add(player); 
     break; 
    case Professional : 
     this.professionalsList.add(player); 
     break; 
    default : 
     System.out.println("FileNotFound"); 
}