我是一名初级程序员,我似乎无法在代码中找到我的错误。
我有一个对象(人)的数组列表,我想将索引的值保存到变量中:
public void randomCaptain(){
Random dice = new Random ();
int n = dice.nextInt(personList.size());
Person theCaptain = personList.get(n);
System.out.println(theCaptain);
}
首先,我想要一个介于 1 和数组列表中的人数之间的随机数。 此后,我想要位置 n 处的值,即我的数组列表中的人员 n 并将其保存到人员“theCaptain”中。我用 personList.get(n) 尝试过这个。 但如果我通过 println 检查这个值,它会返回“null”。 我检查了数组的大小等,数组不为空。所以这不是问题。
编辑
这是数组初始化的部分:
public class Team{
ArrayList<Person> personList = new ArrayList<Person>();
void init(){
//Adding persons to the list
personList.add(new Coach("Tesan de Boer", "Straatweg 45", 2222));
personList.add(new GoalKeeper("Peter Post", "Straatweg 45", 2222, 1));
personList.add(new GoalKeeper("piet puk", "Straatweg 45", 2222, 21));
personList.add(new GoalKeeper("Siem van Aanhoolt", "Straatweg 45", 2222, 31));
personList.add(new Captain("Denis van rijn", "Straatweg 45", 2222, 5));
personList.add(new Fielder("Koen Weegink", "Straatweg 45", 2222, 2));
personList.add(new Fielder("Jan-Willem Rufus op den Haar", "Straatweg 45", 2222, 3));
personList.add(new Fielder("Tom Kraniker", "Straatweg 45", 2222, 4));
personList.add(new Fielder("Leon het Kanon", "Straatweg 45", 2222, 6));
personList.add(new Fielder("Robin Hogezant", "Straatweg 45", 2222, 7));
personList.add(new Fielder("Loesoe de Kat", "Straatweg 45", 2222, 8));
personList.add(new Fielder("Morris de Spee", "Straatweg 45", 2222, 9));
personList.add(new Fielder("Rein Zoekers", "Straatweg 45", 2222, 10));
personList.add(new Fielder("Darion Pok", "Straatweg 45", 2222, 11));
personList.add(new Fielder("Achmed de Bom", "Straatweg 45", 2222, 12));
}
当我用 size() 检查时,它正确返回 15。所以这不应该是问题。
主要内容:
Team team= new Team();
team.init();
team.randomCaptain();
希望您能帮助我,谢谢
最佳答案
我没发现你的程序有什么问题。我能够多次运行您的程序,但无法重现 null
输出。
您可以在这里亲自尝试一下 - http://ideone.com/tVFq4d
关于java - 如何在java中保存对象数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17132148/