[Java] Please fix the problem. Don\'t just copy and paste the answer which alrea
ID: 3820156 • Letter: #
Question
[Java] Please fix the problem. Don't just copy and paste the answer which already exists in the chegg system. It's wrong.
Do not make any changes in the Product or SnackTester.
And PLEASE CHECK YOUR CODE AT THE LINK I PROVIDE BELOW. THE OUTPUT HAS TO BE EXACTLY SAME WITH THE PROGRAM.
Write a Snack class as a subclass of Product. In addition to description and price, Snack has integer instance variable gramsOfFat.
Write a method getGramsOfFat.
Write a method isHealther which returns true if this Snack has fewer grams of fat than the parameter Snack.
Include toString and equals.
Snack should implement Comparable interface. Snacks are ordered first by gramsOfFat with the Snack with the fewer grams of fat coming first. If the grams of fat are the same order by price with the lowest price coming first, If prices are also equal, order alphabetically by description
Implement the Clonable interface
Use the following files:
Product.java
SnackTester.java
[Here's the snack class]
It gives me an error
public class Snack extends Product implements Comparable<Snack>,Cloneable{
private int gramsOfFat;
public Snack(String theDescription, double thePrice,int gramsOfFat){
super(theDescription,thePrice);
this.gramsOfFat=gramsOfFat;
}
public int getGramsOfFat(){
return gramsOfFat;
}
public boolean isHealthier(Snack snack){
return (gramsOfFat<snack.getGramsOfFat());
}
// Overriding the compareTo method
public int compareTo(Snack snack) {
if((this.gramsOfFat-snack.getGramsOfFat())!=0)
return (this.gramsOfFat-snack.getGramsOfFat());
else if((super.getPrice()-snack.getPrice())!=0)
return ((int)(super.getPrice()-snack.getPrice()));
else if (super.getDescription().compareToIgnoreCase(snack.getDescription())>0)
return 1;
else if(super.getDescription().compareToIgnoreCase(snack.getDescription())<0)
return -1;
else
return 0;
}
public Object clone()throws CloneNotSupportedException
{
return super.clone();
}
@Override
public String toString()
{
return super.toString()+"[gramsOfFat="+gramsOfFat+"]";
}
@Override
public boolean equals(Object otherObject)
{
if (otherObject == null) {return false;}
if (this.getClass() != otherObject.getClass()) {return false;}
Snack other = (Snack)otherObject;
return super.getPrice() == other.getPrice()
&& super.getDescription().equals(other.getDescription())&&this.gramsOfFat==other.getGramsOfFat();
}
}
Explanation / Answer
In SnackTester.java,
surround " Snack cloned = (Snack)crunch.clone(); " with try-catch block.
Do something like this ::
Snack cloned;
try{
cloned = (Snack)crunch.clone();
}catch(Exception e){
e.printStackTrace();
}
So, replace above line with code given i bold and it will stop showing that error.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.