// File: Herbivore.java from the package edu.colorado.simulations // Complete documentation is available from the Herbivore link in // http://www.cs.colorado.edu/~main/docs / package edu.colorado.simulations; /****************************************************************************** * A Herbivore is an Animal with extra methods that * allow it to eat Plant objects. * * Java Source Code for this class: * * http://www.cs.colorado.edu/~main/edu/colorado/simulations/Herbivore.java * * * @author Michael Main * (main@colorado.edu) * * @version Feb 10, 2016 * * @see Animal * @see Plant ******************************************************************************/ public class Herbivore extends Animal { /** * Construct an Herbivore with a specified size, growth rate, and * weekly eating need. * @param initSize * the initial size of this Herbivore, in ounces * @param initRate * the initial growth rate of this Herbivore, in ounces * @param initNeed * the initial weekly eating requirement of this Animal, in * ounces per week * Precondition: * initSize >= 0 and initNeed >= 0. * Also, if initSize is zero, then * initRate must also be zero. * Postcondition: * This Herbivore has been initialized. The value returned from * getSize() is now initSize, the value * returned from getRate() is now initRate, and * this Herbivore must eat at least initNeed ounces * of food each week to survive. * @exception IllegalArgumentException * Indicates that initSize, initRate, or * initNeed violates the precondition. **/ public Herbivore(double initSize, double initRate, double initNeed) { super(initSize, initRate, initNeed); } /** * Have this Herbivore eat part of a Plant. * @param meal * the Plant that will be partly eaten * Postcondition: * Part of the Plant has been eaten by this Herbivore, * by activating both eat(amount) and * meal.nibbledOn(amount). The amount is usually * half of the Plant, but it will not be more than 10% of * this Herbivore’s weekly need nor more than the amount that * this Herbivore still needs to eat to survive this week. **/ public void nibble(Plant meal) { final double PORTION = 0.5; // Eat no more than this portion of plant final double MAX_FRACTION = 0.1; // Eat no more than this fraction of weekly need double amount; // How many ounces of the plant will be eaten // Set amount to some portion of the plant, but no more than a given // maximum fraction of the total weekly need, and no more than what the // herbivore still needs to eat this week. amount = PORTION * meal.getSize( ); if (amount > MAX_FRACTION * getNeed( )) amount = MAX_FRACTION * getNeed( ); if (amount > stillNeed( )) amount = stillNeed( ); // Eat the plant eat(amount); meal.nibbledOn(amount); } }