Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial2 Answers
anil rahman
7,786 PointsThis for loop syntax is really simple:
for (char letter : toCharArray()) {
//do stuff for each item we loop through
}
It is basically saying ok so lets make a char variable and its called letter and for each item in my toCharArray() im going t set that item value to letter.
So its like for each letter in my array i am going to for example print out the value.
So if the array held the chars (h,e,l,l,o)
It would go through like this:
set this char letter = item number 1 which is "h" then do the code in the braces then again set char letter = item number 2 which is "e" the do the code in the braces and so on until it gets to the end of the array and you have now looped through and printed each item out.
anil rahman
7,786 PointsI dont think ever seen a for loop without the data type specified. Its always been:
(char letter : listName)
or (String s : myArray)
Alex Popian
977 PointsAlex Popian
977 PointsWhy do we declare char letter inside the for method? Shouldn't it be declared before and then just say for( letter : toCharArray())? Sorry if this sounds dumb I'm not that good with java...