Source of SpeciesFourthTry.java


  1: //SpeciesFourthTry.java
  2: 
  3: import java.util.Scanner;
  4: 
  5: public class SpeciesFourthTry
  6: {
  7:     private String name;
  8:     private int population;
  9:     private double growthRate;
 10: 
 11:     public void readInput()
 12:     {
 13:         Scanner keyboard = new Scanner(System.in);
 14:         System.out.println("What is the species' name?");
 15:         name = keyboard.nextLine();
 16: 
 17:         System.out.println("What is the population of the species?");
 18:         keyboard = new Scanner(System.in);
 19:         population = keyboard.nextInt();
 20: 
 21:         System.out.println("Enter growth rate (% increase per year):");
 22:         growthRate = keyboard.nextDouble();
 23:     }
 24: 
 25:     public void writeOutput()
 26:     {
 27:         System.out.println("Name = " + name);
 28:         System.out.println("Population = " + population);
 29:         System.out.println("Growth rate = " + growthRate + "%");
 30:     }
 31: 
 32:     /**
 33:      * Precondition: years is a nonnegative number.
 34:      * Returns the projected population of the calling object
 35:      * after the specified number of years.
 36:      */
 37:     public int predictPopulation
 38:     (
 39:         int years
 40:     )
 41:     {
 42:         int result = 0;
 43:         double populationAmount = population;
 44:         int count = years;
 45:         while ((count > 0) && (populationAmount > 0))
 46:         {
 47:             populationAmount =
 48:                 (populationAmount + (growthRate / 100) * populationAmount);
 49:             count--;
 50:         }
 51:         if (populationAmount > 0)
 52:             result = (int)populationAmount;
 53: 
 54:         return result;
 55:     }
 56: 
 57:     public void setSpecies
 58:     (
 59:         String newName,
 60:         int newPopulation,
 61:         double newGrowthRate
 62:     )
 63:     {
 64:         name = newName;
 65:         if (newPopulation >= 0)
 66:             population = newPopulation;
 67:         else
 68:         {
 69:             System.out.println("ERROR: using a negative population.");
 70:             System.exit(0);
 71:         }
 72:         growthRate = newGrowthRate;
 73:     }
 74: 
 75:     public String getName()
 76:     {
 77:         return name;
 78:     }
 79: 
 80:     public int getPopulation()
 81:     {
 82:         return population;
 83:     }
 84: 
 85:     public double getGrowthRate()
 86:     {
 87:         return growthRate;
 88:     }
 89: }