Source of SpeciesThirdTry.java


  1: 
  2: import java.util.*;
  3: 
  4: public class SpeciesThirdTry
  5: {
  6:     private String name;
  7:     private int population;
  8:     private double growthRate;
  9: 
 10:     public void readInput( )
 11:     {
 12:         Scanner keyboard = new Scanner(System.in);
 13:         System.out.println("What is the species' name?");
 14:         name = keyboard.nextLine( );
 15: 
 16:         System.out.println("What is the population of the species?");
 17:         population = keyboard.nextInt( );
 18:         while (population < 0)
 19:         {
 20:             System.out.println("Population cannot be negative.");
 21:             System.out.println("Reenter population:");
 22:             population = keyboard.nextInt( );
 23:         }
 24: 
 25:         System.out.println(
 26:                       "Enter growth rate (percent increase per year):");
 27:         growthRate = keyboard.nextDouble( );
 28:     }
 29: 
 30:     public void writeOutput( )
 31:     {
 32:          System.out.println("Name = " + name);
 33:          System.out.println("Population = " + population);
 34:          System.out.println("Growth rate = " + growthRate + "%");
 35:     }
 36: 
 37:     /**
 38:      Precondition: years is a nonnegative number.
 39:      Returns the projected population of the calling object
 40:      after the specified number of years.
 41:     */
 42:     public int projectedPopulation(int years)
 43:     {
 44:         double populationAmount = population;
 45:         int count = years;
 46:         while ((count > 0) && (populationAmount > 0))
 47:         {
 48:             populationAmount = (populationAmount +
 49:                           (growthRate/100) * populationAmount);
 50:             count--;
 51:         }
 52:         if (populationAmount > 0)
 53:             return (int)populationAmount;
 54:         else
 55:             return 0;
 56:     }
 57: }