Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding Element of an Object in an Array in an Array to a String Array
    text
    copied!<p>I have a method that is suppose to traverse 2 arrays of Ojbects, the first being Menu of size 50, which contains Recipes, which hold up to 10 elements called ingredients, which holds up to 3 elements each, but I am only looking for their names! I want to take the matching names of those Ingredient elements in the Recipes and add them to my String array and then return it, here is my code...</p> <pre><code>public class Recipe implements Cloneable { String Name; final int INGREDIENT_ARRAY_MAX = 10; Ingredient Ingredients[] = new Ingredient[INGREDIENT_ARRAY_MAX]; public class RecipeBook { final static int MENU_ARRAY_MAX = 50; static Recipe Menu[] = new Recipe[MENU_ARRAY_MAX]; public static String[] getRecipesByIngredient(String ingredientName) { String[] targetRecipes = new String[MENU_ARRAY_MAX]; int counter = 0; for (int j = 0; j &lt; Menu.length; j++) { if (Menu[j] == null) { break; } else { for (int k = 0; k &lt; Menu[j].Ingredients.length; k++) { System.out.println(Menu[j].Ingredients[k]); if (Menu[j].Ingredients[k].getName().equals(ingredientName)) { targetRecipes[counter] = Menu[j].getName(); counter++; } } } } return targetRecipes; } } } </code></pre> <p>Now I know it doesn't work and why, but the solution I am not sure about. At the moment I only have 3 Recipes and 3 Ingredients in each recipe! The stuff up top is just for reference, those are the object arrays of RecipeBook (Menu) and Recipes (Ingredients).</p> <p>Now when ran this code gets me into a NullPointerException because tries testing nulls against Strings, but how could I make it check through the Recipe, if it doesn't find anything, it moves on to the next Recipe in Menu, if it does, it simply adds it but continues to check til finish. I tried adding "if" statements checking for nulls and not nulls but it becomes convoluted and it still doesn't get my program to return to checking the rest of the arrays. I know the first "if" can stay because, well if the spot i check in Menu is null, the rest of it must be null so there's no point in going farther. But how do I check the Ingredients array, find something, add it, and go back to sifting through the Menu for recipes with that ingredient? Is it possible to add an if inside the inner loop to check for null and if it is, just go back to the outer loop?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload