You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

校园食谱盒项目:如何从ArrayList中获取totalCalories变量

解决Recipe Box中访问totalCalories变量的问题

嘿,我来帮你搞定这个问题!核心点在于:Java里的私有(private)成员变量是不能直接从类外部访问的,所以你需要给Recipe类里的totalCalories添加一个公共的getter方法,这是Java封装机制的标准做法。

步骤1:补全并添加getter方法到Recipe类

首先先把你代码里没写完的totalCalories变量补全,然后加上getter方法:

package recipebox;
import java.util.Scanner;
import java.util.ArrayList;

public class Recipe {
    private String recipeName;
    private int servings;
    private ArrayList recipeIngredients; // 建议这里泛型化,比如ArrayList<Ingredient>
    private double totalCalories; // 补全你的变量定义

    // 添加这个getter方法,用来获取totalCalories
    public double getTotalCalories() {
        return totalCalories;
    }

    // 这里可以保留你原有的其他方法,比如构造器、设置热量的方法等等
}

小提示:你的recipeIngredients ArrayList最好加上泛型,比如ArrayList<Ingredient>,这样类型更安全,避免后续的类型转换问题。

步骤2:从ArrayList中访问单个Recipe的totalCalories

假设你有一个存储Recipe对象的ArrayList,比如:

ArrayList<Recipe> recipeBox = new ArrayList<>();
// 这里假设你已经往recipeBox里添加了若干Recipe对象

获取单个食谱的热量

如果你想访问列表中某一个特定食谱的总热量,直接通过索引获取对象,再调用getter方法即可:

// 获取列表中第一个食谱的总热量(索引从0开始)
double firstRecipeCal = recipeBox.get(0).getTotalCalories();

统计所有食谱的总热量

如果要统计整个食谱盒里所有食谱的热量总和,遍历ArrayList累加就行:

double overallTotalCalories = 0.0;
for (Recipe recipe : recipeBox) {
    overallTotalCalories += recipe.getTotalCalories();
}
// 现在overallTotalCalories就是所有食谱的总热量之和了

注意事项

记得确保你的totalCalories变量已经被正确赋值了(比如在食谱创建时计算好并设置进去),不然getter方法返回的会是double类型的默认值0.0哦。

内容的提问来源于stack exchange,提问作者Andy F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:47:03