I have been tasked to create an apple program with a certain parameter that the type of apple can only be "Red Delicious", "Golden Delicious", "Gala", and "Granny Smith".
But, for some reason even if I call to the class then set the apple type to "Granny Smith" I still get an "This is an invalid type of apple". Also, it won't modify the default type name from "Gala". Maybe my if statement is wrong?
Here's the Apple class:
public class Apple {
private String type;
private double weight;
private double price;
//Default apple values (Constructors)
public Apple ()
{
this.type = "Gala";
this.weight = 0.5;
this.price = 0.89;
}
//Accessors
public String getType()
{
return this.type;
}
public double getWeight()
{
return this.weight;
}
public double getPrice()
{
return this.price;
}
//Mutators
public void setType (String aType)
{
if (!aType.equalsIgnoreCase("Red Delicious") || !aType.equalsIgnoreCase("Golden Delicious") || !aType.equalsIgnoreCase("Gala") || !aType.equalsIgnoreCase("Granny Smith"))
{
System.out.println ("That is an invalid type of apple");
return;
}
this.type = aType;
}
public void setWeight (double aWeight)
{
if (aWeight < 0 || aWeight > 2)
{
System.out.println("That is an invalid weight");
return;
}
this.weight = aWeight;
}
public void setPrice (double aPrice)
{
if (aPrice < 0)
{
System.out.println("That is an invalid price");
return;
}
this.price = aPrice;
}
//Methods
public String toString()
{
return "Name: " + type + " Weight " + weight + " Price " + price;
}
public boolean equals (Apple aApple)
{
return this.type.equalsIgnoreCase (aApple.getType()) && this.weight == aApple.getWeight() && this.price == aApple.getPrice();
}
Here's the apple tester code that calls upon my Apple class:
System.out.println("Setting the new apple's values to the following valid values: Granny Smith, 0.75, 0.99\nPrinting the new apple's values");
Apple grannySmith = new Apple();
grannySmith.setType("Granny Smith");
grannySmith.setWeight (0.75);
grannySmith.setPrice (0.99);
System.out.println(grannySmith+ "\n");
In the output, it says it is an invalid type of apple for some reason and also it sets the "Name: Gala" which Gala is default, and it doesn't change the name to "Granny Smith".
Creating another apple
Setting the new apple's values to the following valid values: Granny Smith, 0.75, 0.99
Printing the new apple's values
That is an invalid type of apple
Name: Gala Weight 0.75 Price 0.99
I don't know why it says it is an invalid type of apple and why it prints the name as the default apple type instead of what I set it to. Maybe my mutator if statement is wrong?