Arrays


Primitive and Object Arrays

ArrayExamples.java
(uses Bunny.java)

ManyNames.java
ManyNamesHarness.java

Deitel 7


Classwork

Create a project using the usual naming convention and add a class with a main and also the class Bunny given above.   When you make methods in the class with main, add the keyword static, just as main uses it.

Part A

Add a method makeBools which takes an int size and returns an array of booleans.  In the method, create an array of booleans whose length is size.  Make every third element of the array true before returning it.

Add a method mashUp which takes an array of Strings and returns a String that consists of all those Strings concatenated together with spaces between, so if given the array {"Hello", "world", "this", "is your message"} mashUp  would return "Hello world this is your message"

Add a method makeBunnies, which takes as parameter an array of Strings, and returns an array of Bunnys.

In makeBunnies, create an array of Bunnys the same size as the array of strings. 

In a loop, fill the array with Bunnys,

(hint: the Bunny class has a parameterized constructor that takes name and carrotcount).

Return the array of Bunnys created.

 In your main, test that these work.  Make an array of at least 5 Bunnys using the special array initialization to create the array of Strings you give to makeBunnies.


Part B

Add a new class BunnyFarmer which has an instance variable to hold the farmer's name and also an instance variable hutch, which is an array of Bunnys.  Also add an instance variable firstEmpty, an int, to keep track of the first empty spot in hutch.  In this case, don't make accessors and mutators for hutch and firstEmpty (we often leave these out, or make them private).

In the default constructor for BunnyFarmer, set up the array hutch with space for 10 Bunnys.  In this case there are no actual Bunnys yet, so firstEmpty is 0.

Add a method addBunny  which takes a Bunny as parameter.  Check firstEmpty to see if there is still space in hutch.  If so, put the given Bunny in the first empty spot in the array and increment firstEmpty.  If we are out of space, do nothing.

In the toString for this class, return a String with the farmer's name at the top and then a numbered list of the Bunnys (using the toString from Bunny).  Only go up to firstEmpty, since all the spots beyond that will be empty.

So something like:

Farmer Bob
Bunny Hutch:
1. Bunny Bun 1 (10 carrots)
2. Bunny Mr. Bunnington (1 carrots)
3. Bunny Bugs (2 carrots)
4. Bunny Babs (15 carrots)
5. Bunny Buster (6 carrots)

 

[EC] Add to BunnyFarmer a parameterized constructor which takes a name for the farmer and an array of Bunnys.  Make hutch twice the size of the given array.  Copy the Bunnys from the array given into hutch and make sure you have set firstEmpty appropriately.

 

 In the other class, in the main method,  create an array of three BunnyFarmers and fill it with BunnyFarmers.  Make sure your methods work