Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: How to iterate through an array that contains null elements

  1. #1
    Junior Member
    Join Date
    Jul 2021
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default How to iterate through an array that contains null elements

    I have a bunch of code that works.
    The program is giving me an error wen I run it and it says:

    Cannot read field "costOf" because "array[1]" is null

    I have done this with a for each loop and I have tried just typing in manually instead of a for each loop. and when I reach the first null I guess it gives me the error.
    I need to have a data structure that only holds 7 places (for each day of the week) so anything that automatically resizes does not work for my application.

    So I initialize my arrays to [7] and had a for loop that went until i<array.length

    I also have tried initializing all the elements of the array to an object of the same type that I need to hold (I created an object that has mostly zero values and i assign the same object to all the elements in the array so it start off with that object) --- this doesn't work as well, gives me the same exact error. This is not my preferred solution since I wont know what spots are blank and which are.

    My question is simple but I cannot find the answer anywhere in the internet. How to loop trough an array that has null spots. (an the null spot could be anywhere in the array.)

    Thank you

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: How to iterate through an array that contains null elements

    How to loop trough an array that has null spots.
    Test the element is not null before trying to use it.
    if(array[i] == null)
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jul 2021
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How to iterate through an array that contains null elements

    Quote Originally Posted by Norm View Post
    Test the element is not null before trying to use it.
    if(array[i] == null)
    Norm,

    That totally worked! I cant understand why this wasn't easier to find online.

    I have kind of the same issue still although for sure I am doing something wrong.

    This is my meal Planner consructor which basically makes a weeks worth of space for recipes. I create an array with 7 spots for the breakfast recipes, one for lunch, one for dinners. 9i am just showing the one for breakfasts in interests of saving space). The loop I made so that there is no empty spots on the array, which I dont really want to do, I'd rather have the array partly empty so that I know when there is no recipe in the spot of the array. I can have a "blank" recipe which has name, cost of zero (0) etc so the array is not supposed to be empty.

     Planner(int day, int month,  int year){
            Recipe blankRecipe = new Recipe("blankRecipe");
            startDate = LocalDate.of(year, month, day);
            LocalDate dateAdd = startDate;
            endDate = dateAdd.plusDays(7);
     
     
            Recipe[] breakfastRecipes = new Recipe[7];
                for (int i = 0; i<breakfastRecipes.length; i++){
                    breakfastRecipes[i] = new Recipe();
                }

    if I was to do something like this on the Main it would give me the same error or a null array

    System.out.println(july5.breakfastRecipes[1].name);

    I added a recipe through the addRecipe() method in spot 0 of the array, but nowhere else. (but its still supposed to have the blank recipe in all the other spots.

    This is my "blankRecipe" constructor

    public Recipe(String recipeName){
            Ingredient blankIngredient = new Ingredient("blankIngredient");
            name = recipeName;
            //name = "BlankRecipe";
            category = "Blank";
            //costOfRecipe = 0d;
            numberOfIngredients = 1;
            recipe.put(blankIngredient, 0d);
        }

    Thank you

    Ian

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: How to iterate through an array that contains null elements

    Do you have a question?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jul 2021
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How to iterate through an array that contains null elements

    Quote Originally Posted by Norm View Post
    Do you have a question?
    Hi Norm,

    Yes:

    How come even when I use my default constructor and I populate the array completely with a "recipe" in each slot of he array I still get a "is null" error.

    Then I made a more "complex" constructor which would give me kind of a real recipe with an ingredient and all the properties for the recipe defined with a name and such and it still gives me the same "null" error. In my eyes every entry of the array should have the blankRecipe in each spot (blankRecipe has 1 ingredient and the recipe costs 0 dollars the ingredient is "blankIngredient" and costs zero dollars as well. - so if I'm tring to look at "nameOfRecipe" of the second spot of the array it should give m "blankRecipe" which it doesnt, it gives me
    "Cannot read field "name" because "july5.breakfastRecipes[1]" is null" this error.

    Thank you,

    Ian

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: How to iterate through an array that contains null elements

    get a "is null" error.
    There must be a variable with a null value.
    Where does the text of that error come from? I do not recognize it.

    Please copy the full text of the error message and paste it here. It has important info about the error.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Jul 2021
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How to iterate through an array that contains null elements

    Quote Originally Posted by Norm View Post
    There must be a variable with a null value.
    Where does the text of that error come from? I do not recognize it.

    Please copy the full text of the error message and paste it here. It has important info about the error.
    Norm,


    I have created a planner called july5 and added a recipe called stirFry
    this is the code in main:
    Planner july5 = new Planner(6, 7, 2021);
            july5.addRecipe(stirFry, 0);

    addRecipe only adds recipes to the breakfastRecipes array.
    public void addRecipe(Recipe recipe, int day){
            Array.set(breakfastRecipes,day,recipe);
            costOfBkWk = costOfBkPlanner(breakfastRecipes);
            //Need to call cost costOfBkPlanner to update cost. - may be done.
        }


    The line of cdoe #51 in main is the following:
    System.out.println(july5.breakfastRecipes[1].name);
    If I change it to: System.out.println(july5.breakfastRecipes[0].name); so that the index in the array is ZERO the code line works fine.

    The complete error is:
    Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "july5.breakfastRecipes[1]" is null
    	at com.mealplanner.Main.main(Main.java:51)

    this is my recipe constructor I am using to populate the array when a new "planner" is created
    public Recipe(String recipeName){
            Ingredient blankIngredient = new Ingredient("blankIngredient");  //********** this is the recipe that gets created to populate the array*********
            name = recipeName;
            //name = "BlankRecipe";
            category = "Blank";
            //costOfRecipe = 0d;
            numberOfIngredients = 1;
            recipe.put(blankIngredient, 0d);

    and this is the code for the planner constructor I am using which creates a recipe named blankRecipe -- this is why I dont understand that the name is null.
    Then the constructor uses that recipe to populate the array. (Again, not my preferred method since now I always will have a recipe in the array in theory, not that its behaving like that.
    Planner(int day, int month,  int year){
            Recipe blankRecipe = new Recipe("blankRecipe");
            startDate = LocalDate.of(year, month, day);
            LocalDate dateAdd = startDate;
            endDate = dateAdd.plusDays(7);
     
     
            Recipe[] breakfastRecipes = new Recipe[7];
                for (int i = 0; i<breakfastRecipes.length; i++){
                    breakfastRecipes[i] = new Recipe();
                }
            Recipe[] lunchRecipes = new Recipe[7];
            for (int i = 0; i<lunchRecipes.length; i++) {
                lunchRecipes[i] = blankRecipe;
            }
            Recipe[] dinnerRecipes = new Recipe[7];
            for (int i = 0; i<dinnerRecipes.length; i++) {
                dinnerRecipes[i] = blankRecipe;
            }
     
            HashMap<Ingredient,Double> shoppingListBk = new HashMap<Ingredient, Double>();
            HashMap<Ingredient,Double> shoppingListLn = new HashMap<Ingredient, Double>();
            HashMap<Ingredient,Double> shoppingListDn = new HashMap<Ingredient, Double>();
     
            double costOfBkWk = 0;
            double costOfLnWk = 0;
            double costOfDnWk = 0;
        }

    Thank you again,

    Ian

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: How to iterate through an array that contains null elements

    Some how the code must be executing that line before the variable is given a value. There is no way I can compile and execute the code to test it given what has been posted.

    It looks like the variable: breakfastRecipes is declared local to the Planner constructor. That means that when the constructor exits, the variable and it values goes away. Is there another variable with the name: breakfastRecipes declared at the class level?
    If the code is supposed to put values in the class level variable, remove its declaration from the constructor and just assign it values in the constructor.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Jul 2021
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How to iterate through an array that contains null elements

    Norm,

    breakfastRecipes is not a variable, its a field in the Planner Class.

    I will post all the code ( I have a Main a, Ingredient, a Recipe, and a Planner class in the same package.
    I have comments on things and I am leaving them just as I had it.

    ---Main---
    package com.mealplanner;
     
    import java.util.Scanner;
     
    public class Main {
     
        public static void main(String[] args) {
            /*System.out.println("Welcome to the meal planer");
            System.out.println("type a unit for your new ingredient");
            Scanner scanner = new Scanner(System.in);
            String userInput = scanner.nextLine();
            Ingredient apple = new Ingredient();
            apple.setUnitPurchased(userInput);
            System.out.println(apple.getUnitPurchased());*/
            Ingredient avocado = new Ingredient("avocado", "GRAMS", true, 200, 5);
            //System.out.println(avocado.name + ", " + avocado.pricePerUnit + ", " + avocado.unitOfMeasure);
            System.out.println(String.format("Your fruit is %s, which costs %f dollars per %s.", avocado.name, avocado.pricePerUnit, avocado.unitOfMeasure));
            Ingredient rice = new Ingredient("rice", "KILOGRAMS", false, 3, 9);
            Ingredient pepper = new Ingredient("pepper", "GRAMS", true, 500, 5);
     
            Recipe stirFry = new Recipe("Stir Fry", "Dinner", avocado, .5, rice, 0.5, pepper, 1);
            System.out.println("You are about to cook " + stirFry.getName() + "!");
            System.out.println("Your recipe has " + stirFry.getNumberOfIngredients() + " ingredients.");
            System.out.println("Ingredient list and amounts: " + stirFry.getRecipe());
            System.out.println("Avocado costs:" + avocado.getPricePerUnit() + " per " + avocado.unitOfMeasure);
            System.out.println("Rice costs: " + rice.getPricePerUnit() + " per " + rice.unitOfMeasure);
            System.out.println("Pepper costs: " + pepper.getPricePerUnit() + " per " + pepper.unitOfMeasure);
            System.out.println(stirFry.recipe.entrySet());
            System.out.println("Stir Fry costs: " + stirFry.costOfRecipe + " dollars, for one family dinner");
            Ingredient beef = new Ingredient("beef", "GRAMS", true, 500, 10);
            stirFry.add1Ingredient(beef, 2.0d);
            System.out.println("Beef costs: " + beef.getPricePerUnit() + " per " + beef.unitOfMeasure);
            System.out.println(stirFry.getRecipe());
            System.out.println("Stir Fry costs: " + stirFry.costOfRecipe + " dollars, for one family dinner");
     
            Ingredient parsley = new Ingredient("parsley", "GRAMS", false, 20, 1);
            Recipe guacamole = new Recipe("Guacamole", "Snack", avocado, .5, parsley, .1);
            Planner july5 = new Planner(6, 7, 2021);
            july5.addRecipe(stirFry, 0);
            System.out.println("Start of planner " + july5.startDate);
            //for (Recipe i : july5.breakfastRecipes)
            System.out.println("Recipe name: " + july5.breakfastRecipes[0].name);
            //july5.addBreakfast(guacamole, 0);
            //System.out.println("Breakfast recipes array size " +july5.breakfastRecipes.size());
            /*for (Recipe i : july5.breakfastRecipes) {
                System.out.println("Recipe name: " + i.name);
                System.out.println("Recipe Cost: " + i.costOfRecipe);
            }*/
            System.out.println(july5.breakfastRecipes[0].name);
            System.out.println(july5.costOfBkWk);
            System.out.println(july5.breakfastRecipes[1].name);
     
     
        }
    }

    -----Ingredient-----
    package com.mealplanner;
     
    public class Ingredient {
        String name = null;
        Boolean organic = false;
        String unitPurchased = null;
        String unitOfMeasure;
        float purchasePrice;
        float purchasedAmount;
        float pricePerUnit;
     
        public Ingredient(){}
     
        public Ingredient(String name) {
            //name = "BlankIngredient";
            unitPurchased = "GRAMS";
            unitOfMeasure = "KILOGRAM";
            purchasePrice = 0;
            purchasedAmount = 0;
            pricePerUnit = 0;
        }
     
        public Ingredient(String ingName, String ingUnitPurchased, boolean ingOrganic, float ingAmount, float ingPrice) {
            name = ingName;
            unitPurchased = ingUnitPurchased;
            unitOfMeasure = null;
            organic = ingOrganic;
            purchasedAmount = ingAmount;
            purchasePrice = ingPrice;
            pricePerUnit = calculatePricePerUnit(this);
        }
     
     
        public float calculatePricePerUnit(Ingredient ingredient) {
            String unit = ingredient.unitPurchased;
            float calculatedPrice = 0;
     
            switch (unit) {
                case "GRAMS" -> {
                    calculatedPrice = (1000f / ingredient.purchasedAmount) * ingredient.purchasePrice;
                    this.setUnitOfMeasure("KILOGRAM");
                }
                case "KILOGRAMS" -> {
                    calculatedPrice = (ingredient.purchasePrice / ingredient.purchasedAmount);
                    this.setUnitOfMeasure("KILOGRAM");
                }
                case "MILLILITERS" -> {
                    calculatedPrice = (1000f / ingredient.purchasedAmount) * ingredient.purchasePrice;
                    this.setUnitOfMeasure("LITER");
                }
                case "LITERS" -> {
                    calculatedPrice = (ingredient.purchasePrice / ingredient.purchasedAmount);
                    this.setUnitOfMeasure("LITER");
                }
                case "CUPS" -> {
                    calculatedPrice = (1000f / (ingredient.purchasedAmount * 0.237f)) * ingredient.purchasePrice;
                    this.setUnitOfMeasure("LITER");
                }
                case "TABLESPOONS" -> {
                    calculatedPrice = (1000f / (ingredient.purchasedAmount * 0.0147868f)) * ingredient.purchasePrice;
                    this.setUnitOfMeasure("LITER");
                }
                case "TEASPOONS" -> {
                    calculatedPrice = (1000f / (ingredient.purchasedAmount * 0.00492892f)) * ingredient.purchasePrice;
                    this.setUnitOfMeasure("LITER");
                }
            }
            return calculatedPrice;
        }
     
     
        public String getUnitPurchased() {
            return unitPurchased;
        }
     
        public void setUnitPurchased(String unitPurchased) {
            this.unitPurchased = unitPurchased;
        }
     
        public Boolean getOrganic() {
            return organic;
        }
     
        public float getPricePerUnit() {
            return pricePerUnit;
        }
     
        public float getPurchasedAmount() {
            return purchasedAmount;
        }
     
        public float getPurchasePrice() {
            return purchasePrice;
        }
     
        public String getName() {
            return name;
        }
     
        public String getUnitOfMeasure() {
            return unitOfMeasure;
        }
     
        public void setName(String name) {
            this.name = name;
        }
     
        public void setOrganic(Boolean organic) {
            this.organic = organic;
        }
     
        public void setPricePerUnit(float pricePerUnit) {
            this.pricePerUnit = pricePerUnit;
        }
     
        public void setPurchasedAmount(float purchasedAmount) {
            this.purchasedAmount = purchasedAmount;
        }
     
        public void setPurchasePrice(float purchasePrice) {
            this.purchasePrice = purchasePrice;
        }
     
        public void setUnitOfMeasure(String unitOfMeasure) {
            this.unitOfMeasure = unitOfMeasure;
        }
     
        public enum UnitPurchased {
        GRAMS, KILOGRAMS, MILLILITERS, LITERS, CUPS, TABLESPOONS, TEASPOONS
        }
     
        public enum UnitOfMeasure {
        LITER, KILOGRAM
        }
     
        public enum IngCategory {
            BAKING, CAN, CONDIMENT, DRY_GOODS, FRUIT, HERB, MEAT, VEGETABLE
        }
    }

    -----Recipe-----
    package com.mealplanner;
     
    import java.util.*;
     
    public class Recipe {
        String name = null;
        String category= null;
        double costOfRecipe;
        int numberOfIngredients = 0;
        HashMap<Ingredient, Double> recipe = new HashMap();
        /*
        ArrayList <Ingredient> ingredients = new ArrayList<Ingredient>();
        ArrayList<Double> amounts = new ArrayList<Double>();
        */
     
        public Recipe(){}
     
        public Recipe(String recipeName){
            Ingredient blankIngredient = new Ingredient("blankIngredient");
            name = recipeName;
            //name = "BlankRecipe";
            category = "Blank";
            //costOfRecipe = 0d;
            numberOfIngredients = 1;
            recipe.put(blankIngredient, 0d);
        }
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount,Ingredient ing3Name, double ing3Amount ){
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            recipe.put(ing3Name, ing3Amount);
            numberOfIngredients = 3;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
        public String getName(){
            return name;
        }
     
        public int getNumberOfIngredients() {
            return numberOfIngredients;
        }
     
        public Set<Ingredient> getRecipe() {
            return recipe.keySet();
        }
     
    public static double calculateCostOfRecipe(HashMap<Ingredient, Double> recipe){
        // loops through the hashmap and multiplies the amount and unit price
            double recipeCost = 0;
            double multiplication = 0;
     
        for (Map.Entry<Ingredient, Double> entry: recipe.entrySet()) {
            multiplication = (entry.getKey().pricePerUnit) * entry.getValue();
            recipeCost += multiplication;
        }
        return recipeCost;
    }
     
        void add1Ingredient(Ingredient ing, Double amount){
            recipe.put(ing, amount);
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
     
        //Constructors
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount){
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            numberOfIngredients = 2;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount,Ingredient ing3Name, double ing3Amount, Ingredient ing4Name, double ing4Amount ){
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            recipe.put(ing3Name, ing3Amount);
            recipe.put(ing4Name, ing4Amount);
            numberOfIngredients = 4;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
     
        //Constructors
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount,Ingredient ing3Name, double ing3Amount,
                      Ingredient ing4Name, double ing4Amount, Ingredient ing5Name, double ing5Amount ){
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            recipe.put(ing3Name, ing3Amount);
            recipe.put(ing4Name, ing4Amount);
            recipe.put(ing5Name, ing5Amount);
            numberOfIngredients = 5;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount,Ingredient ing3Name, double ing3Amount,
                      Ingredient ing4Name, double ing4Amount, Ingredient ing5Name, double ing5Amount,
                      Ingredient ing6Name, double ing6Amount ){
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            recipe.put(ing3Name, ing3Amount);
            recipe.put(ing4Name, ing4Amount);
            recipe.put(ing5Name, ing5Amount);
            recipe.put(ing6Name, ing6Amount);
            numberOfIngredients = 6;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount,Ingredient ing3Name, double ing3Amount,
                      Ingredient ing4Name, double ing4Amount, Ingredient ing5Name, double ing5Amount,
                      Ingredient ing6Name, double ing6Amount, Ingredient ing7Name, double ing7Amount ){
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            recipe.put(ing3Name, ing3Amount);
            recipe.put(ing4Name, ing4Amount);
            recipe.put(ing5Name, ing5Amount);
            recipe.put(ing6Name, ing6Amount);
            recipe.put(ing7Name, ing7Amount);
            numberOfIngredients = 7;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount,Ingredient ing3Name, double ing3Amount,
                      Ingredient ing4Name, double ing4Amount, Ingredient ing5Name, double ing5Amount,
                      Ingredient ing6Name, double ing6Amount, Ingredient ing7Name, double ing7Amount,
                      Ingredient ing8Name, double ing8Amount) {
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            recipe.put(ing3Name, ing3Amount);
            recipe.put(ing4Name, ing4Amount);
            recipe.put(ing5Name, ing5Amount);
            recipe.put(ing6Name, ing6Amount);
            recipe.put(ing7Name, ing7Amount);
            recipe.put(ing8Name, ing8Amount);
            numberOfIngredients = 8;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount,Ingredient ing3Name, double ing3Amount,
                      Ingredient ing4Name, double ing4Amount, Ingredient ing5Name, double ing5Amount,
                      Ingredient ing6Name, double ing6Amount, Ingredient ing7Name, double ing7Amount,
                      Ingredient ing8Name, double ing8Amount, Ingredient ing9Name, double ing9Amount) {
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            recipe.put(ing3Name, ing3Amount);
            recipe.put(ing4Name, ing4Amount);
            recipe.put(ing5Name, ing5Amount);
            recipe.put(ing6Name, ing6Amount);
            recipe.put(ing7Name, ing7Amount);
            recipe.put(ing8Name, ing8Amount);
            recipe.put(ing9Name, ing9Amount);
            numberOfIngredients = 9;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
     
        public Recipe(String name, String category, Ingredient ing1Name, double ing1Amount,
                      Ingredient ing2Name, double ing2Amount,Ingredient ing3Name, double ing3Amount,
                      Ingredient ing4Name, double ing4Amount, Ingredient ing5Name, double ing5Amount,
                      Ingredient ing6Name, double ing6Amount, Ingredient ing7Name, double ing7Amount,
                      Ingredient ing8Name, double ing8Amount, Ingredient ing9Name, double ing9Amount,
                      Ingredient ing10Name, double ing10Amount) {
            this.name = name;
            this.category = category;
            recipe.put(ing1Name, ing1Amount);
            recipe.put(ing2Name, ing2Amount);
            recipe.put(ing3Name, ing3Amount);
            recipe.put(ing4Name, ing4Amount);
            recipe.put(ing5Name, ing5Amount);
            recipe.put(ing6Name, ing6Amount);
            recipe.put(ing7Name, ing7Amount);
            recipe.put(ing8Name, ing8Amount);
            recipe.put(ing9Name, ing9Amount);
            recipe.put(ing10Name, ing10Amount);
            numberOfIngredients = 10;
            costOfRecipe = calculateCostOfRecipe(recipe);
        }
    }

    ----Planner------
    package com.mealplanner;
    import org.jetbrains.annotations.NotNull;
     
    import java.lang.reflect.Array;
    import java.time.*;
    import java.util.ArrayList;
    import java.util.Scanner;
     
     
    import java.util.HashMap;
     
     
    public class Planner {
        LocalDate startDate = null;
        LocalDate endDate = null;
        Recipe[] breakfastRecipes = new Recipe[7];
        ArrayList<Recipe> lunchRecipes     = new ArrayList<Recipe>(7);
        ArrayList<Recipe> dinnerRecipes    = new ArrayList<Recipe>(7);
     
        HashMap<Ingredient,Double> shoppingListBk = new HashMap<Ingredient, Double>();
        HashMap<Ingredient,Double> shoppingListLn = new HashMap<Ingredient, Double>();
        HashMap<Ingredient,Double> shoppingListDn = new HashMap<Ingredient, Double>();
     
        double costOfBkWk = 0;
        double costOfLnWk = 0;
        double costOfDnWk = 0;
     
        Planner(){}
     
        Planner(int day, int month,  int year){
            Recipe blankRecipe = new Recipe("blankRecipe");
            startDate = LocalDate.of(year, month, day);
            LocalDate dateAdd = startDate;
            endDate = dateAdd.plusDays(7);
     
     
            Recipe[] breakfastRecipes = new Recipe[7];
                for (int i = 0; i<breakfastRecipes.length; i++){
                    breakfastRecipes[i] = new Recipe();
                }
            Recipe[] lunchRecipes = new Recipe[7];
            for (int i = 0; i<lunchRecipes.length; i++) {
                lunchRecipes[i] = blankRecipe;
            }
            Recipe[] dinnerRecipes = new Recipe[7];
            for (int i = 0; i<dinnerRecipes.length; i++) {
                dinnerRecipes[i] = blankRecipe;
            }
     
            HashMap<Ingredient,Double> shoppingListBk = new HashMap<Ingredient, Double>();
            HashMap<Ingredient,Double> shoppingListLn = new HashMap<Ingredient, Double>();
            HashMap<Ingredient,Double> shoppingListDn = new HashMap<Ingredient, Double>();
     
            double costOfBkWk = 0;
            double costOfLnWk = 0;
            double costOfDnWk = 0;
        }
        public void addRecipe(Recipe recipe, int day){
            Array.set(breakfastRecipes,day,recipe);
            costOfBkWk = costOfBkPlanner(breakfastRecipes);
            //Need to call cost costOfBkPlanner to update cost. - may be done.
        }
     
        public void addBreakfast(Recipe recipe, int day){
            if (breakfastRecipes[day]== null) {
                breakfastRecipes[day] = recipe;
                costOfBkWk = costOfBkPlanner(breakfastRecipes);
            }else{
                System.out.println("the spot already has a recipe");
                System.out.println("Do you want to replace it");
                Scanner input = new Scanner(System.in);
                String yesNo = input.nextLine();
                        if (yesNo.equals("yes")){
                            breakfastRecipes[day] = recipe;
                        }
                        else{
                            System.out.println("Existing recipe was not replaced");
     
                        }
            }
     
        }
     
        public double costOfBkPlanner(Recipe[] recipe){
            double internalCost = 0;
     
            /*for(Recipe iRecipe: recipe) {
                if(iRecipe == null)
     
                internalCost += iRecipe.costOfRecipe;
            }*/
            for(int i = 0; i<recipe.length; i++)
                if(recipe[i] == null)
                    i++;
                else {
                    internalCost += recipe[i].costOfRecipe;
                }
            return internalCost;
        }
        /*public double costOfAnyPlanner(Recipe[]){
     
        }*/
     
     
     
     
    }


    Thank you,

    Ian

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: How to iterate through an array that contains null elements

    breakfastRecipes is not a variable, its a field in the Planner Class.
    A variable holds values in a program. A field is a special kind of variable.

    The variables: breakfastRecipe, lunchRecipe and dinnerRecipes are declared in two places: one as a field in the class and one as a local variable in the constructor. The code in the Planner class's constructor assigns values to the local variable, not the class level variable. The code needs to be changed so that is assigns values to the class level variable and does not declare a local variable with the same name.

       class SomeClass {
          int someVar;     // declare class level variable
     
          SomeClass() {
             int someVar = 22;   // declare local variable with same name and assign it a value
          }
       }
    To have the SomeClass constructor assign a value to the class level variable, remove the variable's declaration:
            someVar = 22;    // assign value to class level variable
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Jul 2021
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How to iterate through an array that contains null elements

    Norm,

    Conceptually what you say I understand but I guess I dont since I dont know how to do what you mean.

    Where do I have to delete/or/modify?

    Thank you,

    Ian

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: How to iterate through an array that contains null elements

    The middle statement here declares the variable breakfastRecipes and assigns it a value:
        LocalDate endDate = null;
        Recipe[] breakfastRecipes = new Recipe[7];
        ArrayList<Recipe> lunchRecipes     = new ArrayList<Recipe>(7);

    the first statement here declares a variable with the same name and assigns it a value:
            Recipe[] breakfastRecipes = new Recipe[7];    //<<<  Declares another variable with the same name
                for (int i = 0; i<breakfastRecipes.length; i++){
                    breakfastRecipes[i] = new Recipe();
                }
    The second declaration is local to the constructor and will go away when the constructor exits. If also hides the variable at the class level and keeps it from being accessed. Remove that second declaration to use class level variable.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Jul 2021
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How to iterate through an array that contains null elements

    WOW!

    You are blowing my mind!

    So now if I leave the default constructor to build a 'recipe' and populate the array the program gives me a "null" when i ask for the name of a recipe entry that has not been created, which is awesome! i doesnt even give me an error

    How come I used to get an error for null and now I dont?

    So whatever I declare in the constructor goes away? my blankRecipe is just a filler but would that go away or would that stick with the array?

    I had read about variable hiding but I though that when you have a field in the constructor it just meant that you got to declare it with a different value or in a different way. But again, I am jut starting at this.

    Thank you again!

    Ian

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: How to iterate through an array that contains null elements

    whatever I declare in the constructor goes away? my blankRecipe is just a filler but would that go away or would that stick with the array?
    That variable would go away but its value(a reference to an instance of a class) has been assigned to other variables that still exist.
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    Ian_dude (July 9th, 2021)

Similar Threads

  1. How would I iterate through an array 'in chunks'?
    By vividMario52 in forum Loops & Control Statements
    Replies: 2
    Last Post: April 11th, 2013, 04:21 PM
  2. [SOLVED] matching elements of one array with another array.
    By shenaz in forum Java Theory & Questions
    Replies: 13
    Last Post: March 29th, 2013, 10:31 AM
  3. How to sum up elements in an array?
    By D-X69 in forum Java Theory & Questions
    Replies: 2
    Last Post: May 28th, 2012, 01:21 AM
  4. Iterate over array, changing current object?
    By slimchance in forum Loops & Control Statements
    Replies: 7
    Last Post: May 14th, 2012, 04:52 PM