Question

(JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text...

(JAVA) Use the Pet.java program from the original problem (down below) Compile it.

Create a text file named pets10.txt with 10 pets (or use the one below). Store this file in the same folder as your “class” file(s). The format is the same format used in the original homework problem. Each line in the file should contain a pet name (String), a comma, a pet’s age (int) in years, another comma, and a pet’s weight (double) in pounds.

Perform the following operations in the sequence given below:

  1. Create a driver program in a separate source file which contains main
  2. Open the “txt” file
  3. Declare and create an array of 10 Pet elements
  4. Read each line in the file, instantiate a Pet object, and assign to the next unused element in the array of Pet
  5. Close the “txt” file
  6. Print a report showing the name, weight, and age of all of the pets in the array:
    1. Do not use the toString method in Pet.
    2. Instead, format the report using nicely-aligned columns,
      • The pet names should all be left-aligned
      • The weights and ages of the pets should all be right-aligned.
      • The weights should be displayed to 1 decimal point to the right
  7. Determine and print the name, weight, and age of the heaviest pet and the oldest pet. Use your toStringmethod to print this information.
  8. Determine and print the name of the pet with the longest name (use toString)

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.

Please don’t make any changes to the Pet class. You may create as many methods in your driver class as you wish.

When completed, submit a copy of:

  • Your driver program (must be separate from the Pet class)
  • Your “txt” file
  • The output from your program as a PrintScreen

You might consider this…

Use the following code to open your data file:

< above / outside of main, declare the following constant >

private static final String FILE_NAME = "pets10.txt" ;

< inside main >

FileInputStream inputStream = null;

try

{

input stream = new FileInputStream(FILE_NAME);

}

catch (FileNotFoundException e)

{

System.out.println("Can't find " + FILE_NAME + ", aborting. ");

System.exit(0);

}

Scanner petScanner = new Scanner(inputStream);

// Setup scanner and attach to the data file

When done reading the file, close the named input stream using:

  try
  {
     inputStream.close() ;  
  }
  catch (IOException e)
  {
  }

Loop through the text file using the following pseudocode:

declare and create an array of 10 Pets, but do NOT create Pet objects yet
loop through the ten pets in the pets10.txt file
create a new Pet object and assign to the next available element of the array
change delimiter of the scanner to a comma
read the name and age of the pet from the scanner and store in the Pet object
change delimiter to a comma / white space
read the weight of the pet and store in the object

public class Pet
{
// 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 Pet
***************************************************/

// no-argument constructor
public Pet( )
{
this(DEFAULT_NAME, DEFAULT_AGE, DEFAULT_WEIGHT) ;
}
// only name provided
public Pet(String initialName)
{
this(initialName, DEFAULT_AGE, DEFAULT_WEIGHT) ;
}
// only age provided
public Pet(int initialAge)
{
this(DEFAULT_NAME, initialAge, DEFAULT_WEIGHT) ;
}
// only weight provided
public Pet(double initialWeight)
{
this(DEFAULT_NAME, DEFAULT_AGE, initialWeight) ;
}
// full constructor (all three instance variables provided)
public Pet(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(Pet anotherPet)
{
if (anotherPet == null)
{
return false ;
}
return ((this.getName().equals(anotherPet.getName())) &&
(this.getAge() == anotherPet.getAge()) &&
(this.getWeight() == anotherPet.getWeight())) ;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Pet.java

public class Pet {
  
   // 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 Pet
   ***************************************************/

   // no-argument constructor
   public Pet( )
   {
   this(DEFAULT_NAME, DEFAULT_AGE, DEFAULT_WEIGHT) ;
   }
  
   // only name provided
   public Pet(String initialName)
   {
   this(initialName, DEFAULT_AGE, DEFAULT_WEIGHT) ;
   }
   // only age provided
   public Pet(int initialAge)
   {
   this(DEFAULT_NAME, initialAge, DEFAULT_WEIGHT) ;
   }
   // only weight provided
   public Pet(double initialWeight)
   {
   this(DEFAULT_NAME, DEFAULT_AGE, initialWeight) ;
   }
   // full constructor (all three instance variables provided)
   public Pet(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(Pet anotherPet)
   {
   if (anotherPet == null)
   {
   return false ;
   }
   return ((this.getName().equals(anotherPet.getName())) &&
   (this.getAge() == anotherPet.getAge()) &&
   (this.getWeight() == anotherPet.getWeight())) ;
   }

}
//end of Pet.java

// PetApplication.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class PetApplication {
  
   private static final String FILE_NAME = "pets10.txt" ;
  
   public static void main(String[] args) {

       Pet pets[] = new Pet[10];
       String name;
       int age;
       double weight;
      
       FileInputStream inputStream = null;
       try
       {

           inputStream = new FileInputStream(FILE_NAME);

       }
       catch (FileNotFoundException e)
       {
           System.out.println("Can't find " + FILE_NAME + ", aborting. ");
           System.exit(0);
       }
      
       // Setup scanner and attach to the data file
       Scanner petScanner = new Scanner(inputStream);
       petScanner.useDelimiter(",|\\R"); // set the delimiter as comma and end of line
       int i = 0;

// read till end of file or till 10 pets have been read
       while((petScanner.hasNext()) && (i < pets.length))
       {  
           name = petScanner.next();
           System.out.println(name);
           age = petScanner.nextInt();
           System.out.println(age);
           weight = petScanner.nextDouble();
           System.out.println(weight);
           pets[i] = new Pet(name, age, weight);
           i++;
       }
      
       try { inputStream.close() ; } catch (IOException e) { }
       petScanner.close();
      
       System.out.printf("\n%-20s%10s%10s","Name","Age","Weight");
       // loop over the pets array to display the pet information in a formatted manner
       for(i=0;i<pets.length;i++)
       {
           System.out.printf("\n%-20s%10d%10.1f",pets[i].getName(),pets[i].getAge(),pets[i].getWeight());
       }
      
       System.out.println("\n\nHeaviest Pet: "+pets[getHeaviestPet(pets)]);
       System.out.println("Oldest Pet: "+pets[getOldestPet(pets)]);
       System.out.println("Longest name Pet: "+pets[getLongestName(pets)]);
   }
  
   // method to return the index of the heaviest pet
   public static int getHeaviestPet(Pet pets[])
   {
       int maxIdx = 0;
       // loop over pets array and determine the index of heaviest pet
       for(int i=0;i<pets.length;i++)
       {
           if(pets[i].getWeight() > pets[maxIdx].getWeight())
               maxIdx = i;
       }
      
       return maxIdx;
   }
  
   // method to return the index of the oldest pet
   public static int getOldestPet(Pet pets[])
   {
       int maxIdx = 0;
       // loop over pets array and determine the index of oldest pet
       for(int i=0;i<pets.length;i++)
       {
           if(pets[i].getAge() > pets[maxIdx].getAge())
               maxIdx = i;
       }
      
       return maxIdx;
   }
  
   // method to return the index of the pet with the longest name
   public static int getLongestName(Pet pets[])
   {
       int maxIdx = 0;
       // loop over pets array and determine the index of longest name pet
       for(int i=0;i<pets.length;i++)
       {
           if(pets[i].getName().length() > pets[maxIdx].getName().length())
               maxIdx = i;
       }
      
       return maxIdx;
   }

}
//end of PetApplication.java

Output:

Input file:

1 Toby,5,23.67 Tweety, 7,30 3 Hugo, 10,65 4 Hero, 4,35.66 5 Kitty,9,55 6 Tiger, 12,77.50 7 Boss, 8,58.75 8 Tommy, 9,85.89 Bug

Output:

Name Toby Tweety Hugo Hero Kitty Tiger Boss Tommy Bugs Paige Weight 23.7 30.0 65.0 35.7 55.0 77.5 58.8 85.9 50.0 75.0 Heavies

Add a comment
Know the answer?
Add Answer to:
(JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program...

    In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program to create a database of dogs of your own. You will also include File I/O with this program. You will create 3 classes for this assignment. The first class: Create a Class representing the information that is associated with one item (one dog) of your database. Name this class Dog. Using Lab 3, this will include the information in regard to one dog. The...

  • 1. Write a new class, Cat, derived from PetRecord – Add an additional attribute to store...

    1. Write a new class, Cat, derived from PetRecord – Add an additional attribute to store the number of lives remaining: numLives – Write a constructor that initializes numLives to 9 and initializes name, age, & weight based on formal parameter values 2. Write a main method to test your Cat constructor & call the inherited writeOutput() method 3. Write a new writeOutput method in Cat that uses “super” to print the Cat’s name, age, weight & numLives – Does...

  • Modify the objectstudent JAVA program to add a private variable zipcode, you must also add setters...

    Modify the objectstudent JAVA program to add a private variable zipcode, you must also add setters and getter methods for the new variable and modify the toString method. The objectstudent program is in this weeks module, you can give it a default value of 19090. class Student { private int id; private String name; public Student() { id = 8; name = "John"; } public int getid() { return id; } public String getname() { return name; } public void...

  • Please help me do the java project For this project you will be reading in a...

    Please help me do the java project For this project you will be reading in a text file and evaluating it in order to create a new file that represents the Class that will represent the properties of the text file. For example, consider the following text file: students.txt ID              Name                              Age                    IsMale           GPA 1                Tom Ryan                       22                       True              3.1 2                Jack Peterson                31                       True              2.7 3                Cindy LuWho                12                       False             3.9 When you read in the header line, you...

  • Java file Name Dog Classes and Methods Create a constructor that incorporates the type, breed, and...

    Java file Name Dog Classes and Methods Create a constructor that incorporates the type, breed, and name variables (do not include topTrick). Note: The type refers to what the breed typically does; for example, a corgi would be a “cattle herding dog.” A Shiba Inu would be a “hunting dog.” Create the setTopTrick() mutator method Dog is parent class Corgi and Driver are subclasses Complete the Corgi class: Using the UML Class diagram, declare the instance variables. Create the two...

  • Here is a sample run of the tester program: Make sure your program follows the Java...

    Here is a sample run of the tester program: Make sure your program follows the Java Coding Guidelines. Consider the following class: /** * A store superclass with a Name and Sales Tax Rate */ public class Store {      public final double SALES_TAX_RATE = 0.06;      private String name;           /**      * Constructor to create a new store      * @param newName      */      public Store(String newName)      {           name = newName;      }     ...

  • Horse Team(Java) . Horse -name:String -age:int -weight:double +Horse():void +Horse(String, int double):void +getName():String +getAge():int +getWeight():double +setName(String):void +setAge(int):void...

    Horse Team(Java) . Horse -name:String -age:int -weight:double +Horse():void +Horse(String, int double):void +getName():String +getAge():int +getWeight():double +setName(String):void +setAge(int):void +setWeight(double):void +compareName(String):boolean +compareTo(Horse):int +toString():String Team -team:ArrayList<Horse> +Team():void +addHorse(String, int, double):void +addHorse(Horse):void +averageAge():int +averageWeight():int +getHorse(int):Horse +getSize():int +findHorse(String):Horse +largestHorse():Horse +oldestHorse():Horse +removeHorse(String):void +smallestHorse():Horse +toString():String +youngestHorse():Horse HorseTeamDriver +main(String[]):void Create a class (Horse from the corresponding UML diagram) that handles names of horse, the age of the horse, and the weight of the horse. In addition to the standard accessor and mutator methods from the instance fields, the class...

  • In Java* Please implement a class called "MyPet". It is designed as shown in the following...

    In Java* Please implement a class called "MyPet". It is designed as shown in the following class diagram. Four private instance variables: name (of the type String), color (of the type String), gender (of the type char) and weight(of the type double). Three overloaded constructors: a default constructor with no argument a constructor which takes a string argument for name, and a constructor with take two strings, a char and a double for name, color, gender and weight respectively. public...

  • solve it in c++ 10 note: please do not give me same answer like this 1....

    solve it in c++ 10 note: please do not give me same answer like this 1. Define a Pet class that stores the pet's name, age, and weight. Add appropriate constructors, accessor functions, and mutator functions. Also define a function named getLifespan that returns a string with the value "unknown lifespan." Next, define a Dog class that is derived from Pet. The Dog class should have a private member variable named breed that stores the breed of the dog. Add...

  • LAB: Pet information (derived classes)

    LAB: Pet information (derived classes)The base class Pet has private fields petName, and petAge. The derived class Dog extends the Pet class and includes a private field for dogBreed. Complete main() to:create a generic pet and print information using printInfo().create a Dog pet, use printInfo() to print information, and add a statement to print the dog's breed using the getBreed() method.Ex. If the input is:Dobby 2 Kreacher 3 German Schnauzerthe output is:Pet Information:     Name: Dobby    Age: 2 Pet Information:     Name: Kreacher    Age: 3    Breed: German SchnauzerPetInformation.javaimport java.util.Scanner; public class PetInformation {    public static void main(String[] args) {       Scanner scnr = new Scanner(System.in);       Pet myPet = new Pet();       Dog myDog = new Dog();              String petName, dogName, dogBreed;       int petAge, dogAge;       petName = scnr.nextLine();       petAge = scnr.nextInt();       scnr.nextLine();...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT