Question: I'm writing a recursive method for population growth and need the results to be like this: (I've added the code I currently have) Example: Starting
I'm writing a recursive method for population growth and need the results to be like this: (I've added the code I currently have)
Example: Starting with a population of 2, 50 percent increase each day for 7 days.
(E7 means 10 to the 7th power)
Day Population ----------------------------- 1 2.0 2 102.0 3 5202.0 4 265302.0 5 1.3530402E7 6 6.90050502E8 7 3.5192575602E10
package assign6;
/** * * */ /** * The java program that test the recursive method populationSize * that prints numberOfDays and population and finally prints the total population. * */ //Recursion.java import java.util.Scanner; public class Assign6 { public static void main(String[] args) {
//set vlaues int startingPopulation; double increaseRate; int numberOfDays; //create a scanner object Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the starting # of organisms: "); startingPopulation=keyboard.nextInt();
System.out.println("Enter the increase rate: "); increaseRate=keyboard.nextInt();
System.out.println("Enter the total number of Days: "); numberOfDays=keyboard.nextInt();
//call populationSize(startingPopulation,increaseRate,numberOfDays) int totalPopulation=populationSize(startingPopulation,increaseRate,numberOfDays); //print totalPopulation System.out.println(totalPopulation); } public static int populationSize(int startingPopulation, double increaseRate, int numberOfDays) { //Base conditon if(numberOfDays<1) { return startingPopulation; } else { //Set populationSize return value to startingPopulation startingPopulation=populationSize(startingPopulation, increaseRate, numberOfDays-1); //find the increaseRate int startingPopulation and store startingPopulation startingPopulation=(int) (startingPopulation+startingPopulation*increaseRate); //print Day and population System.out.println("Day " + numberOfDays + " Population = " + startingPopulation); } //return startingPopulation return startingPopulation; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
