Tim
Tim

Reputation: 23

Learning Java and Stuck on how to create an array from the elements within a for each loop

I am learning Java and I have the following code:

public Slide[] thisIsASlide (String [] slider) { 
    for (String amount : slider) { 
        Slide st = thisNewMethod(slider, 20,20);
    } 
   return ; 
} 

The elements will be stored into amount at each iteration. I want to put this amount into a new array and return it. Please can someone help?

Thanks

Edit: I think I said this wrong I need to know how to put the variable of Slide (st) into a new array and return it. Please can someone help with this?

Upvotes: 0

Views: 78

Answers (2)

berlinguyinca
berlinguyinca

Reputation: 822

It looks like you only define a local variable and never actually assign the value.

Slide st = thisNewMethod(slider, 20,20);

st in this case is your local variable. Since your forEach loop, does not provide an index where it currently is, it will not assign this to your array of sliders.

I hope this makes sense.

This post, explains the differences rather well:

Foreach vs common for loop

Upvotes: 0

khelwood
khelwood

Reputation: 59095

public Slide[] thisIsASlide (String[] slider) { 
    // create an slide array the same length as your incoming array
    Slide[] slides = new Slide[slider.length];
    for (int i = 0; i < slider.length; ++i) {
        // Add a slide at index i for each string at index i in the incoming array
        slides[i] = thisNewMethod(slider[i], 20, 20);
    }
    // return the created array
    return slides;
} 

Upvotes: 2

Related Questions