我有一个方法可以创建一组6个对象,并为其分配变量,包括名称,团队,位置等。 我需要一种方法,可以搜索对象数组,只显示具有选定变量(位置)的对象。该项目要求我显示只有具有特定位置的玩家的列表。因此,如果所选位置为“QB”,则会显示“Eli Manning”“Tom Brady”“Derek Car”及其统计数据。
//constructor creating 6 players
public NFLPlayerManager(){
NFLPlayer x = new NFLPlayer("Eli Manning", "New York Giants", "QB", 21, 77, 72, 170, 0, 160, "TCU");
playerList.add(x);
NFLPlayer y = new NFLPlayer("Tom Brady", null, "QB", 0, 0, 0, 0, 0, 0, null);
playerList.add(y);
NFLPlayer z = new NFLPlayer("Josh Kline", null, null, 0, 0, 0, 0, 0, 0, null);
playerList.add(z);
NFLPlayer a = new NFLPlayer("Derek Carr", null, "QB", 0, 0, 0, 0, 0, 0, null);
playerList.add(a);
NFLPlayer b = new NFLPlayer("Rob Gronkowski", null, "TE", 0, 0, 0, 0, 0, 0, null);
playerList.add(b);
NFLPlayer c = new NFLPlayer("James White", null, null, 0, 0, 0, 0, 0, 0, null);
playerList.add(c);
}
答案 0 :(得分:0)
public void showPlayerByPosition(String position)
{
for(int i = 0; i < playerList.size(); i++)
{
//now lets grab the NFLPlayer's position with a getter and compare it to the given string in our parameter
if(playerList.get(i).getposition().equals(position))
{
//then print the NFLPlayer
playerList.get(i).showPlayer(); //Note i making up the name for the print function
}
}
}
现在您可以像这样调用函数
showPlayerbyPosition("QB")