Question: FOR JAVA PLEASE! Farm class: o Add a method void exit(String filename) [+4] The method saves the farm data to a file named filename. Farm
FOR JAVA PLEASE!
Farm class: o Add a method void exit(String filename)
-
[+4] The method saves the farm data to a file named filename. Farm data includes at least availableFood and animals (i.e. the array with all animal instances)
-
[+1] Once saved, display a message that data was saved successfully.
-
[+4] If errors (exceptions) happen during the saving process, the method should print
an error message. You should have at least two catch statements (one of them is
FileNotFoundException).
-
[+1] Make sure your code closes the output stream regardless of whether an error
happens or not.
-
[+2] Implement any required changes in your code (e.g. in other classes) so that this
method works.
package P3;
public abstract class Animal implements Cloneable, Comparable
//compareTo, clone public Object clone() throws CloneNotSupportedException{ return super.clone(); } public int compareTo(Animal otherAnimal){ if(this.energy < otherAnimal.energy) return -1; else if(this.energy > otherAnimal.energy) return 1; else return 0; /* Another solution (50% of the mark only): return (int)(this.energy - otherAnimal.energy); //code above is ok but gets only 50% of the mark - since casting will lose precision (e.g. if difference is < 0.5, method will return 0 indicating the two energies are the same) */ } //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); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
