Implement Zoo class (with its test class). Zoo have name and area in meter square. Zoo can have one or more Animals. An Animal has ID, name, Type, Age, gender. We should be able to add new Animals to the Zoo, remove Animals and determine how many animals currently in the zoo.
This is the Zoo class:
import java.util.ArrayList;
public class Zoo {
String name;
String area;
ArrayList<Animal> animals;
static int id;
public Zoo(String name, String area) {
this.name = name;
this.area = area;
}
public void addanimal(animal ann) {
animals.add(id, ann);
id++;
}
}
public class Animal {
String name;
String type;
String age;
String gender;
public Animal(String name, String type, String age, String gender) {
this.name = name;
this.type = type;
this.age = age;
this.gender = gender;
}
}
public class Test {
public static void main(String[] args) {
Zoo nozha = new Zoo("nozha", "100");
Animal lion = new Animal("lion", "male", "20", "fine");
nozha.addanimal(lion);
Znimal tiger = new Animal("tiger", "male", "30", "ssc");
nozha.addanimal(tiger);
System.out.print(Zoo.id);
}
}
First I need help with function (addanimal) because when I print (zoo.id) its not working and I didn't know how to remove animal please help me i am beginner in programming and this is my first time i used ArrayList and I never asked before
You need to initialize the animals variable to something other than its default value, which is null:
private List<Animal> animals = new ArrayList<Animal>();
Then look at the javadoc of java.util.List, and you'll see that it contains methods to add and remove elements, as well as a method which returns its size, and makes thus the id variable completely unnecessary.
Also, notice in the javadoc how ALL the classes start with an uppercase letter, and ALL the methods are spelled in camelCase (like addAnimal() and not like addanimal()). Respect these conventions: they're a very important factor for the readability of your code.
Also, choose the appropriate type for your variables. An area, in meter square, should be an int or a float or a double, but not a String.
First i need help with function (addanimal) because when i print (zoo.id)
Basing from your code it seems that zoo.id would return the size of ArrayList<animals> why use the size of the said list instead animals.size() or by rule of encapsulation, getAnimals().size(). This may return a NullPointerException, so intialize ArrayList<animals> with a emptyarraylist`
In removing a said animal in the list, you better go for animals.remove(Animal ann).
In updating, check for if animals.contains(Animal ann) is true, via ID or hashCode then check what index is ann in the list then update ann by animals.set(<index>, ann)
Zoo.java:
import java.util.ArrayList;
public class Zoo {
String name;
double area;
int sizeOfZoo = 0;
ArrayList<Animal> animals = new ArrayList<Animal>();
public Zoo(String name, double area) {
this.name = name;
this.area = area;
}
public void addAnimal(Animal ann) {
animals.add(ann);
}
public int getSizeOfZoo() {
return animals.size();
}
}
Animal.java
public class Animal {
String name;
String type;
String age;
String gender;
public Animal(String name, String type, String age, String gender) {
this.name = name;
this.type = type;
this.age = age;
this.gender = gender;
}
}
Test.java
public class Test {
public static void main(String[] args) {
Zoo nozha = new Zoo("nozha", 100);
Animal lion = new Animal("lion","fine","20","male");
nozha.addAnimal(lion);
Animal tiger = new Animal("tiger","ssc","30","female");
nozha.addAnimal(tiger);
System.out.println("Number of animals in zoo: " + nozha.getSizeOfZoo());
}
}
I threw in a getSizeOfZoo() method for you, to get rid of the Id variable. Changed String for area to a Double. Keep your classes seperate, keep the naming convention Class, variable, methodName() etc. It makes it much easier to read. The parameters when creating a lion and tiger were a little off, I've put it as name, type, age, gender now.
Check out the javadoc for ArrayList and you can figure out how to 'remove' an element from your ArrayList (I'm reluctant to do your project FOR you). The issues you have encountered are more around coding basics rather than anything Java specific, or OOP specific. Have a read up, try the mothod removeAnimal(animal an) and see how you get on. We can help if there is any issue, but look at getSizeOfZoo() and addAnimal() and the docs and you should be flying!
Hope that helps.
Related
I'm a beginner to java, and I'm having issues creating an object that is a child of a parent class. I can't share source code, because it is for a school project; and I don't want to get dinged for cheating. But, I can write similar code; so that I can gain a fundamental understanding to the concepts that I am not grasping.
Java Environment: Eclipse
When I am attempting to create an child object in my Test class, I'm getting an error (that red symbol in the line numbers).
The error message that I'm receiving is "The constructor Animal(Long, String, Float, String, String) is undefined. Then the suggestions offer two options, modify the Animal constructor to include the child Dog class parameters. Or, create a new Animal constructor with the Animal and child Dog class parameters.
I'm not sure why this is happening. I've double checked and I'm not getting errors at the child constructors; and I'm using "super()". I thought that OOP and Java would automatically create a child object with the matching parameter pattern. Any help would be appreciated.
Parent Class
pubic class Animal {
Long id;
String section;
Float price;
public Animal (Long id, String section, Float price){
this.id = id;
this.section = section;
this.price = price;
}
}
1st Child Class
public class Dog extends Animal {
String name;
String favoriteToy;
public Dog (Long id, String section, Float price, String name, String favoriteToy){
super(id, section, price);
this.name = name;
this.favoriteToy = favoriteToy;
}
}
2nd Child Class
public class Bird extends Animal {
String name;
Integer wingSpan;
public Dog (Long id, String section, Float price, String name, Integer wingSpan){
super(id, section, price);
this.name = name;
this.wingSpan = wingSpan;
}
}
Test Class
public class Test {
public static void main(String[] args) throws java.lang.Exception{
//I get error here
Animal animal1 = new Animal (Long.valueOf(76532), "Canine", 99.95, "Sparky", "tennis ball");
}
}
Your Animal class has exactly one constructor
public Animal (Long id, String section, Float price){
but you're calling a constructor
new Animal (Long.valueOf(76532), "Canine", 99.95, "Sparky", "tennis ball");
This constructor does not exist for Animal. It is exactly what the compiler told you with "The constructor Animal(Long, String, Float, String, String) is undefined". What exists is
public Dog (Long id, String section, Float price, String name, Integer wingSpan){
that is a constructor of your Dog class. You probably want to call that like
new Dog (Long.valueOf(76532), "Canine", 99.95, "Sparky", "tennis ball");
As Dog inherits from Animal, i.e. Dog is an Animal, you can store a Dog reference in a variable of type Animal like
Animal animal1 = new Dog (Long.valueOf(76532), "Canine", 99.95, "Sparky", "tennis ball");
I'm doing an exercise on Inheritance and polymorphism, I have 3 seperate clasees, my main class, a super Animal class, and a sub Cat class. I've made overloaded constructors, getters and setters, and toString() methods in both Animal and Cat classes. I think I have the inheritance part down. Now I need to make 2 Animal Object references, both an instance of Cat, example: one a type Siameese with a name Tobbie.
Could anyone give me an example of one of these object references? You can see I've attempted in my Main class there, but I'm not sure if that is correct.
Here are the three different classes I have currently.
public class Hw02 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Animal Siamese = new Cat("Tobbie");
}
}
Here's my Animal Class.
public class Animal {
private String name;
public Animal() {
this("na");
}
public Animal(String name) {
this.name = name;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Animal{"
+ "name="
+ name
+ '}';
}
}
And here is my Cat class.
public class Cat extends Animal {
private String type;
public Cat() {
}
public Cat(String type) {
this.type = type;
}
public Cat(String type, String name) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Cat{"
+ "type="
+ type
+ '}';
}
}
// in main method
Animal tobbie = new Cat("siamese", "Tobbie")
Animal jackie = new Cat("tomcat", "Jackie")
// in Cat class
public Cat(String type, String name) {
super(name)
this.type = type;
}
A few comments:
It is not proper convention to have the name Siamese; variable names should be "camelCase" (start with a lower-case letter). Compiler will accept it is as you have written, but it is a bad practice.
Your Cat(String type, String name) constructor didn't invoke the proper superclass constructor, thus type was lost; same for the Cat(String type) constructor
I think I would make Animal abstract and its constructors protected. I think it is a bad practice to let clients directly instantiate Animals without specifying what kind of animals they are.
Edit:
Like this:
Animal animal = new Animal("What am I?")
However, I don't consider it a good practice to do this, probably what you want done is better achieved otherwise.
Edit:
Cat toString():
public String toString() {
return super.toString() + " Cat{type=" + type + "}";
}
With the code you have above, this is an example:
Animal animal0 = new Cat("Siamese", "Bob");
Animal animal1 = new Cat("Tomcat", "Frank");
Animal animal2 = new Cat("Tomcat", "George");
Animal animal3 = new Animal("Elephant");
System.out.print(animal0.toString());
System.out.print(animal1.toString());
System.out.print(animal2.toString());
System.out.print(animal3.toString());
Would produce the output:
Cat{type=Siamese}
Cat{type=Tomcat}
Cat{type=Tomcat}
Animal{name=Elephant}
This is the array code I have so far:
ArrayList<Data> arrl = new ArrayList<Data>();
arrl.add("Tim", 23);
Need to know how to an integer and a string to the array.
For Example:
names: and ages:
Tim 23
Max 56
Clare 43
I know how to add integers OR strings to array-lists but i can't figure how to incorporate both in the same array.
Your list is taking objects of type Data. So, create a Data class that contains a String for the name and int for the age. Create a Data object for each entry you want and add it to your arrl list.
public class Data {
private String name;
private int age;
/**
* Constructor
*/
public Data(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters go here.
}
In this example I used a constructor to allow easy construction of a Data object with a name and age.
List<Data> arrl = new ArrayList<Data>();
arrl.add(new Data("Tim", 23));
You could have a class Person for instance, where you save the name and age of a person.
Then, you have a ArrayList of Person, and you can store and access that information.
ArrayList is a class that use generics, it means type-safety, so when you declare a class that use generic in its class definition you have to declare the type when making the instance.
If you want to store Stringobjects declare ArrayList in this way:
ArrayList<String> saveString = new ArrayList<String>
You can make a class Person with those instance variables and resolve your problem.
For example:
public class Person {
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
}
And then you can use in this way:
ArrayList<Person> people = new ArrayList<Person>();
people.add(new Person("Luis Alberto",15));
Your arraylist is made for Data objects that means you have to create Data object to put it there, `this is what i mean by that arrl.add(new Data("Tim",44));
Make sure that you have class Data with constructor for string and int
Something like this:
public class Main {
public static void main(String[] args) {
ArrayList<Person> arrl = new ArrayList<>();
arrl.add(new Person("Tim", 23));
}
}
class Person {
private String name;
private int age;
Person (String name, int age) {
this.name = name;
this.age = age;
}
}
I think the best approach is what is proposed by Wabs and Ashot Karakhanyan. But if your need, is to have the name and age as different items of your list, you can use the following:
List<Object> arrl = new ArrayList<Object>();
arrl.add("name");
arrl.add(23);
I am very new to Java and to programming in general, and I have an assessment to complete where I load employees (with name, age, and department attributes; department can be only one of four enumerated values) into a program that will sort them by age and tell if the age is a prime number. The assignment requires Company, Department, and Employee classes. I am confident that I can figure out age/prime components — I know how to google for algorithms. What I am struggling with is putting all the discrete pieces into a cohesive whole.
Here is what I have so far. I've put in one employee, but the way I'm doing it seems completely inelegant and inefficient. I am sure there is a better way, but I've hit a mental block.
EDIT: as was pointed out below, I was unclear. What I am asking help with is populating the data structure.
Company class:
public class Company {
static Employee one = new Employee();
public static void main(String[] args) {
one.setName("Counting Guru");
one.setAge(55);
one.setDepartment(DepartmentList.ACCOUNTING);
}
}
DepartmentList class:
import java.util.EnumMap;
import java.util.Map;
import java.util.Set;
public enum DepartmentList {
ACCOUNTING, MARKETING, HUMANRESOURCES, INFORMATIONSYSTEMS;
public static void main(String[] args) {
Map<DepartmentList,String>
enumMap=new EnumMap<DepartmentList,String>(DepartmentList.class);
enumMap.put(DepartmentList.ACCOUNTING, "Accounting");
enumMap.put(DepartmentList.MARKETING, "Marketing");
enumMap.put(DepartmentList.HUMANRESOURCES, "Human Resources");
enumMap.put(DepartmentList.INFORMATIONSYSTEMS, "Information Systems");
Set<DepartmentList> keySet = enumMap.keySet();
for (DepartmentList department : keySet) {
String value = enumMap.get(department);
System.out.println("ENUMMAP VALUE:"+value);
}
}
}
Employee class:
public class Employee {
String empName;
int empAge;
DepartmentList empDept;
Employee() {
}
public String getName() {
return empName;
}
public void setName(String name) {
this.empName = name;
}
public int getAge() {
return empAge;
}
public void setAge(int age) {
this.empAge = age;
}
public DepartmentList getDepartment() {
return empDept;
}
public void setDepartment(DepartmentList department) {
this.empDept = department;
}
public Employee(String empName, int empAge, DepartmentList empDept){
}
}
I also have a Department class, but it's currently empty.
Am I on the right track? Can someone give me a nudge? Thank you!
Don't hard-code the data inside the Java program. Put the data in a file and write methods to load the data.
If you MUST hardcode the data in the program, use something like this sample:
public class Employee
{
String name;
int age;
public Employee(String name, int age)
{
this.name = name;
this.age = age;
}
// getters, setters, etc.
}
In the main program
private static Employee[] empData =
{
new Employee("John Smith", 50),
new Employee("Fred Jones", 25),
.
.
.
};
Now you have a static array of Employee objects that you can "load" into your data structure.
If you're asking if there is something like a property in Java, no, there isn't (at least not yet).
If you're asking how to populate your objects something like an IOC container, like Spring, would be a better choice.
Now as it comes to your code you have two main methods in two different classes. Only one will be called. If you want to create a static instance you will be better do
static Employee one = new Employee("Counting Guru", 55, DepartmentList.ACCOUNTING);
or
static Employee one = new Employee();
static {
one.setName("Counting Guru");
one.setAge(55);
one.setDepartment(DepartmentList.ACCOUNTING);
}
When it comes to the enum then you'll better define a constructor for it
public enum DepartmentList {
ACCOUNTING("Accounting"), MARKETING("Marketing");
private String displayName;
public DepartmentList(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return diplayName;
}
}
In the Employee constructor you need to assign the field values to the ones received as arguments.
I am trying to print the first element on the two arrays in my Athlete class, country and name. I also need to create a object that simulates three dive attemps an athlete had (that is initially set to zero). I am new to OOP and I dont know how to go abouts doing this in my main... as far as constructors go. This is what i have done so far...
this is the main:
import java.util.Random;
import java.util.List;
public class Assignment1 {
public static void main(String[] args) {
Athlete art = new Athlete(name[0], country[0], performance[0]);
}
}
I just really am not sure what to do...
And this is the class with the arrays.
import java.util.Random;
import java.util.List;
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
//Here i would like to create something that would be representing 3 dive attemps (that relate to dive and score. eventually.)
Athlete(String[] name, String[] country, Performance[] performance) {
this.name = name;
this.country=country;
this.performance=performance;
}
public Performance Perform(Dive dive){
dive.getDiveName();
return null;
}
public String[] getName() {
return name;
}
public void setName(String[] name) {
this.name = name;
}
public String[] getCountry() {
return country;
}
public void setCountry(String[] country) {
this.country = country;
}
}
thanks in advance for any help and input!
btw there is other classes too, just not relevant atm..
First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.
However, if you really want to use that Getter and Setter, change the public modifier to private instead.
Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
----------Shadowing sample----------
You have the following class:
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
In your main method for example, you instantiate the Person class as follow:
Person person = new Person("theolc");
Variable name will be equal to "theolc".
----------End of shadowing----------
Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
In your main method, you could do this.
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.
Based on what it looks like you're trying to do, this will not work.
These arrays belong in your main class.
Your attempt at an athlete class seems to be dealing with a group of athletes, which is a design fault.
Define a class to represent a single athlete, with fields that represent the athlete's attributes:
public class Athlete {
private final String name;
private final String country;
private List<Performance> performances = new ArrayList<Performance>();
// other fields as required
public Athlete (String name, String country) {
this.name = name;
this.country = country;
}
// getters omitted
public List<Performance> getPerformances() {
return performances;
}
public Performance perform(Dive dive) {
// not sure what your intention is here, but something like this:
Performance p = new Performance(dive, this);
// add new performance to list
performances.add(p);
return p;
}
}
Then your main method would use ti like this:
public class Assignment1 {
public static void main(String[] args) {
String[] name = {"Art", "Dan", "Jen"};
String[] country = {"Canada", "Germant", "USA"};
Dive[] dive = new Dive[]{new Dive("somersault"), new Dive("foo"), new Dive("bar")};
for (int i = 0; i < name.length; i++) {
Athlete athlete = new Athlete(name[i], country[i]);
Performance performance = athlete.perform(dive[i]);
// do something with athlete and/or performance
}
}
}
I think you are a little messed up with what you doing.
Athlete is an object, athlete has a name, i has a city where he lives.
Athlete can dive.
public class Athlete {
private String name;
private String city;
public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){}
}
public class Main{
public static void main (String [] args){
String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord
--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);
}
}
public static void main(String[] args) {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
// initialize your performance array here too.
//Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
Athlete art = new Athlete(name, country, performance);
}
First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:
class Athlete {
private String name;
private String country;
private List<Dive> dives;
public Athlete(String name, String country){
this.name = name;
this.country = country;
}
public String getName(){
return this.name;
}
public String getCountry(){
return this.country;
}
public String getDives(){
return this.dives;
}
public void addDive(Dive dive){
this.dives.add(dive);
}
}
Then for the Dive class:
class Dive {
private Athlete athlete;
private Date date;
private double score;
public Dive(Athlete athlete, double score){
this.athlete = athlete;
this.score = score;
this.date = new Date();
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
}
Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:
#Test
public void testThatDivesRetainInformation(){
Athlete art = new Athlete("Art", "Canada");
Dive art1 = new Dive(art, 8.5);
Dive art2 = new Dive(art, 8.0);
Dive art3 = new Dive(art, 8.8);
Dive art4 = new Dive(art, 9.2);
assertThat(art.getDives().size(), is(5));
}
Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.
You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.