2

我有一个包含对象的 ArrayList。我一直想要/需要做的是在 ArrayList 中搜索特定对象,并在找到时更改其中一个值。IE 我有一个足球运动员队,比如费城老鹰队,其中包含球队名称、总得分、总麻袋数,然后按名字、姓氏、参加的比赛和位置列出所有球员。我正在寻找一个特定的球员,比如 Chad Hall,我想将他从老鹰队中移除,并将他交易到新英格兰爱国者队。到目前为止,我所拥有的是 ArrayList 的迭代,但我的代码没有找到播放器然后退出。

case 6:
           String name = "";
           System.out.print("Who would you like to trade? ");
           name = kb.nextLine();
           tradePlayer(nflTeams, name);

public static void tradePlayer(ArrayList<Team> nflTeams, String name)
  {
     Scanner kb = new Scanner(System.in);
     String teamName = "";
     System.out.print("What team do you want to trade this player to?(Team Acronym) "    );
     teamName = kb.nextLine();

     for(Team t: nflTeams){
        if (nflTeams.contains(name.toLowerCase()))
                      t.setName(teamName);
                }
     System.out.println("Cannot find " + name);
  }

Player课程涉及按名字,姓氏,团队,位置,演奏的球员。我想要改变的是团队。在Team课堂上,我可以setName(String)设置团队名称。

任何建议或想法都非常感谢。

4

3 回答 3

2

if (nflTeams.contains(name.toLowerCase()))

你想做什么?您的列表nflTeams包含Team对象而不是名称。
这是行不通的。
如果您需要Team通过它访问 aname然后Map<String,Team>使用

于 2012-12-04T22:14:11.210 回答
0

您必须从团队中获取球员列表并通过指定的方式从那里删除name

String teamToAddNewPlayer = "New England Patriots";
String deletedPlayer = null;
for(Team t: nflTeams){
      List<String> players = t.getPlayers();
      if (players.contains(name)){
          deletedPlayer = players.remove(name);
      }
      if (t.getName().equals(teamToAddNewPlayer))
          players.add(name);
}
if (deletedPlayer == null)
//nothing was deleted
else
//player was deleted
于 2012-12-04T22:12:16.650 回答
0

使用 Iterator 将使您能够更好地控制您正在尝试的内容。

import java.util.*;

 class IteratorDemo {


public static void main(String args[]) {
      // Create an array list
      ArrayList al = new ArrayList();
      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");

  // Use iterator to display contents of al
  System.out.print("Original contents of al: ");
  Iterator itr = al.iterator();
  while(itr.hasNext()) {
     Object element = itr.next();
     System.out.print(element + " ");
  }
  System.out.println();

  // Modify objects being iterated
  ListIterator litr = al.listIterator();
  while(litr.hasNext()) {
     Object element = litr.next();
     litr.set(element + "+");
  }
  System.out.print("Modified contents of al: ");
  itr = al.iterator();
  while(itr.hasNext()) {
     Object element = itr.next();
     System.out.print(element + " ");
  }
  System.out.println();

  // Now, display the list backwards
  System.out.print("Modified list backwards: ");
  while(litr.hasPrevious()) {
     Object element = litr.previous();
     System.out.print(element + " ");
   }
   System.out.println();
}
}

这个例子来自

于 2012-12-04T22:15:19.360 回答