Arraylist

Horse


/*

 * Activity 3.7.3

 */

import java.util.ArrayList;

import java.util.Scanner;

import java.io.File;


/**

 *  A class to manage the location of horses in a barn.

 */

public class HorseBarn

{

  // The stalls or spaces in the barn. Each array element holds a reference to the horse

  // that is currently occupying the space.  A null value indicates an empty space.

  private ArrayList<Horse> spaces = new ArrayList<Horse>();


  /**

   * Constructor for the HorseBarn class. Loads data from the horsedata.txt file

   * and populates the ArrayList spaces. If a blank line occurs in the data file,

   * the array element is assigned a value of null to indicate the absense of a horse.

   */

  public HorseBarn()

  {

    // a try is like an if statement, "throwing" an error if the body of the try fails

    try

    {

      Scanner sc = new Scanner(new File("horsedata.txt"));

      // The Scanner method hasNextLine returns true if there is

      // another line of input

      while (sc.hasNextLine())

      {

        // String method trim removes whitepsace from the beginning

        // and end of strings

        String temp = sc.nextLine().trim();

        if (temp.equals(""))

        {

          // no horse in this stall, add a null entry

          spaces.add(null);

        }

        else

        {  

          // String method split splits this string based on the

          // specified token and returns an array of individual substrings

          String[] tokens = temp.split(",");  

          String name = tokens[0];

          int  weight = Integer.parseInt(tokens[1]);

         

          // add the horse to the array list

          spaces.add(new Horse(name, weight));

        }

      }

    } catch (Exception e) { System.out.println("Error reading or parsing horsedata.txt" + e); }

  }


  /**

   * Returns the current list of spaces in the barn. If a space does not

   * have a horse in it, the element will be null.

   *

   * @return the ArrayList of spaces

   */

  public ArrayList<Horse> getSpaces()

  {

    return spaces;

  }

}



HorseBarn

/*

 * Activity 3.7.3

 */

import java.util.ArrayList;

import java.util.Scanner;

import java.io.File;


/**

 *  A class to manage the location of horses in a barn.

 */

public class HorseBarn

{

  // The stalls or spaces in the barn. Each array element holds a reference to the horse

  // that is currently occupying the space.  A null value indicates an empty space.

  private ArrayList<Horse> spaces = new ArrayList<Horse>();


  /**

   * Constructor for the HorseBarn class. Loads data from the horsedata.txt file

   * and populates the ArrayList spaces. If a blank line occurs in the data file,

   * the array element is assigned a value of null to indicate the absense of a horse.

   */

  public HorseBarn()

  {

    // a try is like an if statement, "throwing" an error if the body of the try fails

    try

    {

      Scanner sc = new Scanner(new File("horsedata.txt"));

      // The Scanner method hasNextLine returns true if there is

      // another line of input

      while (sc.hasNextLine())

      {

        // String method trim removes whitepsace from the beginning

        // and end of strings

        String temp = sc.nextLine().trim();

        if (temp.equals(""))

        {

          // no horse in this stall, add a null entry

          spaces.add(null);

        }

        else

        {  

          // String method split splits this string based on the

          // specified token and returns an array of individual substrings

          String[] tokens = temp.split(",");  

          String name = tokens[0];

          int  weight = Integer.parseInt(tokens[1]);

         

          // add the horse to the array list

          spaces.add(new Horse(name, weight));

        }

      }

    } catch (Exception e) { System.out.println("Error reading or parsing horsedata.txt" + e); }

  }


  /**

   * Returns the current list of spaces in the barn. If a space does not

   * have a horse in it, the element will be null.

   *

   * @return the ArrayList of spaces

   */

  public ArrayList<Horse> getSpaces()

  {

    return spaces;

  }

}


Runner

/*

 * Activity 3.7.3

 */

import java.util.ArrayList;


 public class HorseBarnRunner

{

  public static void main(String[] args)

  {


    HorseBarn barn = new HorseBarn();

    ArrayList<Horse> barnSpaces = barn.getSpaces();

   


// 2a avg weight

System.out.println("2a:");

System.out.print("Average weight: ");

double totalWgt = 0.0;

for (Horse h : barnSpaces)

totalWgt += h.getWeight();

double avg = totalWgt / barnSpaces.size();

System.out.println(avg);


// 2b - avg weight Horses that are greater then avg

System.out.println("2b:");

 System.out.println("Greater than average weight: ");

    for (Horse h : barnSpaces)

      if(h.getWeight()> avg)

      System.out.println("" + h.getName() + ": " + h.getWeight());

      System.out.println();  



// 2c - Greatest and least

//for (Horse h : barnSpaces)

//System.out.println("    " + h.getName() + ": " + h.getWeight());

System.out.println("2c:");

Horse heaviest = barnSpaces.get(3);

Horse lightest =  barnSpaces.get(1);

int most = heaviest.getWeight();

int least = lightest.getWeight();

if (barnSpaces.size() > 1) {

  for (int i = 1; i < barnSpaces.size(); i++)

  {

    if (barnSpaces.get(i).getWeight() > most)

    {

      most = barnSpaces.get(i).getWeight();

      heaviest = barnSpaces.get(i);

    }

    if (barnSpaces.get(i).getWeight() < least)

    {

      least = barnSpaces.get(i).getWeight();

      lightest = barnSpaces.get(i);

    }

  }

}

System.out.println("The heaviest horse is: " + heaviest + " at " + heaviest.getWeight());

System.out.println("The Lightest horse is:  " + lightest + " at " + lightest.getWeight());



    // the test case in step 5c

    //if (barnSpaces.size() == 0)

    //{

    //  System.out.println("There are no horses in the barn.");

    //  return;

    //}

    //System.out.println(barn.getSpaces());

    //System.out.println(barnSpaces.size());


// horses that have the same weight (complete after 2)

System.out.println("Horses that weigh the same:");

for (int i = 0; i < barnSpaces.size(); i++)

{

  for (int j = i+1; j < barnSpaces.size(); j++)

  {

    if (barnSpaces.get(i).getWeight() ==

        barnSpaces.get(j).getWeight())

    System.out.println("  " + barnSpaces.get(i).getName() +

        " and " + barnSpaces.get(j).getName() + " at " +

        barnSpaces.get(i).getWeight() + " pounds");

  }

}


    // step 4

  /*  System.out.println("----- Horses in the barn ---------------");

    for (Horse h : barnSpaces)

    {

      // step 5 and 6: error ConcurrentModificationException, cannot change size of arraylist here

     

      if (h.getName().equals("Patches"))

        barnSpaces.remove(h);

     

      System.out.println(h);

    }

    */

    // step 7: error ArrayIndexOutOfBoundsException

   /* int numSpaces = barnSpaces.size();

    for (int i = 0; i < numSpaces; i++)

      {

        Horse h = barnSpaces.get(i);

        if (h.getName().equals("Patches"))

        System.out.println("Bye bye " +  barnSpaces.remove(i));

      }

   

   */

    // step 8 - 10: commented out to use the final version below

    /*****

    System.out.println("----- Horses in the barn ---------------");

    for (int i = 0; i < barnSpaces.size(); i++)

    {

      Horse h = barnSpaces.get(i);

      if (h.getName().equals("Lady"))

        System.out.println("Bye bye " +  barnSpaces.remove(i));

      // step 9

      else if (h.getName().equals("Patches"))

        System.out.println("Bye bye " +  barnSpaces.remove(i));

    }

    for (Horse h : barnSpaces)

      System.out.println(h);

    *****/

   

    // step 11 - 15: final version

    System.out.println("----- Horses in the barn ---------------");

    /***** for (int i = 0; i < barnSpaces.size(); i++) *****/

    int i = 0;

    while(i < barnSpaces.size())

    {

      Horse h = barnSpaces.get(i);

      if (h.getName().equals("Patches"))

      {

        System.out.println("Bye bye " + barnSpaces.remove(i));

        i--;

      }

      else if (h.getName().equals("Lady"))

      {

        System.out.println("Bye bye " + barnSpaces.remove(i));

        i--;

      }

      i++;

    }

 for (Horse h : barnSpaces)

   System.out.println("    " + h.getName() + ": " + h.getWeight());


}

}


HData.txt

Trigger,1340,M,8

Silver,1210,M,9

Lady,1575,F,5

Patches,1350,F,1

Duke,1410,M,4

Major,1495,M,7

Misty,1425,F,9

Gypsy,1335,M,12

Buddy,1340,M,6

Magic,1425,F,5

Autumn,1460,F,10

Spirit,1295,M,2

Princess,1445,F,3

Chief,1505,M,5

Actions

Remove 

enhanced for loop to remove an item:

      if (h.getName().equals("Patches"))

            barnSpaces.remove(h);


v2
int numSpaces = barnSpaces.size();
            for (int i = 0; i < numSpaces; i++)
            {
Horse h = barnSpaces.get(i);
if (h.getName().equals("Patches"))
System.out.println("Bye bye " +  barnSpaces.remove(i));
`     }