Search code examples
javaarraysobjectsystem.out

Printing single element of object in array. Java


Trying to store objects in an array and to later print them out. Keep getting the actual location in memory instead. Can't remember for the life of me how to print the contents and not the locations.

case VIEW_RECIPE:
            System.out.println("Please enter the recipe ID:");
            searchIndex = input.nextInt();
            System.out.println(recipeArray[searchIndex-1]);
            break;
case CREATE_RECIPE:
            Recipe recipe = new Recipe();
            recipeArray[recipe.getRecipeId() -1] = recipe; //-1 to store in element 0;
            break;

So assuming there is a recipe at index 0 of the recipeArray[], how do I print it. this code only gives me the memory location, and looping through is impractical.

tried the code

System.out.println(Arrays.toString(recipeArray[searchIndex-1]));

but it says the toString should be deepToString, or the array should be long.

EDIT: After being asked for the recipe class here it is

package potluck;
import java.util.*;


public class Recipe {

private int recipeId = 0;
private Scanner input = new Scanner(System.in);
private String attribution; 
private String dateAdded;
private String category;
private String listOfIngredients; 
private String tags;
private String steps;  
private String comments; 


public Recipe(){ //constructor
    recipeId += 1;
    setAttribution(); 
    setDateAdded();
    setCategory();
    setListOfIngredients(); 
    setTags();
    setSteps();
    System.out.println("Thank you for the recipe, it's Id is "+recipeId);
    System.out.println("Use this to find it later.");
    System.out.println();
}

everything else is getters and setters


Solution

  • You should override toString() methond in Recipe class. For example:

    class Recipe {
        private int id;
        private String name;
    
        public String toString() {
            return "Recipe#" + id + ": " + name;
        }
    }