'How can I change this to have it stop printing the else statement on top and bottom?
public class Snack {
private String id;
private String size;
private double price;
public Snack(String id, String size) {
this.id = id;
this.size = size;
}
private String getId() {
return id;
}
private String getSize() {
return size;
}
public double getPrice() {
if(size.equals("S")) {
price = 19.99;
}
else if(size.equals("M")) {
price = 29.99;
}
else if(size.equals("L")) {
price = 39.99;
}
return price;
}
public String toString() {
return "ID:" + this.id + " Size: " + this.size + " Price: " + String.format("%.2f", getPrice());
}
public void display() {
System.out.println(toString());
}
}
public class FruitSnack extends Snack{
private boolean Citrus;
public FruitSnack(String id, String size, boolean citrus) {
super(id, size);
this.Citrus = citrus;
}
public double getPrice() {
if(this.Citrus) {
return super.getPrice() + 5.99;
}
else {
System.out.println("That is not a citrus fruit your price is: " + super.getPrice());
return super.getPrice();
}
}
public void display() {
System.out.println(toString());
String.format("%.2f",getPrice());
}
}
public class OrderSystem {
public static void main(String[] args) {
Snack test = new Snack("1s89w", "L");
Snack fruittest = new FruitSnack("14gb8", "L", false);
Snack saltytest = new SaltySnack("8752a", "S", true);
test.display();
System.out.println("");
fruittest.display();
System.out.println("");
saltytest.display();
}
My problem is my getPrice() inside my FruitSnack class, I am not sure what to change or modify so that it will not print on the top and bottom of its else statement.
This is what it is doing:
"That is not a citrus fruit your price is: 39.99 ID:14gb8 Size: L Price: 39.99 That is not a citrus fruit your price is: 39.99"
I only want it to print on the bottom but I know you can't use System.out in a return.
Solution 1:[1]
Remove your getPrice() and Display() methods and include this code in your FruitSnack Class
small edit you don't need the setter. Instead update the price in getPrice() method.
private double price
//public void setPrice(double price){
//this.price = super.getPrice() + 5.99;
//}
public double getPrice() {
return super.getPrice() + 5.99;
}
public void display() {
if (! this.Citrus)
System.out.println("That is not a citrus fruit your price
is:\n" + super.getPrice());
else
System.out.println(getPrice());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
