I'm a starting programmer and i can't seem to find my mistake in my code.
I have an arraylist of objects(persons) and I want to save the value of an index into a variable:
public void randomCaptain(){
Random dice = new Random ();
int n = dice.nextInt(personList.size());
Person theCaptain = personList.get(n);
System.out.println(theCaptain);
}
First i want a random number between 1 and the amount of persons in my arraylist. After this I want the value at spot n, so person n of my arraylist and save this into Person 'theCaptain'. I tried this with personList.get(n). But if I check this value by a println it returns 'null'. I checked the size of my array etc and the array is not empty. So that's not the problem.
edit
This is the part where the array is being initialized:
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));
}
When I check this with size(), than it returns 15 correctly. So that shouldn't be the problem.
In the main:
Team team= new Team();
team.init();
team.randomCaptain();
I hope you can help me, thanks
Iif it's you and not the famous variablei:)personList.new ArrayList<X>()will not automatically create yourXinstances on demand!null?