Part 2 --Programming 40
points - Read all instructions
carefully before beginning!
Open
BlueJ. Choose “Project”, “New Project”
and create a new project called Animal in your Java 1 folder. In this project, you are to create two
classes. An object class called Animal and an application program AnimalTest.
ANIMAL CLASS
This
should keep track of an animal’s type (it will either be a snail, bunny, or a
cheetah), its name, and its distance (how far it has travelled.)
Your
class will need four methods.
The
first is a constructor that takes zero parameters. This constructor should randomly create
either a snail, bunny, or cheetah, each with an equal likelihood. To do this, you will need to use a Random
object. (You must figure out how to
make an equal chance of getting either of these three.) If it creates a snail,
its name should be “Pokey”. If it
creates a bunny, its name should be “Snuffy”.
The name of the cheetah should be “Blazer”. It should initialize its distance to zero.
You
should next create the move
method. The move method takes zero
parameters. If the executor of the call
is a snail, have your little friend move 1 unit. If it is a bunny, it should move 4 units, and if it is a cheetah,
have it move 16 units. This is an
action method.
Your
next method is again the move method,
except this time you will overload it by giving it one parameter, numSteps. You will need a for loop inside this method that loops numSteps times, calling the move method
that took no parameters each time.
Your
final method should be a query method to return the distance the animal has
travelled so far.
To
make this easier for you, here are the headers for the methods:
·
public
Animal()
·
public
void move()
·
public
void move(int numSteps)
·
public
int getDistance()
·
public
String toString()
**Include a toString() method
to print out the following: name is a animalType and has
travelled distance.**
For
example, if you have a bunny who had moved twice, it should print: “Snuffy is a
bunny and has travelled 8.”
APPLICATION PROGRAM
This
will be used to test your object class.
You are to create an application program that creates a new ArrayList
called animals and, in a for loop,
randomly adds between 1 and 10 animals to the list.
You
should then pick a random number numSteps
between 1 and 5 which will be the number of times you would like your animals
to move.
Now
make a for loop that loops through all the animals in the ArrayList, having
them move the amount you randomly chose before
the loop began. (All animals are to
move the same amount!)
The
exact line of code for this is: ((Animal)animals.get(i)).move(numSteps);
// have to cast here!
After
that loop, print out the following: “The animals should move numSteps times.”
WHEN YOU ARE DONE, RUN YOUR
APPLICATION PROGRAM. Then COPY its
output into the TOP of your APP PROGRAM as a comment. (This way I can see what it did without running your program.)