I have two classes, one running the Main method has the following for
loop:
for (int b = startRecipe; b <= endRecipe; b++)
{
Rec = fileScan.nextLine() + "\n";
}
System.out.println(theRecipe.addRecipeStep(Rec));
In my other class, I have the following loop:
public String[] addRecipeStep(String Rec ){
for (int a = 0; a < maxNumOfSteps; a++)
recipeSteps[a] = Rec;
return recipeSteps;
}
int maxNumOfSteps
can be accessed across the two classes. My first question is, I would like to loop over the first loop, and for every Rec
value, I would like to add it to my recipeSteps
array in the second loop. For right now, the second loop only adds the last value that Rec
takes, understandably (and the array contains the same thing in all the indices). If I do Rec +=
and add every Rec
values to 1 index of the array (everything shows up), then it is against the program requirements. Ideally, I should have as many indices in the 2nd array as there are numbers of Rec
values.
Problem # 2 is, when I call the addRecipeStep(param)
from the main
class, it prints out "trash." I have attempted to use toString()
but there has been no successes yet. All advices are welcomed.
Thank you!
Since addRecpieStep is in one class, and your first loop is in another, you will need a refrence to the class containing addRecepieStep. Then simply call that method each time in your loop with the value of rec.
In addRecpieStep you need to change a bit. Earlier you overwrote all elements with the value of rec, but you simply want to add it to the end of the list. So addRecpieStep you want to loop until you find a null value, and add the element to that position:
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;
}
To explain, when you do this (as you did in your example):
public String[] addRecipeStep(String Rec ){
for (int a = 0; a < maxNumOfSteps; a++)
recipeSteps[a] = Rec;
return recipeSteps;
}
you overwrite the whole array with the value of rec since it will loop thru the array, and add rec to each position which is not what you want
As for the printing of the array I will leave it up to you to complete. But, you will need to loop thru the array, and call println on each element. So, write a method that takes an array as parameter, loops thru the array and calls println every loop. Good luck
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.