一个方法的签名可以使用以下方式定义:
public List getIngredients(String recipeName) {
// 方法体
}
这个方法的签名包括方法的访问修饰符(public),返回类型(List
下面是一个简单的示例代码,展示如何使用这个方法来获取特定食谱的配料列表:
import java.util.ArrayList;
import java.util.List;
public class RecipeBook {
private List recipeNames;
private List> ingredientsList;
public RecipeBook() {
recipeNames = new ArrayList<>();
ingredientsList = new ArrayList<>();
}
public void addRecipe(String recipeName, List ingredients) {
recipeNames.add(recipeName);
ingredientsList.add(ingredients);
}
public List getIngredients(String recipeName) {
int index = recipeNames.indexOf(recipeName);
if (index != -1) {
return ingredientsList.get(index);
} else {
return null;
}
}
public static void main(String[] args) {
RecipeBook recipeBook = new RecipeBook();
List recipe1Ingredients = new ArrayList<>();
recipe1Ingredients.add("Ingredient A");
recipe1Ingredients.add("Ingredient B");
recipe1Ingredients.add("Ingredient C");
recipeBook.addRecipe("Recipe 1", recipe1Ingredients);
List recipe2Ingredients = new ArrayList<>();
recipe2Ingredients.add("Ingredient X");
recipe2Ingredients.add("Ingredient Y");
recipe2Ingredients.add("Ingredient Z");
recipeBook.addRecipe("Recipe 2", recipe2Ingredients);
List ingredients = recipeBook.getIngredients("Recipe 1");
if (ingredients != null) {
System.out.println("Ingredients for Recipe 1:");
for (String ingredient : ingredients) {
System.out.println(ingredient);
}
} else {
System.out.println("Recipe not found");
}
}
}
这个示例中,我们创建了一个RecipeBook
类来管理所有的食谱。addRecipe
方法用于向食谱书中添加新的食谱和配料列表。getIngredients
方法使用特定的食谱名称作为参数,返回该食谱的配料列表。在main
方法中,我们示范了如何使用getIngredients
方法来获取特定食谱的配料列表,并将其打印出来。
上一篇:编写一个方法containsInstanceOf(Class<? extends SuperClassName>)
下一篇:编写一个方法来确定一个数是否能被11整除,并返回true或false。此外,生成从11到110的100个随机整数。