java - 打印数组中对象的单个元素。 java

标签 java arrays object system.out

尝试将对象存储在数组中并稍后将其打印出来。继续获取内存中的实际位置。我一辈子都不记得如何打印内容而不是位置。

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;

假设在recipeArray[]的索引0处有一个菜谱,我该如何打印它。这段代码只给我内存位置,循环是不切实际的。

尝试了代码

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

但它说 toString 应该是 deepToString,或者数组应该很长。

编辑:在被要求提供配方类后,它是

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();
}

其他都是 getter 和 setter

最佳答案

您应该重写 Recipe 类中的 toString() 方法。例如:

class Recipe {
    private int id;
    private String name;

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

关于java - 打印数组中对象的单个元素。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36186213/

相关文章:

java - 如何在 jung 库中使用 DirectedSparseVertex() ?

javascript - jQuery 指定在数组中搜索值的条件

java - 计算字符串中小写字母的数量并以直方图的形式打印出它们的出现次数?

objective-c - Objective-C 和 Swift 之间的 UserDefaults

java - 无法读取 iText 生成的 pdf

java - 在 weblogic 中面临 perm gen space 错误

java - Swagger2 - 找不到用于 GET 的处理程序

python - Numpy: "bump"数组的高效索引数组

java - 从文本文件中逐行读取车辆并将这些车辆传递到 Java 的构造函数中

c++ - C++中如何存储静态数据和方法细节