Data storage
[Agent practical 1 of 9]


So far we've only got one agent. We'll now build a short array of agents.


Empty the main block of Model of all the agent code and then, in there, make an array of Agent class, thus:

Agent[] agents = new Agent[3];

Compile your code to check it.

 


Doomed: Now, as we saw in the lecture materials, this code doesn't actually make any agents, just spaces ready for them. To see this, alter your code to this:

Agent[] agents = new Agent[3];
System.out.println(agents[0].x);

While you should be able to compile the code, it won't run properly (there's nothing wrong with asking for something that doesn't exist, so it will compile, it's just a foolish thing to do in the middle of a program and it will break it). Instead of running to the end, the program will break half way through and come back with an error containing the term NullPointerException. We'll deal with exceptions later in the course, but for now it is worth knowing that a warning containing NullPointerException means you've used a label that doesn't have anything attached to it. In this case, we haven't made any Agents, or attached one of them to the label agents[0] (we also, therefore, haven't made its x). When the JVM goes looking for agents[0] it finds nothing attached to it (well, except the value null) and so breaks when it then asks for its x.

So, remove the System.out.println(agents[0].x);

 


Can you now put new Agent objects into the three spaces? To do so, you'll need to think:

Some of this information can be found on the Key Ideas page. Combine these three pieces of knowledge together into a single line to fill the first space in the array. Compile the code to check it. Then do the remaining two spaces the same way. Remember, we need three new objects, one per label, not one new object attached to all three array labels.

 


Having done this, you should now be able to access and change the variables inside the agents inside the array, in the same way as you did before, but using array notation. So, whereas before you may have had:

int a = agent.x;
System.out.println(a);

You'd now have:

int a = agents[2].x;
System.out.println(a);

Again, have a play. See if you can use the array notation within the Model class to set each agent's y variable to a different value and check it has worked.

Note that we haven't changed anything in the Agent class -- each agent still has the same x and y variable. All we've changed is to store them inside an array, rather than giving each their own name.


Once you're happy with that, we'll move on to setting up our environment.