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 trialcaleb morton
Courses Plus Student 1,007 PointsI am having issues with the setup of this for loop.
I don't really understand what the for(char letter: mAnswer.toCharArray()){} is doing exactly. I know it is changing the string mAnswer to an array of chars but what is the char letter: actually doing?
public class ScrabblePlayer {
private String mHand;
public ScrabblePlayer() {
mHand = "";
}
public String getHand() {
return mHand;
}
public void addTile(char tile) {
// Adds the tile to the hand of the player
mHand += tile;
}
public boolean hasTile(char tile) {
return mHand.indexOf(tile) > -1;
}
public int getTileCount(char tile){
int tileCount = 0;
for(char letter: mHand.toCharArray()){
if(letter
}
}
}
2 Answers
Manish Giri
16,266 PointsThis is a "for each" loop. mHand.toCharArray() returns an array of characters. In the construct: for(char letter: mHand.toCharArray()), every letter in the character array is being assigned one-at-a-time to letter, so that you can perform some manipulation on the letter. In this case, you'll (probably) check if the current character , ie the value of 'letter' matches one of the letters in the to-guess word, and will increment the number of attempts if it doesn't match(as far as I remember).
So essentially, in a for-each loop, you iterate through the collection by stepping over every element in the collection one at a time.
caleb morton
Courses Plus Student 1,007 PointsOk I understand your explanation using arrays because they are essentially lists. What other reason would you use a "for each" loop besides looping through array values? To me that type of loop seems to have a specific use while the "while" and "do/while" loops are more general.
Is that correct? Sorry pretty new to coding anything besides super simple programs.