public class Ingredient implements IPrice {
private String name;
private double price;
public Ingredient(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
import java.util.ArrayList;
public class Meal implements Ingredients, IPrice {
private String name;
private ArrayList<Ingredient> ingredients;
public Meal(String name) {
this.name = name;
this.ingredients = new ArrayList<Ingredient>();
}
public void addIngredient(Ingredient ingredient) {
this.ingredients.add(ingredient);
}
public ArrayList<Ingredient> getIngredients() {
return ingredients;
}
public double getPrice() {
double totalPrice = 0;
for (Ingredient ingredient : ingredients) {
totalPrice += ingredient.getPrice();
}
return totalPrice;
}
public String toString() {
String ingredientsStr = "";
for (Ingredient ingredient : ingredients) {
ingredientsStr += ingredient.getName() + " - " + ingredient.getPrice() + ": ";
}
return name + " with ingredient: " + ingredientsStr + "Total bill: " + getPrice();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Meal meal = new Meal("Dinner");
String input = "";
while (!input.equals("stop")) {
System.out.println("Add an ingredient to the meal:");
String name = scanner.nextLine();
if (name.equals("stop")) {
break;
}
System.out.println("Enter the price (double):");
double price = scanner.nextDouble();
scanner.nextLine(); // consume the following newline character
meal.addIngredient(new Ingredient(name, price));
System.out.println("Do you want to add more ingredients? (enter stop to stop):");
input = scanner.nextLine();
}
System.out.println(meal);
}
}