Question

+1 change your code so that the animals array will have enough space for a 100 animals. (No need to add a 100 animals in the Farms constructor - see the next two points) +4] Add a method boolean add (Animal anim) that adds an animal to the next empty spot in the animals array. For example, when you first create animals, it will have a 100 empty spots (i.e. all null). The code below adds a new chicken at index 0 and a cow at index 1. The remaining spots will remain empty (i.e. equal to null). myFarm.add (new Chicken ()) myFarm.add (new Cow ()); The add method should return true when the given animal is added successfully, and falsee when the farm is full (i.e. no empty spots in animals array) +1] modify the Farms constructor to use the above add method in order to add a chicken, a cow, and two llamas. The animals array should now have exactly 4 animals and 96 empty spots. [+3] modify the getAnimals method so that it returns an array with existing animals only (i.e. dont return the full animals array if it has empty spots). For example, if you have only4 animals in your farm, getAnimals will return a new array of the size 4 with these 4 animals. +4] Add a method void animSort () that sorts the animals in the animals array based on their energy. You must use the Arrays.sort method in your implementation. For example, suppose that animals[Cowl, Chickenl, Llamal, null, null, ..., null] and assume that the order based on the energy is Llamal < Chickenl < Cow1. Then, animSort would change animals to: animals = [Llama 1 , Chicken!, Cowl, null, null, , null] +4] Implement any changes outside the Farmclass in order for animSort () to work properly.o +21 Add a method boolean addClone (Animal anim) that clones the given animal, anim, and adds it to the animals array. For example, if animals has 4 animals and we call myFarm.addClone (animals [2]),a clone of animals [2] would be created and added to animals at the next available spot. The method addClone returns true if the animal is added successfully to animals and false if the farm is full. +4] Implement any changes outside the Farm class in order for addClone to work properly. o +3] Add a method displayAnimals that will print the list of animals currently living in the may farm. For example, if myFarm has only two animals, then myFarm.printAnimals print this output: Chickenl: alive at (0.0,0.0) Energy-28.9 Cowl: alive at (0.0,0.0) Energy-87.5 o +4] Add a method int getNumChicken ) that returns the number of chicken in the farm. +2] Add two more methods, getNumCowsand getNumLlamas cows and llamas on the farm. (hint: use instanceof). that return the number of o [+2] Add a method void displaySummary that prints the total number of animals, the number of each animal type, and the amount of available food (see sample output in part C below).

help with java OOP, here is the started code:

package P2;
public class Farm {
   private double availableFood;
   private Animal[] animals;
   public Farm() {
       setAvailableFood(1000);
       animals = new Animal[4];
       animals[0] = new Chicken();
       animals[1] = new Cow();
       animals[2] = new Llama();
       animals[3] = new Llama();
   }
   public void makeNoise(){           // all animals make their sound (Moo, Cluck, etc)
       for(Animal animal: animals)
           animal.sound();
   }
   public void feedAnimals(){            // restore energy of all animals and deduct amount eaten from availableFood
       for(Animal animal : animals)
           if(availableFood >= Math.min(animal.getMealAmount(), (100-animal.getEnergy())))
           // no penalty if student uses: if(availableFood >= animal.getMealAmount())
               availableFood -= animal.eat();
           else
               System.out.println("Not enough food for your animals! You need to collect more food items.");
   }
   public double getAvailableFood() {
       return availableFood;
   }
   public void setAvailableFood(double availableFood) {
       if(availableFood>=0 && availableFood<=1000)
           this.availableFood = availableFood;
   }
   public Animal[] getAnimals() {
       return animals;
   }  
}

public class Animal {
   private String name;
   private double energy, mealAmount, x, y, speedX=1, speedY=1;
   private boolean alive;  
   public Animal() {
       setEnergy(100);
   }
   public void speak(String msg){
       if (isAlive()) System.out.println(getName() + " says: " + msg);
   }
   public double eat(){
       if (isAlive()) {
           //get amount needed and round to 2 decimals
           double amount = Math.round((100-getEnergy())*100)/100.0;
           if (amount >= mealAmount) {
               System.out.println(getName() + " ate " + mealAmount + " units");
               setEnergy(getEnergy() + mealAmount);
               return mealAmount;
           } else if (amount > 0) {
               System.out.println(getName() + " ate " + amount + " units. Now it is full!");
               setEnergy(100);
               return amount;
           } else {
               System.out.println(getName() + " didn't eat. It is full!");
               return 0;
           }
       } else {
           System.out.println(getName() + " is dead!");
           return 0;
       }
   }
   public void move() {
       if(isAlive()){
           x += speedX;
           y += speedY;
           setEnergy(getEnergy() - 0.1);
       }else
           System.out.println(getName() + "can't move. It is dead!");
   }
   public void sound(){if(isAlive()) System.out.println("Unknown sound!");}
   //setters, getters, toString
   public String getName() {
       return name;
   }
   public double getEnergy() {
       return energy;
   }
   public void setName(String name) {
       this.name = name;
   }
   public void setEnergy(double energy) {
       if(energy>0 && energy <=100)
           this.energy = energy;
       if(this.energy <= 17 )
           System.out.println(getName() + " says: I'm STARVING");
       else if(this.energy <= 50)
           System.out.println(getName() + " says: I'm hungry");
       this.alive = (energy > 0);   
   }
   public double getMealAmount() {
       return mealAmount;
   }
   public void setMealAmount(double mealAmount) {
       if(mealAmount>0 && mealAmount<100) this.mealAmount = mealAmount;
   }
   public double getX() {
       return x;
   }
   public void setX(double x) {
       this.x = x;
   }
   public double getY() {
       return y;
   }
   public void setY(double y) {
       this.y = y;
   }
   public double getSpeedX() {
       return speedX;
   }
   public void setSpeedX(double speedX) {
       this.speedX = speedX;
   }
   public double getSpeedY() {
       return speedY;
   }
   public void setSpeedY(double speedY) {
       this.speedY = speedY;
   }
   public boolean isAlive() {
       return alive;
   }
   public String toString(){
       //return String.format("Alive:%b Name:%-10sEnergy:%-7.1fLocation:(%-2.1f,%-2.1f)", isAlive(), name, energy,x,y);
       return String.format("%-8s: %-5s at (%-2.1f,%-2.1f) Energy=%-7.1f", name, isAlive()?"alive":"dead",x,y,energy);
   }  
}

thanks for your help!!

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

Thanks for posting the question, here are the first 4 changes requested in the question. I am only sharing the changes that i have updated/modified remaining methods you need to keep it as it is

______________________________________________________________________________________________

import java.util.Arrays;
import java.util.Comparator;

public class Farm {
    private double availableFood;
    private Animal[] animals;
    private int animalCount; // we need to add this variable to track the # of animals we have in the //array

    public Farm() {
        setAvailableFood(1000);
        animals = new Animal[100];
        animalCount=0;
//        animals[0] = new Chicken();
//        animals[1] = new Cow();
//        animals[2] = new Llama();
//        animals[3] = new Llama();
        add(new Chicken());
        add(new Cow());
        add(new Llama());
        add(new Llama());

    }

    public void animSort(){

        Arrays.sort(animals, new Comparator<Animal>() {
            @Override
            public int compare(Animal o1, Animal o2) {
                return (int) (o1.getEnergy()-o2.getEnergy());
            }
        });
    }

    public Animal[] getAnimals() {
        Animal[] cattles = new Animal[animalCount];
        for(int index=0;index<animalCount;index++){
            cattles[index]=animals[index];
        }
        return cattles;
    }


    public boolean add(Animal anim){

        if(animalCount<100){
            animals[animalCount]=anim;
            animalCount++;
            return true;
        }else{
            return false;
        }
    }

}
Add a comment
Know the answer?
Add Answer to:
help with java OOP, here is the started code: package P2; public class Farm {   ...
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
  • Java Programming II Homework 6 Create a class to represent a Farm object containing instances of...

    Java Programming II Homework 6 Create a class to represent a Farm object containing instances of the Animal objects Farm View javadoc for Animal and Farm classes https://bit.ly/2X6yxzw - animals : Animal [ ] - farmName : String - numAnimals : int //calculated controlled variable no setter + Farm() //default 10 animals + Farm(String) //default 10 animals + Farm(int) //size of array + Farm(String, int) + addAnimal(Animal) : void //use the next available slot to add the Animal, resize the...

  • This is the question about object-oriend programming(java) please show the detail comment and prefect code of...

    This is the question about object-oriend programming(java) please show the detail comment and prefect code of each class, Thank you! This question contain 7 parts(questions) Question 1 Create a class a class Cat with the following UML diagram: (the "-" means private , "+" means public) +-----------------------------------+ | Cat | +-----------------------------------+ | - name: String | | - weight: double | +-----------------------------------+ | + Cat(String name, double weight) | | + getName(): String | | + getWeight(): double | |...

  • I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student...

    I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student {    private String name;    private double gpa;    private int idNumber;    public Student() {        this.name = "";        this.gpa = 0;        this.idNumber = 0;    }    public Student(String name, double gpa, int idNumber) {        this.name = name;        this.gpa = gpa;        this.idNumber = idNumber;    }    public Student(Student s)...

  • What is wrong with the following Java Code. public class TestEdible { abstract class Animal {...

    What is wrong with the following Java Code. public class TestEdible { abstract class Animal { /** Return animal sound */ public abstract String sound(); } class Chicken extends Animal implements Edible { @Override public String howToEat() { return "Chicken: Fry it"; } @Override public String sound() { return "Chicken: cock-a-doodle-doo"; } } class Tiger extends Animal { @Override public String sound() { return "Tiger: RROOAARR"; } } abstract class Fruit implements Edible { // Data fields, constructors, and methods...

  • P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList()...

    P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList() { header = null; } public final Node Search(int key) { Node current = header; while (current != null && current.item != key) { current = current.link; } return current; } public final void Append(int newItem) { Node newNode = new Node(newItem); newNode.link = header; header = newNode; } public final Node Remove() { Node x = header; if (header != null) { header...

  • Provided code Animal.java: public class Animal {    private String type;    private double age;   ...

    Provided code Animal.java: public class Animal {    private String type;    private double age;       public Animal(String aT, double anA)    {        this.type = aT;        if(anA >= 0)        {            this.age = anA;        }    }    public String getType()    {        return this.type;    }    public double getAge()    {        return this.age;    } } Provided code Zoo.java: public class Zoo {...

  • please help me add on this java code to run public class CarHwMain public static void...

    please help me add on this java code to run public class CarHwMain public static void main(String args 1/ Construct two new cars and one used car for the simulation Cari carl = new Car W"My New Mazda", 24.5, 16.0); Car car2 = new Cart My New Ford" 20.5, 15.0) Cari car) - new Cari ("My Used Caddie", 15.5, 16.5, 5.5, 1/ ADD CODE to completely fill the tanks in the new cars and off the used cars ton //...

  • In Java. Please use the provided code Homework 5 Code: public class Hw05Source { public static...

    In Java. Please use the provided code Homework 5 Code: public class Hw05Source { public static void main(String[] args) { String[] equations ={"Divide 100.0 50.0", "Add 25.0 92.0", "Subtract 225.0 17.0", "Multiply 11.0 3.0"}; CalculateHelper helper= new CalculateHelper(); for (int i = 0;i { helper.process(equations[i]); helper.calculate(); System.out.println(helper); } } } //========================================== public class MathEquation { double leftValue; double rightValue; double result; char opCode='a'; private MathEquation(){ } public MathEquation(char opCode) { this(); this.opCode = opCode; } public MathEquation(char opCode,double leftVal,double rightValue){...

  • Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element...

    Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element stored at this node */ private int element; // reference to the element stored at this node /** A reference to the subsequent node in the list */ private Node next; // reference to the subsequent node in the list /** * Creates a node with the given element and next node. * * @param e the element to be stored * @param n...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

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