java - 如何将方法参数中的值存储到数组中?
问题描述
我正在编写一个程序来存储某些食谱信息。成一个数组。使用方法 RecipeEntry() 及其参数,该程序旨在将最多 3 个食谱存储到名为:totalEntry[] 的数组中。
下面是我编写这个程序的尝试,但是,我遇到了错误......无法弄清楚我错过了什么。
import java.util.*;
public class RecipeArray
{
private String author;
private Recipe recpH_1;
private Recipe recpC_2;
private static RecipeEntry[] totalEntry = new RecipeEntry[3];
private static int entryCount;
public RecipeArray(String author, Recipe hot, Recipe cold) // constructor
{
entryCount = 0;
this.author = author;
recpH_1 = hot;
recpC_2 = cold;
totalEntry[entryCount] = new RecipeArray(author, recpH_1, recpC_2);
}
public static void main(String[] args)
{
RecipeEntry("Mary Bush", SpaghettiHOT, SpaghettiCOLD);
// RecipeEntry method, when called should pass its parameter values into
// totalEntry [] array. entryCount variable should keep count of every entry.
System.out.println("ALL ENTRY = " + entryCount + Arrays.toString(totalEntry));
}
}
public class Recipe //create class data of type recipe
{
private String name;
private int id, rating;
public Recipe(String name)
{
this.name = name;
id = 0;
rating = 0;
}
}
预期的输出应打印条目列表 - 示例:
输出:
索引 0 - [Mary Bush, SpaghettiHOT{id=0, rating=0}, SpaghettiCOLD{id=0, rating=0}]
解决方案
问题是您没有从您的方法中捕获返回的数组:RecipeEntry("Mary Bush", SpaghettiHOT, SpaghettiCOLD);
实际上,您编写的 RecipeArray 将返回一个数组;这意味着该方法将传递 Array 给它的调用者。用以下行更改上述行将解决问题:RecipeEntry[] totalEntry = RecipeEntry("Mary Bush", SpaghettiHOT, SpaghettiCOLD);
访问https://www.tutorialspoint.com/importance-of-return-type-in-java以更好地理解 Java 方法:
推荐阅读
- javascript - 无法使用 javascript 从 AWS S3 存储桶获取文件计数或列表
- android - 我可以在 Google Play 控制台的哪个位置查看我的应用的 Android 版本分布?
- sequelize.js - Sequelize - 包含模块,而 where 子句是可选的
- r - 如何仅使用非 NA 值为每一行数据帧制作 bin?
- android - 实现 .aar 库和上下文问题
- c# - 如何有条件地在linq中添加where条件
- python - Python selenium - 找不到元素
- excel - Excel:动态相关列表
- weka - WEKA Ham 或 Spam J48 显示为灰色
- python - 我的输出如何显示真实的列标题而不是自动增量数字