Create a text file named petstxt with 10 pets The format is

Create a text file named “pets.txt” with 10 pets. The format is the same format used in the original homework problem. Each line in the file should contain:

·        pet name (String)

·        comma

·        pet’s age (int) in years

·        comma

·        pet’s weight (double) in pounds

Using the classes from the following PetRecord.java program:

Perform the following operations in the sequence given below:

1.      Create a driver program in a separate source file which contains the main() method.

2.      Declare and create an array of 10 PetRecord objects

3.      Open the “pets.txt” file (stored in the same file as your programs’ “class” files)

4.      Read each line in the file, instantiate a PetRecord object, and assign to the next unused element in the array of PetRecord objects.

5.      Close the “pets.txt” file

6.      Print a report showing the name, weight, and age of all of the pets in the array:

a.      Do not use the toString() method in PetRecord.

b.      Format the report using nicely-aligned columns,

i.      The pet names should all be left-aligned

ii.      The weights and ages of the pets should all be right-aligned.

iii.      The weights should be displayed to 1 decimal point to the right

7.      Determine and print the name and weight of the heaviest pet and the oldest pet

8.      Determine and print the name of the pet with the longest name

Do not determine or print any of the information requested in steps 6, 7, or 8 as you are reading in the data. These must be determined and printed only after all pets have been read from the file and placed into the array.

Also, don’t make any changes to the PetRecord class. You may create as many methods in your driver program as you wish.

Solution


public class PetRecord
{
    // Instance variables
    private String name;
    private int age;             //in years
    private double weight;       //in pounds

    // Default values for instance variables
    private static final String DEFAULT_NAME = \"No name yet.\" ;
    private static final int DEFAULT_AGE = -1 ;
    private static final double DEFAULT_WEIGHT = -1.0 ;

   /***************************************************
    * Constructors to create objects of type PetRecord
    ***************************************************/

    // no-argument constructor
    public PetRecord( )
    {
        this(DEFAULT_NAME, DEFAULT_AGE, DEFAULT_WEIGHT) ;
    }
    // only name provided
    public PetRecord(String initialName)
    {
        this(initialName, DEFAULT_AGE, DEFAULT_WEIGHT) ;
    }
    // only age provided
    public PetRecord(int initialAge)
    {
        this(DEFAULT_NAME, initialAge, DEFAULT_WEIGHT) ;
    }
    // only weight provided
    public PetRecord(double initialWeight)
    {
        this(DEFAULT_NAME, DEFAULT_AGE, initialWeight) ;
    }
    // full constructor (all three instance variables provided)
    public PetRecord(String initialName, int initialAge, double initialWeight)
    {
        setName(initialName) ;
        setAge(initialAge) ;
        setWeight(initialWeight) ;
    }

   /****************************************************************
    * Mutators and setters to update the Pet. Setters for age and
    * weight validate reasonable weights are specified
    ****************************************************************/

    // Mutator that sets all instance variables
    public void set(String newName, int newAge, double newWeight)
    {
        setName(newName) ;
        setAge(newAge) ;
        setWeight(newWeight) ;
    }

    // Setters for each instance variable (validate age and weight)
    public void setName(String newName)
    {
        name = newName;
    }
    public void setAge(int newAge)
    {
        if ((newAge < 0) && (newAge != DEFAULT_AGE))
        {
            System.out.println(\"Error: Invalid age.\");
            System.exit(99);
        }
        age = newAge;
    }
    public void setWeight(double newWeight)
    {
        if ((newWeight < 0.0) && (newWeight != DEFAULT_WEIGHT))
        {
            System.out.println(\"Error: Invalid weight.\");
            System.exit(98);
        }
        weight = newWeight;
    }

   /************************************
    * getters for name, age, and weight
    ************************************/
    public String getName( )
    {
        return name;
    }
    public int getAge( )
    {
        return age;
    }
    public double getWeight( )
    {
        return weight;
    }

   /****************************************************
    * toString() shows the pet\'s name, age, and weight
    * equals() compares all three instance variables
    ****************************************************/
    public String toString( )
    {
        return (\"Name: \" + name + \" Age: \" + age + \" years\"
                       + \"   Weight: \" + weight + \" pounds\");
    }
    public boolean equals(PetRecord anotherPetRecord)
    {
        if (anotherPetRecord == null)
        {
            return false ;
        }
        return ((this.getName().equals(anotherPetRecord.getName())) &&
                (this.getAge() == anotherPetRecord.getAge()) &&
                (this.getWeight() == anotherPetRecord.getWeight())) ;
    }
}

--------------------------------------------------------------------------------------------

//Test java program that reads the pets.txt file
//and print the pet records to console. and then
//find the pet with max weight and pet with longest name
//PetDriver.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class PetDriver {

   public static void main(String[] args) {


       String fileName=\"pets.txt\";
       Scanner filescanner=null;
       final int SIZE=10;
       //create an array of PetRecord type
       PetRecord[] pets=new PetRecord[SIZE];
       String name;
       int age;
       double weight;
       String line;
       int index=0;

       try
       {
           //create an instance of the filescanner with File class
           filescanner=new Scanner(new File(fileName));

           //read until end of file
           while(filescanner.hasNextLine())
           {
               line=filescanner.nextLine();
               String[] data=line.split(\",\");

               //read name,age and weight
               name=data[0];
               age=Integer.parseInt(data[1]);
               weight=Double.parseDouble(data[2]);

               //Create an instance of PetRecord class with name, age and weight
               pets[index]=new PetRecord(name, age, weight);
               index++;              
           }

           filescanner.close();          
       }
       catch (FileNotFoundException e)
       {
           System.out.println(e.getMessage());
       }

       System.out.printf(\"%-10s%10s%10s\ \",
               \"Name\",
               \"Age\",
               \"Weight\");
       System.out.printf(\"-----------------------------\ \");
       //print name, age and weight aligned
       for (PetRecord petRecord : pets)
       {
           System.out.printf(\"%-10s%10d%10.1f\ \",
                   petRecord.getName(),
                   petRecord.getAge(),
                   petRecord.getWeight());
       }

       //assume that starting pet\'s weight is heaviest
       double maxWeight=pets[0].getWeight();
       int maxWtIndex=0;

       for (int i = 1; i < pets.length; i++)
       {
           if(pets[i].getWeight()>maxWeight)
               maxWtIndex=i;
       }

       System.out.println(\"Maximum Weight Pet and its weight\");
       System.out.println(\"Name : \"+pets[maxWtIndex].getName());
       System.out.println(\"Weight : \"+pets[maxWtIndex].getWeight());
       //assume that first name is longest
       String longestName=pets[0].getName();
       int longestNameIndex=0;

       for (int i = 1; i < pets.length; i++)
       {
           if(pets[i].getName().length()>longestName.length())
           {
               longestNameIndex=i;
           }
       }
       System.out.println(\"Longest Pet name\");
       System.out.println(\"Name : \"+pets[longestNameIndex].getName());      
   }
}

--------------------------------------------------------------------------------------------

pets.txt

peacock,2,40
hen,1,10
pegion,1,5
duck,2,15
cat,4,35
rat,2,5
mouse,2,10
dog,5,40
horse,4,100
chick,1,20

--------------------------------------------------------------------------------------------

Name             Age    Weight
-----------------------------
peacock            2      40.0
hen                1      10.0
pegion             1       5.0
duck               2      15.0
cat                4      35.0
rat                2       5.0
mouse              2      10.0
dog                5      40.0
horse              4     100.0
chick              1      20.0
Maximum Weight Pet and its weight
Name : horse
Weight : 100.0
Longest Pet name
Name : peacock

Create a text file named “pets.txt” with 10 pets. The format is the same format used in the original homework problem. Each line in the file should contain: · p
Create a text file named “pets.txt” with 10 pets. The format is the same format used in the original homework problem. Each line in the file should contain: · p
Create a text file named “pets.txt” with 10 pets. The format is the same format used in the original homework problem. Each line in the file should contain: · p
Create a text file named “pets.txt” with 10 pets. The format is the same format used in the original homework problem. Each line in the file should contain: · p
Create a text file named “pets.txt” with 10 pets. The format is the same format used in the original homework problem. Each line in the file should contain: · p

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site