Java Programming: Write a class that represents a Zoo. The zoo only holds pengui
ID: 3772159 • Letter: J
Question
Java Programming:
Write a class that represents a Zoo. The zoo only holds penguins and lions (best zoo over). The zoo should l have the following methods. Member variable to store animal object representing animals in my zoo. A constructor to build objects of this class taking in as arguments an array of strings and an array of booleans. The strings will be animal names, the booleans will be true if the animal is penguin, false if it is a lion. You can safely assume names are unique and that the length of these two arrays is the same.Explanation / Answer
I have made three classes: Zoo, Animal, and a Driver class to test.
Following is the code:
package zoo;
import java.util.Arrays;
public class Zoo {
private Animal[] animals;
Zoo(String[] names, boolean[] lop) {
animals = new Animal[names.length];
String type;
for(int i=0; i<names.length; i++) {
if(lop[i] == true)
type = "Penguin";
else
type = "Lion";
animals[i] = new Animal(type, names[i]);
}
}
void feed() {
for(Animal an : animals){
an.feed();
}
}
void visitAnimal(String name) {
int i;
for(i=0; i<animals.length; i++) {
if(animals[i].getName() == name) {
animals[i].visit();
break;
}
}
if(i == animals.length)
System.out.println("There is no animal with name: " + name + " in the zoo.");
}
void printVisited() {
System.out.println("Name Lion/Penguin Visited or Not" );
String status;
for(Animal an : animals) {
if(an.getVisitStatus() == true)
status = "Visited";
else
status = "Not Visited";
System.out.println(an.getName() + " " + an.getType() + " " + status);
}
}
};
package zoo;
public class Animal {
private String type;
private String name;
private boolean isVisited;
public Animal(String t, String n) {
type = t;
name = n;
isVisited = false;
}
public String getType() {
return type;
}
public void setType(String t) {
type = t;
}
public String getName() {
return name;
}
public void setName(String n) {
name = n;
}
public void feed() {
System.out.println("Feeding " + type + " " + name);
}
public void visit() {
System.out.println("Visiting " + type + " " + name);
isVisited = true;
}
public boolean getVisitStatus(){
return isVisited;
}
};
package zoo;
public class Driver {
public static void main(String[] args) {
String[] names = new String[]{"Mighty Lion", "Lion2", "Pretty Penguin"};
boolean[] lop = new boolean[]{false, false, true};
Zoo zoo1 = new Zoo(names, lop);
zoo1.feed();
zoo1.visitAnimal("Lion2");
zoo1.visitAnimal("Pretty Penguin");
zoo1.printVisited();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.