簡體   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