gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:21:22 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com