首页 > 解决方案 > 如何将方法参数中的值存储到数组中?

问题描述

我正在编写一个程序来存储某些食谱信息。成一个数组。使用方法 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}]

标签: javaarraysvariablesmethods

解决方案


问题是您没有从您的方法中捕获返回的数组: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 方法:


推荐阅读