结果与图片一致
结果与图片一致
结果与图片一致
结果与图片一致
结果与图片一致
新增IPrice接口并定义getPrice方法
package com.test;
public interface IPrice {
public double getPrice();
}
新增Ingredient类并继承IPrice接口,类中定义name、price字段,getName属性,并实现getPrice方法
package com.test;
public class Ingredient implements IPrice{
private String name;
private double price;
public Ingredient(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public double getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
}
新增Ingredients接口并定义addIngredient、getIngredients方法
package com.test;
import java.util.ArrayList;
public interface Ingredients {
public void addIngredient(Ingredient ingredient);
public ArrayList<Ingredient> getIngredients();
}
新增Meal并实现IPrice、Ingredients方法,类中定义name、price、ingredients属性并实现getPrice、addIngredient、getIngredients方法,新增getName方法
package com.test;
import java.util.ArrayList;
public class Meal implements IPrice, Ingredients {
private String name;
private double price;
private ArrayList<Ingredient> ingredients = new ArrayList<>();
@Override
public double getPrice() {
double p = 0.0;
for (Ingredient ingredient : ingredients) {
p += ingredient.getPrice();
}
return p;
}
@Override
public void addIngredient(Ingredient ingredient) {
ingredients.add(ingredient);
}
@Override
public ArrayList<Ingredient> getIngredients() {
return this.ingredients;
}
public String getName() {
return this.name;
}
}
新增测试类
package com.test;
import java.util.Objects;
import java.util.Scanner;
public class MainTest {
public static void main(String[] args) {
Meal Dinner = new Meal();
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.print("Add an ingredient to the meal: ");
String name = scanner.next();
System.out.print("Enter the price (double): ");
double price = scanner.nextDouble();
Dinner.addIngredient(new Ingredient(name, price));
System.out.print("Do you want to add more ingredients? (enter stop to stop): ");
String operation = scanner.next();
if (Objects.equals("stop", operation)) {
break;
}
}
System.out.print("Dinner with ingredient:");
for (Ingredient ingredient : Dinner.getIngredients()) {
System.out.print(ingredient.getName());
System.out.print(" - ");
System.out.print(ingredient.getPrice());
System.out.print("; ");
}
System.out.print(" Total bill: ");
System.out.print(Dinner.getPrice());
}
}
运行结果
Add an ingredient to the meal: rice
Enter the price (double): 1
Do you want to add more ingredients? (enter stop to stop): yes
Add an ingredient to the meal: beaf
Enter the price (double): 40
Do you want to add more ingredients? (enter stop to stop): yes
Add an ingredient to the meal: tomato
Enter the price (double): 6
Do you want to add more ingredients? (enter stop to stop): stop
Dinner with ingredient:rice - 1.0; beaf - 40.0; tomato - 6.0; Total bill: 47.0
Process finished with exit code 0