Source of SpeciesFourthTry.java


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