Java Programming Assignment 5

Requirement

Write a Java abstract superclass (call it Pet) that contains protected instance variables for the name (String) and birthyear (int). The default values for the variables will be "No Name" and 2000 (recommend to assign in their declarations). Include the following instance methods: (each MUST refer to one or more instance variables)

Solution

import java.util.*;
public abstract class HW5_Pet
{

protected String name = "No Name";

protected int birthyear = 2000;


public HW5_Pet()

{

}


public HW5_Pet(String s_Name, int i_birthYear)

{

setName(s_Name);

setBirthYear(i_birthYear);

}


public HW5_Pet(int i_birthYear)

{

setBirthYear(i_birthYear);

}


// accessor

public String getName()

{

return name;

}


public int getBirthYear()

{

return birthyear;

}


// mutator

public void setName(String s_Name)

{

if(s_Name != null)

name = s_Name;

}


public void setBirthYear(int i_birthYear)

{

GregorianCalendar oGregorianCalendar = new GregorianCalendar();

if(i_birthYear > 1900 && i_birthYear <= oGregorianCalendar.get(Calendar.YEAR))

birthyear = i_birthYear;

}


public int calcAge()

{

// instantiate a GregorianCalendar object (include java.util.*) using its default constructor, then call the get method on the object, passing Calendar.YEAR

GregorianCalendar oGregorianCalendar = new GregorianCalendar();

return (oGregorianCalendar.get(Calendar.YEAR) - birthyear);

}


// Abstract methods

public abstract int convertYears();


public abstract int lifeExpectancy();


// method for display

public String toString()

{

return this.getClass().getSuperclass().getName() + ": Name: " + name + ", Birth Year: " + birthyear;

}

}

HW5_Cat class

public class HW5_Cat extends HW5_Pet
{

private boolean isIndoor = true;


public HW5_Cat()

{

super(); // probably not needed

}


public HW5_Cat(String s_PetName, int i_PetBirthYear, boolean b_IsIndoor)

{

super(s_PetName, i_PetBirthYear);

setIsIndoor(b_IsIndoor);

}


public void setIsIndoor(boolean b_IsIndoor)

{

isIndoor = b_IsIndoor;

}


public boolean getIsIndoor()

{

return isIndoor;

}


// Equivalent human years using the rules: 1 cat year is 15 human years, 2 cat years is 24 human years, add 4 human years for every ca year over 2.

public int convertYears()

{

int i_CatAge = calcAge();

int i_EquivalentHumanYears = 0;

if (i_CatAge == 1)

i_EquivalentHumanYears = 15;

else if (i_CatAge == 2)

i_EquivalentHumanYears = 24;

else

i_EquivalentHumanYears = 24 + ((i_CatAge - 2) * 4);


return i_EquivalentHumanYears;

}


public int lifeExpectancy()

{

// Cat: 16 years if indoor cat, 4 years if outdoor cat

int i_lifeExpectancy;

i_lifeExpectancy = (isIndoor)? 16 : 4;

return i_lifeExpectancy;

}


public String toString()

{

String s_IsIndoor = (isIndoor)? "Indoor" : "Not Indoor";

return this.getClass().getName() + " " + super.toString() + ", " + s_IsIndoor ;

}

}

HW5_Dog class

public class HW5_Dog extends HW5_Pet
{

private int numOfTricks = 0;

private char size = 'S'; // ('S', 'M', or 'L') later use enumeration type


public HW5_Dog()

{

super();

}


public HW5_Dog(String s_PetName, int i_PetBirthYear, int i_NumOfTricks, char c_DogSize)

{

super(s_PetName, i_PetBirthYear);

setNumOfTricks(i_NumOfTricks);

setDogSize(c_DogSize);

}

public void setNumOfTricks(int i_NumOfTricks)

{

if(i_NumOfTricks > 0)

numOfTricks = i_NumOfTricks;

}


public void setDogSize(char c_DogSize)

{

if (Character.isLetter(c_DogSize))

{

c_DogSize = Character.toUpperCase(c_DogSize);

if(c_DogSize == 'S' || c_DogSize == 'M' || c_DogSize == 'L')

size = c_DogSize;

}

}

public int getNumOfTricks()

{

return numOfTricks;

}


public char getDogSize()

{

return size;

}


// Equivalent human years using the rules: 1 dog year is 9 human years, add 7 years for every year over 1

public int convertYears()

{

int i_DogAge = calcAge();

int i_EquivalentHumanYears = 0;

if (i_DogAge == 1)

i_EquivalentHumanYears = 9;

else

i_EquivalentHumanYears = 9 + ((i_DogAge - 1) * 7);


return i_EquivalentHumanYears;

}


public int lifeExpectancy()

{

// Dog: 16 years if a small dog, 12 years if a medium dog, 10 years if a large dog

if(size == 'S')

return 16;

else if(size == 'M')

return 12;

else // if(size == 'L')

return 10;

}


public String toString()

{

return this.getClass().getName() + " " + super.toString() + ", # of Tricks: " + numOfTricks + ", Dog Size: " + size;

}

}

HW5_Main class

/*

Name of program: Learn to use Inheritance, abstract class/methods using Pet, Dog, Cat classes

Programmer's name: ABC

Current Date: dd/mm/yyyy

Computer system and compiler you are using: Win 8, JDK 1.7

Brief description of the program (1-5 sentences): Learn to use Inheritance, abstract class/methods using Pet, Dog, Cat classes

Variable names (if any) and descriptions of what they represent:

*/
import java.util.Scanner;
public class HW5_Main 
{

static Scanner oScanner = new Scanner(System.in);

public static void main(String[] args)

{

HW5_Pet [] oPets;

// 1. Get Pet information from user

oPets = getPets();


// 2. Given Test class to skip method A

//oPets = getTestPetArray();


// Sort Pet list

SortPetList(oPets);


// Display all Pets

Display(oPets);


int numOfLargeDogs = NumberOfLargeDogs(oPets);

if(numOfLargeDogs >= 0)

System.out.println("Number of large dog(s): " + numOfLargeDogs);

else

System.out.println("No Dogs");

}


// Method that returns (in a return statement) an array of Pet objects. In this method, read the size of array from the user, (don't allow < 1 or > 20) allocate memory for the array, then assign to each element the return value from a static method that reads and PARSES the input (in another method, see A. below).

public static HW5_Pet [] getPets()

{

HW5_Pet [] oPets;

int i_NumOfPets = 0;

while (i_NumOfPets < 1 || i_NumOfPets > 20)

{

System.out.print("Enter total number of pets you want to create (between 1-20): ");

i_NumOfPets = oScanner.nextInt();

oScanner.nextLine(); // to flush new line before taking value from user

}

oPets = new HW5_Pet[i_NumOfPets];

for(int i = 0; i < oPets.length; i++)

{

oPets[i] = getPet();

if(oPets[i] == null) // if entered pet information has problem ask one more time, How to do it in a better way ??

i--;

}


return oPets;

}


// Method (in the same class as main that you write) to sort the array by name (be sure to use the length variable of the array), using the String class' compareToIgnoreCase method.

public static void SortPetList(HW5_Pet [] oPets)

{

HW5_Pet oTmpPet;

for(int i = 0; i < oPets.length; i++)

{

for (int j = i+1; j < oPets.length; j++)

{

if(oPets[i].getName().compareToIgnoreCase(oPets[j].getName()) > 0)

{

oTmpPet = oPets[i];

oPets[i] = oPets[j];

oPets[j] = oTmpPet;

}

}

}

}


// A. In the method that reads and parses the input, read into a String, tokenize (using a StringTokenizer or split method in the String class), convert the tokens into the expected types based on whether it's a Dog or Cat, and return an instance of Dog or Cat based on the tokens (converted to int if needed). To convert a String with an int to an int, use Integer.parseInt(str).

public static HW5_Pet getPet()

{

System.out.print("Enter pet info, separated by commas: ");

String s_PetInfo = oScanner.nextLine();

String [] a_PetInfo;

if(s_PetInfo.contains(","))

{

a_PetInfo = s_PetInfo.split(",");

if(a_PetInfo != null)

{

if(a_PetInfo[0].compareToIgnoreCase("CAT") == 0)

{

String s_CatName = (a_PetInfo.length > 0)? a_PetInfo[1] : "";

int i_CatBirthYear = (a_PetInfo.length > 1)? Integer.parseInt(a_PetInfo[2]): 0;

boolean b_IsIndoor = (a_PetInfo.length > 2)? Boolean.parseBoolean(a_PetInfo[3]): true; // default to true same as default initialize value of variable

return new HW5_Cat(s_CatName, i_CatBirthYear, b_IsIndoor);

}

else if (a_PetInfo[0].compareToIgnoreCase("DOG") == 0)

{

String s_DogName = (a_PetInfo.length > 0)? a_PetInfo[1] : "";

int i_DogBirthYear = (a_PetInfo.length > 1)? Integer.parseInt(a_PetInfo[2]): 0;

int i_NumOfTricks = (a_PetInfo.length > 2)? Integer.parseInt(a_PetInfo[3]): 0;

char c_DogSize = (a_PetInfo.length > 3)? a_PetInfo[4].charAt(0) : 'S';

return new HW5_Dog(s_DogName, i_DogBirthYear, i_NumOfTricks, c_DogSize);

}

else

{

System.out.println("Invalid input -- try again");

return null;

}

}

else

{

System.out.println("Invalid input -- try again");

return null;

}

}


System.out.println("Invalid input -- try again"); // In case

return null;

}


// a method (in the same class as main that you write) that prints each object's toString AND the return value from convertYears AND return value from lifeExpectancy in an enhanced for loop.

public static void Display(HW5_Pet [] oPets)

{

for(HW5_Pet oPet: oPets)

{

System.out.println(oPet.toString() + ", Human Years: " + oPet.convertYears() + ", Life Expentancy: " + oPet.lifeExpectancy());

}

}


// Method (in the same class as main that you write) to return how many Dogs in the array (if any) are Large Dogs (described in B. below)

public static int NumberOfLargeDogs(HW5_Pet [] oPets)

{

int numOfLargeDogs = 0;

boolean b_IsDog = false;

for (HW5_Pet oPet: oPets)

{

if(oPet instanceof HW5_Dog)

{

HW5_Dog oHW5_Dog= (HW5_Dog) (oPet);

if(oHW5_Dog.getDogSize() == 'L')

numOfLargeDogs ++;

b_IsDog = true;

}

}


if(!b_IsDog) numOfLargeDogs = -1;

return numOfLargeDogs;

}


// Given Test Case

public static HW5_Pet [] getTestPetArray(){

return new HW5_Pet[]{

new HW5_Dog("Doby Doberman", 2006, 7, 'L'),

new HW5_Dog("Wienie Dog", 2003, 3, 's'),

new HW5_Cat("Calico Cat", 2006, true),

new HW5_Dog("banjo dog", 2008, 2, 'l'),

new HW5_Cat("FRAIDY CAT", 2010, false)

};

} //end getTestPetArray

}
/*
Given Test Case Output:
HW5_Dog HW5_Pet: Name: banjo dog, Birth Year: 2008, # of Tricks: 2, Dog Size: L, Human Years: 37, Life Expentancy: 10
HW5_Cat HW5_Pet: Name: Calico Cat, Birth Year: 2006, Indoor, Human Years: 44, Life Expentancy: 16
HW5_Dog HW5_Pet: Name: Doby Doberman, Birth Year: 2006, # of Tricks: 7, Dog Size: L, Human Years: 51, Life Expentancy: 10
HW5_Cat HW5_Pet: Name: FRAIDY CAT, Birth Year: 2010, Not Indoor, Human Years: 28, Life Expentancy: 4
HW5_Dog HW5_Pet: Name: Wienie Dog, Birth Year: 2003, # of Tricks: 3, Dog Size: S, Human Years: 72, Life Expentancy: 16
Number of large dog(s): 2
Test Run 1:
Enter total number of pets you want to create (between 1-20): 5
Enter pet info, separated by commas: dog,Doby Doberman,2006,7,L
Enter pet info, separated by commas: Dog,Weinie Dog,2003,3,s
Enter pet info, separated by commas: Cat,Calico Cat,2006,true
Enter pet info, separated by commas: DOG,banjo dog,2008,2,L
Enter pet info, separated by commas: CAT,FRAIDY CAT,2010,false
HW5_Dog HW5_Pet: Name: banjo dog, Birth Year: 2008, # of Tricks: 2, Dog Size: L, Human Years: 37, Life Expentancy: 10
HW5_Cat HW5_Pet: Name: Calico Cat, Birth Year: 2006, Indoor, Human Years: 44, Life Expentancy: 16
HW5_Dog HW5_Pet: Name: Doby Doberman, Birth Year: 2006, # of Tricks: 7, Dog Size: L, Human Years: 51, Life Expentancy: 10
HW5_Cat HW5_Pet: Name: FRAIDY CAT, Birth Year: 2010, Not Indoor, Human Years: 28, Life Expentancy: 4
HW5_Dog HW5_Pet: Name: Weinie Dog, Birth Year: 2003, # of Tricks: 3, Dog Size: S, Human Years: 72, Life Expentancy: 16
Number of large dog(s): 2
Test Run 2:
Enter total number of pets you want to create (between 1-20): 3
Enter pet info, separated by commas: cat,Prance Tabby,2007,false
Enter pet info, separated by commas: Cat,Nip Cat,2004,true
Enter pet info, separated by commas: CAT,FLIP Cat,2009,false
HW5_Cat HW5_Pet: Name: FLIP Cat, Birth Year: 2009, Not Indoor, Human Years: 32, Life Expentancy: 4
HW5_Cat HW5_Pet: Name: Nip Cat, Birth Year: 2004, Indoor, Human Years: 52, Life Expentancy: 16
HW5_Cat HW5_Pet: Name: Prance Tabby, Birth Year: 2007, Not Indoor, Human Years: 40, Life Expentancy: 4
No Dogs
Test Run 3:
Enter total number of pets you want to create (between 1-20): 4
Enter pet info, separated by commas: Dog,tiny chihuahua,2009,8,S
Enter pet info, separated by commas: dog,Sparky Dalmatian,2006,6,m
Enter pet info, separated by commas: cat,smokey cat,2010,false
Enter pet info, separated by commas: dog,NANOOK HUSKY,2006,7,M
HW5_Dog HW5_Pet: Name: NANOOK HUSKY, Birth Year: 2006, # of Tricks: 7, Dog Size: M, Human Years: 51, Life Expentancy: 12
HW5_Cat HW5_Pet: Name: smokey cat, Birth Year: 2010, Not Indoor, Human Years: 28, Life Expentancy: 4
HW5_Dog HW5_Pet: Name: Sparky Dalmatian, Birth Year: 2006, # of Tricks: 6, Dog Size: M, Human Years: 51, Life Expentancy: 12
HW5_Dog HW5_Pet: Name: tiny chihuahua, Birth Year: 2009, # of Tricks: 8, Dog Size: S, Human Years: 30, Life Expentancy: 16
Number of large dog(s): 0
Test Run 4:
Enter total number of pets you want to create (between 1-20): 3
Enter pet info, separated by commas: cat,bad cat,2020,false
Enter pet info, separated by commas: dog,bad dog,2000,-2,X
Enter pet info, separated by commas: iguana,lizard face,1900
Invalid input -- try again
Enter pet info, separated by commas: Dog,old dog,1900,1,m
HW5_Cat HW5_Pet: Name: bad cat, Birth Year: 2000, Not Indoor, Human Years: 68, Life Expentancy: 4
HW5_Dog HW5_Pet: Name: bad dog, Birth Year: 2000, # of Tricks: 0, Dog Size: S, Human Years: 93, Life Expentancy: 16
HW5_Dog HW5_Pet: Name: old dog, Birth Year: 2000, # of Tricks: 1, Dog Size: M, Human Years: 93, Life Expentancy: 12
Number of large dog(s): 0
*/