繁体   English   中英

Java-在一个类中循环并将元素添加到另一个中的数组

[英]Java - looping in 1 class & adding element to array in another

我有两个类,一个运行Main方法的类具有以下for循环:

for (int b = startRecipe; b <= endRecipe; b++)
        {
            Rec = fileScan.nextLine() + "\n";
        }
        System.out.println(theRecipe.addRecipeStep(Rec));

在另一堂课中,我有以下循环:

 public String[] addRecipeStep(String Rec ){

        for (int a = 0; a < maxNumOfSteps; a++)
            recipeSteps[a] = Rec;

        return recipeSteps;

    }  

可以在两个类之间访问int maxNumOfSteps 我的第一个问题是,我想循环遍历第一个循环,对于每个Rec值,我想将其添加到第二个循环中的recipeSteps数组中。 现在,第二个循环仅添加Rec采用的最后一个值,这是可以理解的(并且数组在所有索引中都包含相同的内容)。 如果我执行Rec +=并将每个Rec值添加到数组的1个索引中(一切都显示出来),那么这违反了程序要求。 理想情况下,第二个数组中的索引应该与Rec值的数目一样多。

问题2是,当我从main类调用addRecipeStep(param) ,它会打印出“垃圾箱”。 我尝试使用toString()但尚未成功。 欢迎任何建议。
谢谢!

由于addRecpieStep在一个类中,而您的第一个循环在另一个类中,因此您需要引用包含addRecepieStep的类。 然后,只需在循环中每次使用rec的值调用该方法即可。

在addRecpieStep中,您需要进行一些更改。 之前,您用rec的值覆盖了所有元素,但您只想将其添加到列表的末尾。 因此,您要循环执行addRecpieStep,直到找到空值,然后将元素添加到该位置:

    for (int b = startRecipe; b <= endRecipe; b++)
    {
        rec = fileScan.nextLine() + "\n";
        refrenceToYourClassContainingAddRecipeStep.addRecipeStep(rec); //add this line
    }


 public String[] addRecipeStep(String rec ){

          for (int a = 0; a < maxNumOfSteps; a++){
              if(receipeStep[a]==null  // loop until you reached a empty spot in your string arrray
                 recipeSteps[a] = rec;  // add rec to your empty spot
                 break;            
          }

        return recipeSteps;

    }  

为了解释,在执行此操作时(如您在示例中所做的那样):

public String[] addRecipeStep(String Rec ){

        for (int a = 0; a < maxNumOfSteps; a++)
            recipeSteps[a] = Rec;

        return recipeSteps;
    }

您可以使用rec的值覆盖整个数组,因为它将遍历该数组,然后将rec添加到不是您想要的每个位置

至于阵列的打印,我将留给您完成。 但是,您将需要遍历数组,并在每个元素上调用println。 因此,编写一个将数组作为参数,循环遍历数组并在每个循环中调用println的方法。 祝好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM