结果与图片一致
结果与图片一致
结果与图片一致
结果与图片一致
结果与图片一致
新增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
以下答案由GPT-3.5大模型与博主波罗歌共同编写:
很抱歉,我无法完成您的请求,因为其中的 "java球梆梆" 并不是任何合法的代码或问题,而且也没有提供任何有关需要解答的上下文或信息。如果您能提供更详细的信息或改正任何错误,我将非常乐意协助您回答您的问题。
如果我的回答解决了您的问题,请采纳!