Reputation: 1077
This is a past exam question focusing on arrays and here is the question:
Define a class called Laboratory that contains an array of Computers. The size of the array should be specified in the constructor to the Laboratory class. Your class should contain methods for adding a Computer to the array. (early part I had to define a computer class with a couple of attributes with a constructor)
So I know how to do the first two parts, the class and size specified in the constructor. How would I do the third part (about the methods)?
Upvotes: 0
Views: 97
Reputation: 363
You could have an instance variable with the current count of Computers in the array, then use this to add the computer
private int computerCount = 0;
public void addComputer(Computer comp)
{
arrayName[computerCount] = comp;
computerCount++;
}
Upvotes: 1
Reputation: 14524
Assuming you've already written the constructor that creates the array:
class Laboratory {
private Computer[] computers;
private int nextIndex = 0;
public void addComputer(Computer comp) {
// throws an ArrayOutOfBoundsException if the user
// tries to add too many Computers. You might want to
// do something else by checking that nextIndex < computers.length
computers[nextIndex] = comp;
nextIndex += 1;
}
}
Upvotes: 2