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.

Page 1 of 2 12 LastLast
Results 1 to 25 of 26

Thread: Trying to iterate through hashmap of objects from a class I created

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

    Default Trying to iterate through hashmap of objects from a class I created

    I am trying to calculate the cost of a "Recipe" object which contains a hashmap<Ingredient, Double>
    I have created the Ingredient class which contains pricePerUnit as one of its values.
    The Double is the amount of the ingredients that is needed for the recipe.

    I want to calculate the cost of the recipe given that each ingredient instance has a costPerUnit and we know how many units we need for each ingredient.
    costOfRecipe = ingredient.costPerUnit * amount (looping through all the 3 ingredients in the hashmap)
    I create the recipe with a constructor that takes 3 ingredients (since I don't know how to make a constructor with a variable amount of Ingredients/Amounts - help on this would also be appreciated)

    Code below for the ingredient and the recipe class and also the main class which works fine when I run the code. Sorry for the messy comments, I am stumbling as I go and I have accepted some "suggestions" from inteliJ like casting to Ingredient and some others.

    Recipe Class
    package com.mealplanner;
     
    import java.util.*;
     
    public class Recipe {
        String name = null;
        String category= null;
        double costOfRecipe;
        int numberOfIngredients = 0;
        ArrayList <Ingredient> ingredients = new ArrayList<Ingredient>();
        ArrayList<Double> amounts = new ArrayList<Double>();
        HashMap<Ingredient, Double> recipe = new HashMap();
     
     
        public Recipe(){}
     
        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 HashMap<Ingredient, Double> getRecipe() {
            return recipe;
        }
     
        /*
            public static double calculateCostOfRecipe(ArrayList<Ingredient> ingredients, ArrayList<Double> localAmounts){
                float costOfRecipe = 0;
     
                for (Ingredient i: ingredients) {
      //*************THIS IS WHERE I AM STUCK*********************
                    int counter = 1;
                    costOfRecipe += i.pricePerUnit* localAmounts.get(counter);
                    counter ++;
                }
                return costOfRecipe;
            }
            */
    public static double calculateCostOfRecipe(HashMap<Ingredient, Double> recipe){
        // Need to make the loop through the hashmap and multiply the amount and unit price
            double recipeCost = 0;
        List<Ingredient> listKey;
        List<Double> listValue;
     
        for (Map.Entry<Ingredient, Double> entry: recipe.entrySet()) {
            listKey = (List<Ingredient>) entry.getKey();
            listValue = Collections.singletonList(entry.getValue());
     
            //Ingredient i = new Ingredient();
            //i.(recipe.keySet());
            //if recipe.containsKey();
            //recipeCost = recipeCost;
        }
        int size = listKey.size();
        for(int i =0: i<= size: ++i){
            listKey(i)
        }
        return recipeCost;
    }
     
        /*void add1Ingredient(){
            ingredients.
        }*/
    }

    Ingredient Class

    package com.mealplanner;
     
    public class Ingredient extends  Recipe{
        String name = null;
        Boolean organic = false;
        String unitPurchased = null;
        String unitOfMeasure;
        float purchasePrice;
        float purchasedAmount;
        float pricePerUnit;
     
        public Ingredient() {
        }
     
        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
        }
    }

    Main Class
    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, 500, 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(stirFry.costOfRecipe);
            System.out.println(stirFry.recipe.keySet());
     
        }
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    I don't know how to make a constructor with a variable amount of Ingredients/Amounts
    Look at using varargs. Here is an example:
    public class TestVarArgs {
       // a simple class to pass using varargs
       static class Data {
          String name;
          int amt;
          Data(String name, int amt) {
             this.name = name;
             this.amt = amt;
          }
          public String toString() {
             return name + " " + String.valueOf(amt);
          }
       }
     
       TestVarArgs(Data... someData) {      //  Uses VarArgs
          // show the args
          for(Data d : someData) {
             System.out.println(d);
          }
       }
     
       public static void main(String[] args) {
          //  Pass variable number of args to the constructor
          TestVarArgs td1 = new TestVarArgs(new Data("a", 1), new Data("b",2));
          TestVarArgs td2 = new TestVarArgs(new Data("ax", 1), new Data("bx",2), new Data("cx", 3));
       }
    }
    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: Trying to iterate through hashmap of objects from a class I created

    Norm,
    Thank you for the answer.

    I will look into the varargs for sure.
    Do you have any input on the question on how to get to the ingredient say for example "avocado.costPerUnit" from having the Ingredient "avocado" inside the Hashmap passed into the calculateCostOfRecipe method?

    That method may as well be blank since I don't yet know how to access the and I just have been trying things inside of it. Talking it through should be ver siple since I have a list of ingredients paired with the amount that is needed of that ingredient, so since the ingredient has an "knows" ho much it costs per kilogram say and we know how many kilograms we need then should be a simple multiplication but getting to the value is my issue.

    Thank you

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    calculate the cost of the recipe
    Is this the logic:
    The recipe has the list of ingredients and the amount needed of that ingredient.
    Iterate through the list, get the type and amount of each ingredient,
    lookup the unit cost of that ingredient, use the amount of the ingredient to compute the cost of that ingredient and add that cost to the total
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    I think you need to establish your abstractions and classes properly. An Ingredient certainly doesn't extend Recipe. A Recipe is composed of ingredients. You might consider something like a subclass of Ingredient called RecipeIngredient that encapsulates an amount (that's just off the top of my head)
    Or you could do have a class RecipeElement initialised with Ingredient and amount
    Last edited by gozzy; July 3rd, 2021 at 11:39 AM.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Norm,

    Yes, although when you say "get the type and amount of each ingredient"
    I would say get the costPerUnit (since the Ingredient instance has a costPerUnit) and amount needed for the recipe (found in the values() of the hashmap with each ingredient)" (but I think you mean the same).
    And the rest is the same!

    Thank you for the help!

    --- Update ---

    Gozzy,

    How would that make the program better/easier/correct? (I'm not saying you are wrong, I just want to understand)
    Would I handle the "ingredients"? in this case?
    I have been trying to understand subclasses, inheritance etc but still pretty green as you can tell.

    Thanks for the input.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    When working with collections (and some other utility classes) it is better to use the interface instead of the class. For example use a Map to hold the <key, value> pairs. When initializing the Map set it to a new HashMap instance.
    Map<String, String> aMap = new HashMap<>();

    What goes into the Map you want to use? Why use a Map vs a List to hold the ingredients for a Recipe?
    A Map would be useful for storing the cost of an ingredient: Map<ingredient, cost>

    Note on extending a class. An example: a Cat is an animal and a Cat class would extend the Animal class.
    An Ingredient is not a Recipe. It should not extend the Recipe class.
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Quote Originally Posted by Norm View Post
    When working with collections (and some other utility classes) it is better to use the interface instead of the class. For example use a Map to hold the <key, value> pairs. When initializing the Map set it to a new HashMap instance.
    Map<String, String> aMap = new HashMap<>();

    What goes into the Map you want to use? Why use a Map vs a List to hold the ingredients for a Recipe?
    A Map would be useful for storing the cost of an ingredient: Map<ingredient, cost>
    .
    I will look at the interface vs class (since I don't understand that very well).

    So the hashmap is an element of the recipe instance which holds the ingredient (so I'm guessing I could access all the elements of the ingredient) and the amount of that ingredient needed for the recipe (its assumed the amount is entered in the same unit as the costPerUnit unit but that's a detail I can handle)
    I don't know why use hashmap than a List, i did some research and I found that hashmaps were something to use which could store value pairs. If there is an easier/better way of doing this I am all eyes. Ultimately I am doing this to learn and I want to learn the best way to do things.

    In my main you can see that I declare 3 ingredients for the recipe called stirFry I would like to calculate the cost for that recipe as a test.

    I get the ineritance concept now, thanks for that.

    Thank you!

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    How does the program need to access the ingredients?
    Does it need to directly access one particular ingredient by name? If so use a Map<name, Ingredient>
    If getting the ingredients one at a time in some order, then a List<Ingredient> should work.

    Where would the cost of an ingredient be stored? That would be a use of a Map<nameOfIngredient, cost>
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Quote Originally Posted by Ian_dude View Post
    Gozzy,

    How would that make the program better/easier/correct? (I'm not saying you are wrong, I just want to understand)
    Would I handle the "ingredients"? in this case?
    I have been trying to understand subclasses, inheritance etc but still pretty green as you can tell.

    Thanks for the input.
    Well you of course need to establish the correct design. A subclass B of A means that B is a specialisation of A. You can surely see that a recipe and an ingredient are separate entities? (even if one contains a collection of the other)

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Quote Originally Posted by Norm View Post
    How does the program need to access the ingredients?
    Does it need to directly access one particular ingredient by name? If so use a Map<name, Ingredient>
    If getting the ingredients one at a time in some order, then a List<Ingredient> should work.

    Where would the cost of an ingredient be stored? That would be a use of a Map<nameOfIngredient, cost>
    Norm,
    The program should be able to add ingredients.
    The program will need to "know" if the ingredient exists and if it does then it does need to access the ingredient by name (I think that's the easiest way to "grab" an ingredient" ) Right now the cost of 1 Kilogram or 1 Liter is stored in a field in the ingredient instance.

    Your answer seems to me like I need a bunch of lists or a map, how would I then go into the list of the ingredient/cost to get the total cost for the ingredients in the recipe, I am having trouble visualizing how to do that.

    Thank you,

    Ian

    --- Update ---

    Quote Originally Posted by gozzy View Post
    Well you of course need to establish the correct design. A subclass B of A means that B is a specialisation of A. You can surely see that a recipe and an ingredient are separate entities? (even if one contains a collection of the other)
    That makes total sense.
    So basically I have to copy the code of Ingredient into the Recipe class. But I still have my initial issue of how to iterate throgh the hasmap or ma or list to get the oneIngredient.costPerUnit and then from there perform the operation to multiply by the amount.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    I think there needs to be a better definition of ingredient and the amount of the ingredient being used in the recipe.
    For example: butter is an ingredient and 1/2 cup is the quantity being used. It would be useful to see if a recipe used butter so how to store the data for the butter being used. It seems that butter and 1/2 cup are two values that need to be separate but associated for the recipe. Does butter have other properties that need to be saved? Using a Map<name, valuesForName>
    where name is the String "butter" and valuesForName is an instance of a class that holds 1/2 cup and anything else needed.
    More work needs to be done on the design before writing any more code.
    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: Trying to iterate through hashmap of objects from a class I created

    I though I had the design figured out but I am new at this and most likely my design has some serious flaws.

    Right now as it stands the ingredient lets call it avocado (since I have it in the code above)
    has all these values right off the bat.
    String name = null; // this would be "avocado" for example
    Boolean organic = false; // no important for this issue but could be true
    String unitPurchased = null; // this is to determine the case that would be picked up to get the operation to turn whatever they bought into Kilograms in this case since its sold by weight, not volume. (they bough 200 grams etc..)
    String unitOfMeasure; // This one simply gets defined by the constructor if they enter anything to do with mass it'll go to Kilograms if its identified with volume it'll go to Litters
    float purchasePrice; //prince they paid at the store
    float purchasedAmount; // the actual ammount they purchased - from the line unitPurhased above this would be 200
    float pricePerUnit; // the constructor calls the calculatePricePerUnit method with some of the values entered (code in the original post) and this is supposed to calculate the $/Kilogram or $/Liter of product.

    Then the with Recipe Class one can create a recipe which will have:
    String name = null; // in the code of the original post this would be the stirFry
    String category= null; // not concerned with this now, it could be "main dish" or "dinner" or "entree" but its not important right now its just a tag to organize recipes in the future.
    double costOfRecipe; // this is the method is the one which is giving me trouble. I have the hashmap with the (Ingredient_instance, amount of the ingredient) since I made a constructor for a recipe that takes 3
    ingredients and they are passed into the hashmap called recipe inside of the instance of Recipe called stirFry.
    int numberOfIngredients = 0; // as of right now i just have this set to 3 manually since the only constructor I have reicieves 3 ingredients but once I add an "addOneIngredient method or a way to add an unspecified number of
    ingredients this will have to change.
    ArrayList <Ingredient> ingredients = new ArrayList<Ingredient>(); // currently I am not using this.
    ArrayList<Double> amounts = new ArrayList<Double>(); // currently I am not using this.
    HashMap<Ingredient, Double> recipe = new HashMap(); //I am using this hashmap to try to get the ingredients into the object stirFry and be able to use them to calculate the cost, he ingredient I asme I could do something like (avocado.costPerUnit) * (amount) since those two things are on each entry of the hashmap the avocado as an ingredient and the amount needed for the recipe (thats why i thought using a hashmap was good)

    I hope I'm explaining things properly and they make sense. I am doing the best I can while reading up and learning as much as possible.

    Thank you,

    Ian

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Is the above complete? Can you trying writing the code for it?
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Quote Originally Posted by Norm View Post
    Is the above complete? Can you trying writing the code for it?
    Norm,

    In my original post above I copied the code for the Ingredient Class and for the Recipe Class and for the Main which uses the classes for now. I tried to write a for each loop in several ways but i only could get the for each to add the amounts up which logically makes no sense if they are not individually multiplied by their unit cost first.

    If you look in the Recipe Class' code above I have a comment like this:
    //*************THIS IS WHERE I AM STUCK*********************
    that is the for loop that started all this.

    I think that is what you are asking, but I am not sure.

    Ian

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    I tried to write a for each loop
    What is that loop supposed to do? Is it what I talked about in post#4?

    Some comments on the code in post#1
    Why is a reference to an instance of a Recipe passed to any method in the Recipe class? The contents of the class are automatically available to all the methods in the class. The same with the Ingredients class.
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    From long experience I can tell you one guiding principle: never write code until you have the design completely worked out. I gave it some thought and RecipeElement is probably a good way to go. If you were writing a real world app (and actually it could be pretty useful for pricing up recipes) you might like to think about a Unit class too. All ingredients have a default unit, and they can vary quite a lot. An enum might be a candidate here

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Quote Originally Posted by gozzy View Post
    From long experience I can tell you one guiding principle: never write code until you have the design completely worked out. I gave it some thought and RecipeElement is probably a good way to go. If you were writing a real world app (and actually it could be pretty useful for pricing up recipes) you might like to think about a Unit class too. All ingredients have a default unit, and they can vary quite a lot. An enum might be a candidate here
    Gozzy,

    I am not very experienced with Java as you can tell but I though I had it well specked out. But obviously not.
    I acually have 2 enums in my Ingredient Class
    public enum UnitPurchased {
    GRAMS, KILOGRAMS, MILLILITERS, LITERS, CUPS, TABLESPOONS, TEASPOONS
    }

    public enum UnitOfMeasure {
    LITER, KILOGRAM
    }

    I think that they will be useful for when I actually have people (or me) entering info through an interface and the enums will be the only options they can choose. As of now I am not really using them.
    The UnitPurchased has may options since I think that those are all the options that one may have and the UnitOfMeasure is basically how I am planning to manage the costing:
    if its a liquid or measured by volume it'll be liters and if its measured in weight the unit will be Kilograms.

    As a part of the constructor of the Ingredient (code above in my first post) I have this switch statement that assigns a string either KILOGRAM or LITER which is exactly the enums but I most likely am not using the enum functionality correctly here either.

    Let me know your thoughts.

    Thank you,

    Ian

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Quote Originally Posted by Norm View Post
    What is that loop supposed to do? Is it what I talked about in post#4?

    Some comments on the code in post#1
    Why is a reference to an instance of a Recipe passed to any method in the Recipe class? The contents of the class are automatically available to all the methods in the class. The same with the Ingredients class.
    Norm,

    Yes it is what you are talking about in post #4.
    You may as well ignore the code I have for the 2 attempts at creating the method called "calculateRecipeCost"
    since they don't work and I have tried 10 different things on each so I may as well start that method from scratch.

    If you see in my second attempt at the method (the one which is not commented out) i have a "recipe.entrySet()"
    this is because I called my hashmap "recipe" that is part of every Recipe instance of a Recipe, in this case in my min called stirFry
    I am trying to get the inredient.pricePerUnit basically so that I can multiply against the amount in the value() of the hashmap. ( I thought this would be fairly easy but seems to be a pain)

    In my mind if I could do something like:

    hashmap(counter) ---- and this gave me the ingredient "avocado" (for the stirFry recipe found in Main)
    then it would be like saying
    avocado.pricePerUnit if I did (hashmap(counter).getKey).pricePerUnit) or something.
    then I could multiply this by "amount" so to get amount I could do hashmap(counter).getValue()
    and that would be the amount of avocado needed.

    so in my head if this would work (which I dont know how to write)
    recipeCost = (hashmap(counter).getKey).pricePerUnit) * (hashmap(counter).getValue())

    the for each loop iterates and keeps adding to the recipeCost variable.

    In the end, I am not married to hashmaps, thats what I try to use, but if you can show me how to do this with another object type I would gladly change it, I write my answers in with that word since its what I have in the code.

    Thank you again!

    Ian

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Ok, so if the recipes are stored in a Map<name, ingredients> then
    Use the entrySet method to iterate through all the entries in the Map giving access to each of the ingredient instances in the Map. If the ingredients are in a List, it is simpler to get the instance.
    If the cost of the ingredient is stored in the ingredient class instance, then the total can be computed by summing the value from each instance. If the costs are dynamic depending on where they are purchased, then the cost of the ingredient may need to be obtained from another place like a Map<nameOfIngred, costPerUnit>.
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    I am so happy Norm:

    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;

    This totally works!

    From my Main, which I declare the 3 ingredients, and then the stirFry recipe i get this:

    From this line:
    System.out.println("Stir Fry costs: " + stirFry.costOfRecipe + " dollars, for one family dinner");

    I get:
    Stir Fry costs: 24.0 dollars, for one family dinner

    Which is accurate (i have done the math on paper)

    Thank you for the help!

    Now one more question:
    Gozzy said that Ingredient should be a sub class of recipe or that there should be a RecipeElement and ingredient should be in there.

    Do you agree? and how would that change the way I interact with my code?

    Thank you so much!

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Gozzy said that Ingredient should be a sub class of recipe
    Go back and read that again. I didn't think he said that.

    The fields in the classes should be private. Their values should be retrieved with a get method, not directly accessed.
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Quote Originally Posted by Norm View Post
    Go back and read that again. I didn't think he said that.

    The fields in the classes should be private. Their values should be retrieved with a get method, not directly accessed.
    Norm,

    Post 5 "I think you need to establish your abstractions and classes properly. An Ingredient certainly doesn't extend Recipe. A Recipe is composed of ingredients. You might consider something like a subclass of Ingredient called RecipeIngredient that encapsulates an amount (that's just off the top of my head)
    Or you could do have a class RecipeElement initialised with Ingredient and amount"

    I have the code working now but I want to learn so that is why I ask this question.
    Would moving the Ingredient Class off from a separate class and making it a sub Class of Recipe make any difference?

    Thank you,

    Ian

  24. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Would moving the Ingredient Class off from a separate class and making it a sub Class of Recipe
    An Ingredient is not a Recipe. A Recipe has a list of Ingredients.
    A SpicyRecipe could be a sub class of Recipe.

    have the code working
    Can you post it so we can see if there are any other problems with it?
    If you don't understand my answer, don't ignore it, ask a question.

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

    Default Re: Trying to iterate through hashmap of objects from a class I created

    Quote Originally Posted by Norm View Post
    An Ingredient is not a Recipe. A Recipe has a list of Ingredients.
    A SpicyRecipe could be a sub class of Recipe.


    Can you post it so we can see if there are any other problems with it?
    Thanks for the class/subclass answer.
    The loop code is in a post above (post 21)

    But here is the code and I added a add1Ingredient() method to the recipe which updates the cost as well.
    I also added 9 constructors to take up to 10 ingredients but that i didnt copy since I didnt want to bulk the post too much.

    Thank you
    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 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);
        }
    }
    Last edited by Norm; July 4th, 2021 at 04:07 PM. Reason: ADDED CODE TAGS

Page 1 of 2 12 LastLast

Similar Threads

  1. How to use session handler created in one class in another class?
    By Asif Masood in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 12th, 2014, 03:50 PM
  2. Need some help testing created class.
    By fpritt24 in forum Object Oriented Programming
    Replies: 4
    Last Post: November 15th, 2013, 04:05 PM
  3. Help with using pre-created objects and Vectors **First Post :)**
    By jimmyo88 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 18th, 2011, 08:08 AM
  4. Replies: 3
    Last Post: November 25th, 2011, 02:02 PM
  5. Autoboxing and unboxing for user created objects
    By tcstcs in forum Java Theory & Questions
    Replies: 3
    Last Post: March 22nd, 2011, 07:54 AM

Tags for this Thread