Java Project: Mice Fill Central Park

Tips :: JavaJava program that calculates the time it would take mice to multiply and cover every inch of Central Park.
This project was created as part of a Java programming 101 course in the fall semester of 2012. The project and tutorial can help Java newbies get a sense of some of the basic conditions, loops, and mathematical functions.

 

Copying this project in full or in part is plagiarism. I share this code as a sample, to help you understand and learn. If you use any of this code, you should maintain the attribution to the original author (me!) along with a link to this page.

The Exercise

The original project exercise requested to create a program that calculates the time it would take to have enough mice cover every corner of central park. It allows for the existence of cats, who, of course, eat mice at a certain rate.

Algorithm Description

As with most codes, this too can be done in many different ways. I chose to use ‘BigFloat’ (which is a java library) to have the ability to present large numbers with many decimal points out of my love for accurate pure math. However, this should work just as well using floats. It won’t be as delightfully accurate to the umpteenth floating point, though.

The program is divided into two files:

  • SpeciesGrowth.java Class Defines the species objects and the method to define growth per a certain length of time.
  • MiceFillCentralPark.java Sets up the program, requests input from the user, and refers to the SpeciesGrowth class to calculate the desired result.

Algorithm Flowchart

This flowchart represents the conceptual operation of the program:

Algorithm Flowchart, Click to Enlarge

Algorithm Flowchart, Click to Enlarge

The SpeciesGrowth Class

This class defines the objects that will create the Mice and Cats, and holds methods for growth factors per certain length of time.

Object Methods

  • growPopulation (int)
    • Description: Calculates the new population number based on the growth factor and number of iterations. If “saveTheValue” is set to false, the value will not be saved in the population property. Otherwise, the value is automatically set into population property for the object.
    • Expected Input: numWeeks (int); saveTheValue
    • Output: New population number (int).
  • setPopulation (void)
    • Description: sets the population number for the object. Reverts to 0 on negative values.
    • Expected Input: popAmount (BigDecimal)
    • Output: void.
  • setSpecies
    • Description: sets the species name for the object.
    • Expected Input: specName (String)
    • Output: void.
  • setGrowthRate
    • Description: sets the growth rate for the object.
    • Expected Input: rate (double)
    • Output: void.
  • getSpeciesName
    • Description: retrieves the species name set for this object.
    • Expected Input: none.
    • Output: String.
  • getPopulation
    • Description: retrieves the current population number for the object.
    • Expected Input: none.
    • Output: BigDecimal.
  • getGrowthRate
    • Description: retrieves the growth rate that is set for this object.
    • Expected Input: none.
    • Output: double.

MiceFillCentralPark

This program reads user input for the initial number of mice and cats, their growth rates, and how many mice each cat eats per week. Then, it calculates the number of mice and number of cats per week, taking into account the number of eaten mice. Every year, it calculates the new population based on the growth rate. The program then displays the result to the user.

Class Methods

I later created a standalone user validation class for Java programs that contains the validation and user input request loops below. You can go over that class here.
  • askForInputDouble (double)
    • Description: Repeatedly asks the user for input, verifies the input is valid, and only returns the value when it is valid.
    • Expected Input: inputQuestion (String)
    • Output: The inserted valid value is returned as a double.
  • askForInputInt (int)
    • Description: Repeatedly asks the user for input, verifies the input is valid, and only returns the value when it is valid.
    • Expected Input: inputQuestion (String)
    • Output: The inserted valid value is returned as integer.
  • processValue (Boolean)
    • Description: retrieves the species name set for this object.
    • Expected Input: value (String); type (String).
    • Output: Boolean.

The Program Itself

Now that we have our object classes up and running, it’s time to work on the actual program. We start by presenting the user an introduction:

And then set up the species objects for both cats and mice:

The program proceeds to request an input for three variables: initial number of mice, growth rate for mice per year, and initial number of cats. If the user chose to have some number of cats that is not zero, the program will ask for the growth rate of cats per year and the number of mice each cat eats per week.

It’s worth noting that there is a difference in timing between the number of cats eaten (per week) and the growth rate of both populations (per year). This made the calculations a bit more elaborate (though much more fun, too, as you’ll see later in the code.)

The inputs are requested by invoking the askForInputInt and askForInputDouble methods, which verify the validity of the input and return its numerical value. They will continue asking for input from the user until the input is found to be valid. (For an updated version of these inputs as a standalone validation class, check out my Java User Input Validation tutorial)

Setting up the Calculation (or: Math! AAAA!)

If you dislike math, and the ‘or’ applies to you, the first step to take here is taking a breath and following the good ol’ concept: Don’t Panic.

Whatever initial values were given, the final result will involve large numbers that cannot be stored in an Integer type. As a result, the code will deal with BigDecimals to make sure the mathematical calculations can be processed. (As mentioned above, you should also be able to achieve this by using floats, but I chose to be messier for the sake of better accuracy)

initMice and initCats are transformed into BigDecimal values, and stored in the objects:

After collecting the inputs the program proceeds in a ‘do’ loop to calculate the eaten mice per week, and growth of the populations of mice and cats per year.

The loop is fairly simple. In each iteration, the area made by the number of mice is compared to the area of Central Park. The loop will proceed as long as the area of the mice is smaller than that of Central Park, or until all mice were eaten by cats, and there are no more mice left:

The Calculation Loop

Since each cat eats certain amount of mice per week, and yet both population growth happen per year, it’s more than reasonable that there will be no more mice left to increase after 52 weeks of being eaten by cats. The code must continuously make sure there are mice left, and also that the number of mice do not go over the area allowed.

Each loop iteration represents one week. It begins by retrieving the current number of mice and cats, and uses that data to calculate how many mice were eaten this week:

Then, it calculates the current area made by the new population of mice:

This miceArea variable is the one used by the loop to decide if another iteration should happen.

Now we must account for population growth. The above code is run every week, but we must also make sure that the populations of mice and cats grow exponentially once a year, based on their prospective growth factors.

We do this by checking if the number of weeks is divisible by 52, as there are 52 weeks per year:

Early in the programming process I realized another potential issue: since the population growth is exponential, and my program checks this growth once a year, there may be a good chance that the area created by the mice will suddenly grow beyond that of Central Park.

There are two ways of solving this issue. First, you can redo the calculation loop to calculate the relative growth of mice and cats per week (and that is definitely possible, but requires another calculation) or, you can do what I did, which was first check if the next year’s population is acceptable, and if it is not, ignore it and count up to the current year. It might be a cop-out, but considering I went above and beyond the requirements of the initial project, I deemed it acceptable. If you want to practice your skills, you can try adjusting the loop to do the first suggested solution.

So, back to the calculation of species growth. The cat population will grow regardless (they don’t have natural predators in this program) but the mice population will first be tested, so we insert it to temporary variables called “testPopulation” and “testPopArea“:

If the mice population after the yearly increase is larger than the area of central park, the code will ignore the new increase and exit to show the output. If it’s smaller than central park, the code will save the new population into the Mice object and continue counting.

See? Problem solved. Not ideal, but hey – it works.

The loop will now check the value of miceArea  and micePopulation. If miceArea is bigger or equals to the area of Central Park, or if micePopulation is zero (no more mice) the loop will end.

Printing the Result

There are two options for a result – either there were enough mice left to cover Central Park, or all mice were eaten. The final section of the code checks for exactly that, and returns the proper response:

And there you have it. Either mice covered Central Park, or there were lots of really fat cats.

Output

Welcome to ‘Mice Fill Central Park’.

====================================

How many mice would you like to start with?

1000

What is the percentage of growth of mice per year?

50

How many cats would you like to start with?

1

What is the percentage of growth of cats per year?

100

How many mice would each cat eat per week?

1

Calculating…

Result:

Could not fill up Central Park, because all mice were eaten within 319 weeks. At that time, there were 128 cats.

Done.

Or, another option:

Welcome to ‘Mice Fill Central Park’.

====================================

How many mice would you like to start with?

10000

What is the percentage of growth of mice per year?

50

How many cats would you like to start with?

5

What is the percentage of growth of cats per year?

10

How many mice would each cat eat per week?

1

Calculating…

Result:

After 1924 weeks (about 37 years), there will be 30403592887 mice that will fill up central park.

The mice take an area of 30403592.887sq feet of Central Park. There are 187 cats.

The Full Code

Please note: You are free to use this class in your code, as long as you keep the attribution and copyright notice. If you improve it, send it back to me and I’ll make sure to credit your improvements in the live version!

SpeciesGrowth.java

 

MiceFillCentralPark.java

 

Tags: ,

Trackback from your site.

Leave a comment