Population projection

The problem

The U.S. Census Bureau projects population based on the following assumptions:

  • One birth every 7 seconds
  • One death every 13 seconds
  • One new immigrant every 45 seconds

For this lesson write a program to display the population for each of the next five years. Assume the current population is 312,032,486 and one year has 365 days. Hint: In Java, if two integers perform division, the result is an integer. The fraction part is truncated. For example, 5 / 4 is 1 (not 1.25) and 10 / 4 is 2 (not 2.5).

Breaking it down

Representing the number of years we will use java 8 to create a range of numbers then use a forEach to iterate through the elements. Within the java 8 function the yearly population will be calculated by adding the births, immigrants and base population while subtracting the number of deaths. Finally formatting and outputting the results.

private static double BIRTH_RATE_IN_SECONDS = 7.0;
private static double DEATH_RATE_IN_SECONDS = 13.0;
private static double NEW_IMMIGRANTS_IN_SECONDS = 45.0;
private static double CURRENT_POPULATION = 312032486;
private static double SECONDS_IN_YEAR = 60 * 60 * 24 * 365;

public static void main(String[] strings) {

    double numBirths = SECONDS_IN_YEAR / BIRTH_RATE_IN_SECONDS;
    double numDeaths = SECONDS_IN_YEAR / DEATH_RATE_IN_SECONDS;
    double numImmigrants = SECONDS_IN_YEAR / NEW_IMMIGRANTS_IN_SECONDS;

    IntStream.rangeClosed(1, 5)
            .forEach(
                    i -> {
                        CURRENT_POPULATION += numBirths + numImmigrants
                                * numDeaths;
                        System.out.printf(
                                "Year %d %d" + System.lineSeparator(), i,
                                (int) CURRENT_POPULATION);
                    });
}

Output

Year 1 314812582 
Year 2 317592679 
Year 3 320372776 
Year 4 323152872 
Year 5 325932969