In: Mechanical Engineering
An animal in our JunglePark application needs to check whether another animal is in its neighborhood (close to it). To implement this behavior, add isClose() method to the Animal base class and implement it. This method must have the following signature.
public boolean isClose(Animal otherAnimal, int range) { }
The isClose() method returns TRUE if otherAnimal is located within a range distance [0 .. range] around the current animal and FALSE otherwise.
Code:
package test;
public class Animal {
public String Animal;
//position of the animal in x and co-ordinates
public Double xDistance;
public Double yDistance;
public Animal(String animal, Double xDistance,
Double yDistance) {
super();
Animal = animal;
this.xDistance = xDistance;
this.yDistance = yDistance;
}
public Animal() {
}
public String getAnimal() {
return Animal;
}
public void setAnimal(String animal) {
Animal = animal;
}
public Double getxDistance() {
return xDistance;
}
public void setxDistance(Double xDistance) {
this.xDistance = xDistance;
}
public Double getyDistance() {
return yDistance;
}
public void setyDistance(Double yDistance) {
this.yDistance = yDistance;
}
public boolean isClose(Animal otherAnimal, int range) {
Double x1 =
this.xDistance;
Double y1 = this.yDistance;
Double x2 =
otherAnimal.getxDistance();
Double y2 =
otherAnimal.getyDistance();
//Distance between the
animals
double distanceBetweenAnimals =
Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
System.out.println("Distance
betweeen them:" + distanceBetweenAnimals);
System.out.println("Allowed Range
is:" + range);
if (distanceBetweenAnimals <
range)
return
true;
else
return
false;
}
public static void main(String[] args) {
Animal firstAnimal = new
Animal("Dog", 1.0, 1.0);
Animal secondAnimal = new
Animal("Cat", 9.0, 5.0);
System.out.println(
"Position of first animal:(" +
firstAnimal.getxDistance() + "," + firstAnimal.getyDistance() +
")");
System.out.println(
"Position of first animal:(" +
secondAnimal.getxDistance() + "," + secondAnimal.getyDistance() +
")");
boolean check =
firstAnimal.isClose(secondAnimal, 10);
if (check == true)
System.out.println("The animal is it its neighbourhood");
else
System.out.println("The animal is not in its neighbourhood");
}
}
Screenshot: