Я делаю Коробку рецептов для школы, и мне нужна помощь в понимании того, как получить доступ к одной переменной внутри ArrayList. Мне нужно получить доступ только к переменной totalCalories в файле рецепта, а не к ингредиенту, чтобы я мог добавить общее количество калорий в самом рецепте. Вот код.
package recipebox;
import java.util.Scanner;
import java.util.ArrayList;
public class Recipe {
private String recipeName;
private int servings;
private ArrayList recipeIngredients;
private double totalRecipeCalories;
public String getRecipeName() {
return recipeName;
}
public void setRecipeName(String recipeName) {
this.recipeName = recipeName;
}
public double getTotalRecipeCalories() {
return totalRecipeCalories;
}
public void setTotalRecipeCalories(double totalRecipeCalories) {
this.totalRecipeCalories = totalRecipeCalories;
}
public ArrayList getRecipeIngredients() {
return recipeIngredients;
}
public void setRecipeIngredients(ArrayList recipeIngredients) {
this.recipeIngredients = recipeIngredients;
}
public int getServings() {
return servings;
}
public void setServings(int servings) {
this.servings = servings;
}
public Recipe() {
this.recipeName = "";
this.servings = 0;
this.recipeIngredients = new ArrayList<>();
this.totalRecipeCalories = 0;
}
public Recipe(String recipeName, int servings, ArrayList <String> recipeIngredients, double totalRecipeCalories) {
this.recipeName = recipeName;
this.servings = servings;
this.recipeIngredients = recipeIngredients;
this.totalRecipeCalories = totalRecipeCalories;
}
public void printRecipe() {
int singleServingCalories = (int)(totalRecipeCalories/getServings());
System.out.println("Recipe: " + getRecipeName());
System.out.println("Serves: " + getServings());
System.out.println("Ingredients:");
System.out.println(recipeIngredients);
System.out.println("Each serving has " + singleServingCalories + " Calories.");
}
public void addIngredient() {
recipeIngredients.add(Ingredient.createNewIngredient());
}
public static void main(String[] args) {
createNewRecipe();
}
public static Recipe createNewRecipe() {
double totalRecipeCalories = 0;
ArrayList <String> recipeIngredients = new ArrayList();
boolean addMoreIngredients = true;
Recipe myRecipe = new Recipe();
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter the recipe name: ");
while (!scnr.hasNextLine()){
System.out.println("Invalid input");
System.out.println("Please enter the recipe name: ");
scnr.nextLine();
}
String recipeName = scnr.nextLine();
System.out.println("Please enter the number of servings: ");
while (!scnr.hasNextInt()){
System.out.println("Invalid input");
System.out.println("Please enter the number of servings: ");
scnr.nextLine();
}
int servings = scnr.nextInt();
do {
myRecipe.addIngredient();
totalRecipeCalories += recipeIngredients.get(totalCalories);
Остальное я не включил, потому что это не имеет значения. Последняя строка неверна и требует исправления. Вот код ингредиента.
package recipebox;
import java.util.Scanner;
public class Ingredient {
private String nameOfIngredient;
private float numberUnits;
private String unitMeasurement;
private int numberCaloriesPerUnit;
private double totalCalories;
/**
* @return the nameOfIngredient
*/
public String getNameOfIngredient() {
return nameOfIngredient;
}
/**
* @param nameOfIngredient the nameOfIngredient to set
*/
public void setNameOfIngredient(String nameOfIngredient) {
this.nameOfIngredient = nameOfIngredient;
}
/**
* @return the numberUnits
*/
public float getNumberUnits() {
return numberUnits;
}
/**
* @param numberUnits the numberUnits to set
*/
public void setNumberUnits(float numberUnits) {
this.numberUnits = numberUnits;
}
/**
* @return the numberCaloriesPerUnit
*/
public int getNumberCaloriesPerUnit() {
return numberCaloriesPerUnit;
}
/**
* @param numberCaloriesPerUnit the numberCaloriesPerUnit to set
*/
public void setNumberCaloriesPerUnit(int numberCaloriesPerUnit) {
this.numberCaloriesPerUnit = numberCaloriesPerUnit;
}
/**
* @return the totalCalories
*/
public double getTotalCalories() {
return totalCalories;
}
/**
* @param totalCalories the totalCalories to set
*/
public void setTotalCalories(double totalCalories) {
this.totalCalories = totalCalories;
}
/**
* @return the unitMeasurement
*/
public String getUnitMeasurement() {
return unitMeasurement;
}
/**
* @param unitMeasurement the unitMeasurement to set
*/
public void setUnitMeasurement(String unitMeasurement) {
this.unitMeasurement = unitMeasurement;
}
public Ingredient() {
this.nameOfIngredient = "";
this.numberUnits = 0.00f;
this.unitMeasurement = "";
this.numberCaloriesPerUnit = 0;
this.totalCalories = 0.0;
}
public Ingredient(String nameOfIngredient, float numberUnits, String unitMeasurement, int numberCaloriesPerUnit, double totalCalories) {
this.nameOfIngredient = nameOfIngredient;
this.numberUnits = numberUnits;
this.unitMeasurement = unitMeasurement;
this.numberCaloriesPerUnit = numberCaloriesPerUnit;
this.totalCalories = totalCalories;
}
public static Ingredient createNewIngredient() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter the name of the ingredient: ");
while (!scnr.hasNextLine()){
System.out.println("Invalid input");
System.out.println("Please enter the name of the ingredient: ");
scnr.nextLine();
}
String nameOfIngredient = scnr.nextLine();
System.out.println("What unit of measurement will you be using? ");
while (!scnr.hasNextLine()){
System.out.println("Invalid input");
System.out.println("What unit of measurement will you be using? ");
scnr.nextLine();
}
String unitMeasurement = scnr.nextLine();
System.out.println("Please enter the number of " + unitMeasurement + " of " + nameOfIngredient + " we will need: ");
while (!scnr.hasNextFloat()) {
System.out.println("Invalid input");
System.out.println("Please enter the number of " + unitMeasurement + " of " + nameOfIngredient + " we will need: ");
scnr.nextLine();
}
float numberUnits = scnr.nextFloat();
System.out.println("Please enter the number of calories per " + unitMeasurement + ": ");
while (!scnr.hasNextInt()) {
System.out.println("Invalid input");
System.out.println("Please enter the number of calories per " + unitMeasurement + ": ");
scnr.nextLine();
}
int numberCaloriesPerUnit = scnr.nextInt();
double totalCalories = numberUnits * numberCaloriesPerUnit;
System.out.println(nameOfIngredient + " uses " + numberUnits + " " + unitMeasurement + " and has " + totalCalories + " calories.");
recipebox.Ingredient tempIngredient = new recipebox.Ingredient(nameOfIngredient, numberUnits, unitMeasurement, numberCaloriesPerUnit, totalCalories);
return tempIngredient;
}
}
Теперь, когда я отлаживаю файл рецепта, сразу после того, как он возвращается после получения ингредиентов, я вижу в списке переменных нужную мне переменную, но не могу понять, как к ней добраться.
Так выглядит меню переменных отладки
Если кто-то может помочь мне получить доступ к этой переменной и, возможно, объяснить начинающим, как вы это сделали, я был бы очень благодарен. Спасибо.
Вы должны завершить свой цикл do-while
В вашем коде System.out.println(recipeIngredients);. Вы уверены, что он печатается правильно? Никогда не пробовал так
Хороший глаз, это на самом деле из предыдущего кода, когда ингредиенты были собраны из самого файла рецепта. Вот почему recipeIngredients нужно собирать ингредиенты в массив, чтобы он распечатал все, когда это потребует программа recipeBox.




Переменная recipeIngredients - это список, а не объект. Список содержит объект типа Ingredient. Итак, чтобы получить значение общего количества калорий из ингредиента в списке, вам нужно сначала получить доступ к конкретному ингредиенту в этом списке, а затем взять его свойство.
Итак, это будет recipeIngredients.get(0).getTotalCalories() - чтобы получить общее количество калорий для первого ингредиента в списке.
Если вы хотите, чтобы это было для всего рецепта, вам понадобится цикл, который просматривает этот список и вычисляет. Что-то вроде:
int calories;
for(Object ingredient: recipeIngredients)
calories+= ((Ingredient)ingredient).getTotalCalories();
Также в коде:
System.out.println(recipeIngredients);
По этой же причине вы не будете печатать ничего полезного. Вам нужно пройтись по каждому ингредиенту и распечатать его красиво.
Вы также можете подумать о том, чтобы составить этот список типа Ingredient с использованием универсальных типов, чтобы вам не нужно было преобразовывать, и вы в любом случае используете его только для ингредиентов.
не будет ли здесь необходимости в приведении типов, поскольку recipeIngredients объявлен как ArrayList, а не как ArrayList<Ingredients>, и поэтому List.get() возвращает объект типа Object?
System.out.println (recipeIngredients); вызывается из программы recipeBox. Изначально у меня были все ингредиенты в файле рецепта, но мне пришлось его убрать.
может быть, попробуйте прочитать документацию ArrayList, чтобы узнать, есть ли у него метод для элемента 0 получать?