Contents

  1. ./Chicken.java
  2. ./Farm2.java
  3. ./Farm.java
  4. ./ParameterPassingDemo1.java
  5. ./ParameterPassingDemo2.java
  6. ./TemperatureTable.java

./Chicken.java 1/6

[
top][prev][next]
/**
 * A Java class that represents a chicken. The state of the chicken is
 * its name, height and weight.  There is also a static variable
 * representing the name of the farm that the Chickens are on.
 * 
 * @author Sara Sprenkle
 */
public class Chicken {

    // ------------ INSTANCE VARIABLES -------------------

    /** the name of the chicken */
    private String name;

    /** the height of the chicken in centimeters */
    private int height;

    /** the weight of the chicken in pounds */
    private double weight;


    // ------------ CLASS VARIABLES ------------------

    /** the name of the farm the chickens are on */
    public static String FARM = "McDonald";

    /** the amount of weight the chicken gains during feeding */
    private static double WEIGHT_GAIN = .3;

    /** the amount of height the chicken gains during feeding */
    private static int HEIGHT_GAIN = 1;
    
    /** the amount of weight difference we are okay with */
    public static double ERROR_TOLERANCE = .0001;


    /**
     * Create a new Chicken object with the charactistics as specified by the
     * parameters.
     * @param name the name of the chicken
     * @param height the height of the chicken in centimeters
     * @param weight the weight of the chicken in pounds
     */
    public Chicken(String name, int height, double weight) {
        this.name = name;
        this.height = height;
        this.weight = weight;
    }

    /**
     * Default name: "Bubba"; height and weight specified by parameters
     * @param height the height of the chicken in centimeters
     * @param weight the weight of the chicken in pounds
     */
    public Chicken(int height, double weight) {
        // if the user doesn't specify a name, let's make it Bubba
        this("Bubba", height, weight);
    }

    //
    // ----------- GETTER METHODS ------------
    // (also Accessor methods)

    /**
     * Returns the chicken's height, in centimeters
     * 
     * @return the height of the chicken, in centimeters
     */
    public int getHeight() {
        return this.height;
    }

    /**
     * Returns the chicken's weight, in pounds
     * 
     * @return the weight of the chicken, in pounds
     */
    public double getWeight() {
        return weight;
    }

    /**
     * Returns the chicken's name
     *
     * @return the name of the chicken
     */
    public String getName() {
        return name;
    }

    //
    // ------------- MUTATORS -----------
    //

    /**
     * Feeds the chicken, increasing the chicken's weight and height
     */
    public void feed() {
        weight += WEIGHT_GAIN;
        height += HEIGHT_GAIN;
    }

    //
    // ------------- SETTERS ----------
    //

    /**
     * Sets the name of the chicken
     * 
     * @param n the name of the chicken
     */
    public void setName(String n) {
        name = n;
    }

    /**
     * Sets the height of the chicken, in cm
     * 
     * @param h the height of the chicken, in cm
     */
    public void setHeight(int h) {
        height = h;
    }

    /**
     * Sets the weight of the chicken, in pounds
     * 
     * @param w the weight of the chicken, in pounds
     */
    public void setWeight(double w) {
        weight = w;
    }

    /**
     * Returns a string representation of the chicken.
     * Format:
     * <br/>Chicken name: &lt;name&gt;
     * <br/>weight: &lt;weight&gt; pounds
     * <br/>height: &lt;height&gt; cm
     * <p>Weight is displayed to one decimal place
     * @return a string representation of this Chicken
     */
    @Override
    public String toString() {
        StringBuffer rep = new StringBuffer("Chicken name: ");
        rep.append(name);
        rep.append("\nweight: ");
        rep.append(String.format("%.1f", weight));
        rep.append(" pounds");
        rep.append("\nheight: ");
        rep.append(height);
        rep.append(" cm");
        return rep.toString();
    }

    /**
     * Determines if the Object o is equivalent to this Chicken, 
     * based on their name, height, and weight.
     * @param o the object to compare
     * @return true if this object is the same as the o argument (by name, height, and wight).  Otherwise, returns false. 
     */
    @Override
    public boolean equals(Object o) {
        // Follows the _Effective Java_ process
        if( o == this ) {
            return true;
        }

        if( ! ( o instanceof Chicken ) ) {
            return false;
        }

        Chicken other = (Chicken) o;

        if( ! other.getName().equals(this.getName() ) ) {
            return false;
        }
        // if other.height != this.height 
        if( other.getHeight() != this.getHeight() ) {
            return false;
        }

        // This could be trouble; need to make sure the difference is within reason.
        if( Double.compare( other.getWeight(), this.getWeight()) == 0 ) {
            return true;
        }
        
        double difference = this.getWeight() - this.getWeight();
        if( difference > ERROR_TOLERANCE ) {
            return false;   
        }

        return true;

    }

    /**
     * @param args
     *            the command-line arguments
     */
    public static void main(String[] args) {
        int fredHeight = 38;
        Chicken chicken = new Chicken("Fred", fredHeight, 2.0);

        System.out.println(chicken);

        if( chicken.getHeight() != fredHeight ) {
            System.err.println("Problem likely in constructor setting height");
        }
        if( !chicken.getName().equals("Fred") ) {
            System.err.println("Problem likely in constructor setting name");
        }

        chicken.feed();

        int newFredHeight = chicken.getHeight();
        System.out.println(chicken.getName() + " is now " + newFredHeight +
                           " cm tall.");

        chicken.feed();

        System.out.println("He's a growing boy at " + chicken.getHeight() + " cm tall and " + chicken.getWeight() + " pounds");

        String expectedRep = "Chicken name: Fred\nweight: 2.6 pounds\nheight: 40 cm";
        String actualRep = chicken.toString();

        // Demonstrates trickiness with testing with doubles
        if( ! actualRep.equals(expectedRep) ) {
            System.err.println("Problem in toString");
            System.err.println("\tActual: " + actualRep);
            System.err.println("\tExpected: " + expectedRep);
        }

        Chicken trivialMatch = chicken;

        if( ! chicken.equals(trivialMatch) ) {
            System.err.println("Problem in equals");
            System.err.println("\tActual: " + chicken.equals(trivialMatch) );
            System.err.println("\tExpected: " + true);
        }

        Chicken grownFred = new Chicken("Fred", 40, 2.6);
        // This doesn't work -- again issue with comparing doubles
        if( ! chicken.equals(grownFred) ) {
            System.err.println("Problem in equals");
            System.err.println("\tActual: " + chicken.equals(grownFred) );
            System.err.println("\tExpected: " + true);
        }


        // ---- creating tests for chickens -----

        String[] names = {"Rocky", "Baby Chicken"};
        double[] weights = {4.0, .8};
        int[] heights = {50, 4};

        for( int i=0; i < names.length; i++ ) {
            Chicken thisChicken = new Chicken( names[i], heights[i], weights[i] );

            if( !thisChicken.getName().equals(names[i]) ) {
                System.err.println("Problem likely in constructor setting name");
                System.err.println("\tActual: " + thisChicken.getName());
                System.err.println("\tExpected: " + names[i]);
            }


            if( thisChicken.getWeight() != weights[i] ) {
                System.err.println("\tError in getWeight for Chicken " + i );
                System.err.println("\tActual: " + thisChicken.getWeight());
                System.err.println("\tExpected: " + weights[i] );
            }

            // feed the chicken and check the state
            thisChicken.feed();
            if( thisChicken.getWeight() != weights[i] + WEIGHT_GAIN ) {
                System.err.println("Error in feed weight for Chicken " + i);
                System.err.println("\tActual: " + thisChicken.getWeight());
                System.err.println("\tExpected: " + (weights[i] + WEIGHT_GAIN) );
            }

            if( thisChicken.getHeight() != heights[i] + HEIGHT_GAIN ) {
                System.err.println("Error in feed height for Chicken " + i);
                System.err.println("\tActual: " + thisChicken.getHeight());
                System.err.println("\tExpected: " + (heights[i] + HEIGHT_GAIN) );
            }

            // feed the chicken again and check the state

            thisChicken.feed();

            // NOTE: this test may fail, but tried to address by giving some
            // error tolerance on the weight
            double expectedWeight2 = weights[i] + 2 * WEIGHT_GAIN;
            int comparison = Double.compare(thisChicken.getWeight(),  expectedWeight2 );
            if( comparison != 0 ) {
                if( thisChicken.getWeight() - expectedWeight2 > ERROR_TOLERANCE ) {
                    System.err.println("Error in second feed weight for Chicken " + i);
                    System.err.println("\tActual: " + thisChicken.getWeight());
                    System.err.println("\tExpected: " + (expectedWeight2 ));
                }
            }

            if( thisChicken.getHeight() != heights[i] + 2 * HEIGHT_GAIN ) {
                System.err.println("Error in second feed height for Chicken " + i);
                System.err.println("\tActual: " + thisChicken.getHeight());
                System.err.println("\tExpected: " + (heights[i] + 2 * HEIGHT_GAIN ));
            }

            // TODO: test setName method
        }

    }
}

./Farm2.java 2/6

[
top][prev][next]
/**
 * Represents a Farm (poorly).  Primarly used to demonstrate pass by value
 * @author CSCI209
 */
public class Farm2 {

    private String name;

    public Farm2(String name) {
        this.name = name;
    }

    /**
     * c copies the value of the variable passed into the method.
     * When c is then assigned to a _new_ Chicken object, c now refers to 
     * a new address.  The original variable passed in does not change,
     * so updates to the new Chicken object do not affect the original 
     * Chicken object passed in.
     */
    public void feedChicken(Chicken c) {
        c = new Chicken(c.getName(), c.getWeight(),
                        c.getHeight() );
        c.setWeight( c.getWeight() + .5);
    }

    public static void main(String[] args) {
        Farm2 farm = new Farm2("OldMac");
        Chicken sal = new Chicken("Sallie Mae", 5, 23.2);
        System.out.println(sal.getWeight());
        farm.feedChicken(sal);
        // sal is not affected
        System.out.println(sal.getWeight());
    }

}

./Farm.java 3/6

[
top][prev][next]
/**
 * Represents a Farm (poorly).  Primarly used to demonstrate pass by value
 * @author CSCI209
 */
public class Farm {

    private String name;

    public Farm(String name) {
        this.name = name;
    }

    /**
     * c copies the value of the variable passed into the method
     * so the Chicken object that is referenced by c will be
     * changed after this method returns.
     */
    public void feedChicken(Chicken c) {
        c.setWeight( c.getWeight() + .5 );
    }

    public static void main(String[] args) {
        Farm farm = new Farm("OldMac");
        Chicken sal = new Chicken("Sallie Mae", 5, 23.2);
        System.out.println(sal.getWeight());
        farm.feedChicken(sal);
        // weight of Sal will be higher.
        System.out.println(sal.getWeight());
    }

}

./ParameterPassingDemo1.java 4/6

[
top][prev][next]
/**
 * Demonstrating Pass By Value with a primitive type
 * @author CSCI209
 */
public class ParameterPassingDemo1 {
    public static void main(String[] args) {
        int x = 10;
        int squared = square(x);
        System.out.println("The square of " + x + " is " +     squared);
    }

    /**
     * num copies the value of the parameter passed into the method
     */
    public static int square(int num) {
        return num*=num;
    }
}

./ParameterPassingDemo2.java 5/6

[
top][prev][next]
/**
 * Demonstrates Pass By Value with a primitive type
 * @author CSCI209
 */
public class ParameterPassingDemo2 {
    
    public static void main(String[] args) {
        int x = 27;
        System.out.println(x);
        doubleValue(x);
        // x does not get changed by calling doubleValue
        System.out.println(x);
    }
    
    /**
     * p copies the value passed into the method
     */
    public static void doubleValue(int p) {
        p = p * 2;
    }
}

./TemperatureTable.java 6/6

[
top][prev][next]

/**
 * Format a table of temperature conversions, using String format and System.out.printf
 *
 * @author CSCI209
 */
public class TemperatureTable {

    public static void main(String[] args) {
	String headingFormat = "%10s %10s %10s";

	String headings = String.format(headingFormat, "Temp C", "Temp F", "Temp K");
	String lines = String.format(headingFormat, "------", "------", "------");

	System.out.println(headings);
	System.out.println(lines);

	double[] temps = {-459.7, -273.1, 0.0};

	String tempFormat = "%10.1f %10.1f %10.1f";
	
	// better to have the values calculated rather than hardcoded.

	// Using String.format
	System.out.println(String.format(tempFormat, temps[0], temps[1], temps[2]));

	// Alternatively: using System.out.printf
	System.out.printf(tempFormat + "\n", temps[0], temps[1], temps[2]);

	double[] temps2 = {0.0, -17.8, 255.4};

	System.out.println(String.format(tempFormat, temps2[0], temps2[1], temps2[2]));


	double[] temps3 = { 32.0, 0.0, 273.1};

	System.out.println(String.format(tempFormat, temps3[0], temps3[1], temps3[2]));

	// Including \n in the template string
	tempFormat = tempFormat + "\n";
	System.out.printf(tempFormat, temps3[0], temps3[1], temps3[2]);
	

    }
    
}

Generated by GNU Enscript 1.6.6.