+ 3

I need some help understanding Java Arrays.

Can someone write a basic java program to demonstrate how to effectively work with Object arrays? Well commented code would help my understanding a great deal. Example: A class named Player with name and age as private variables and methods to work with them. Create a Player array of variable length (based on player input, default length of 2). include methods for traversing that array (getCurrentPlayer, getNextPlayer,) and allow those players to use the methods from the player class.

1st Jul 2017, 12:18 AM
Mark Paramonte
Mark Paramonte - avatar
3 odpowiedzi
+ 5
Think of how String arrays work. It's the same thing! :D Strings are objects. The problem you are having in your code is that each object in the array is null. Remember the default value of objects is null, So: players = new Player[2]; Creates an array with 2 null elements. So, when you write: a.setName(); This is giving a null exception. Because setName() isn't a method in null, so the compiler can't find anything. The problem can be fixed by using your fillArray() method! You can either call fillArray() after creating the PlayerArray object or call it in the constructors. Example in constructors/ PlayerArray(){ players = new Player[2]; fillArray(); } PlayerArray(int n){ players = new Player[n]; fillArray(); }
1st Jul 2017, 2:00 AM
Rrestoring faith
Rrestoring faith - avatar
+ 3
@Rrestoring Thanks, this is extremely helpful!
1st Jul 2017, 2:26 AM
Mark Paramonte
Mark Paramonte - avatar
+ 2
https://code.sololearn.com/cel2zOtf19ZJ/?ref=app Here is the code I have, which you can probably see what I'm trying to do...
1st Jul 2017, 12:19 AM
Mark Paramonte
Mark Paramonte - avatar