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 trialKshatriiya .
1,464 PointsHi please explain for (String word: treet.getWord()) or similar for (Char letter: example.toCharArray()) etc
Hello,
I understand what they do roughly but having a difficult time digesting why it is formatted that way. Does for (Char letter: example.toCharArray()) changed the String stored in example to character array and then store that in Char letter?
Say if String example = "hello"; does Char letter than become ['h', 'e', 'l', 'l', 'o'] ?
So when you pair it with for command that does mean for every character in Char letter?
if that is the case why can't we do something like
Char[] letter = example.toCharArray();
for (letter) {
}
Thanks in advance.
1 Answer
jcorum
71,830 PointsYes. It creates an array of chars, as you say: ['h', 'e', 'l', 'l', 'o'] .
The problem is that there were syntax errors in your code.
//create String
String example = "hello";
//convert to char array
char[] letter = example.toCharArray(); //char must be lower case
//loop through char array
for (char l : letter) { //loop must have a typed variable
System.out.print(l + " ");
}
//output
//h e l l o