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 trialShane May
5,114 PointsFor Each loop help (Scrabble game). Not familiar with this for each loop, and I am not sure what to do
For Each loop help (Scrabble game). Not familiar with this for each loop, and I am not sure what to do
public class ScrabblePlayer {
private String mHand;
public int getTileCount(char ltr){
int count = 0;
for(char letter: mHand.toCharArray()){
if(mHand.indexOf(letter) >= 0){
count++;
}
}
return count;
}
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;
}
}
1 Answer
jcorum
71,830 PointsNeed a bit more info. Your code compiles fine. So what is it you feel you need to do? I'll try to guess, but if I guess wrong let me know.
If it's just understanding the for each loop, there are plenty of resources on the web. But in short, for-each loops are an easy way to traverse an array or collection. Here you are using it to look at each of the chars in the mHand String.
If it helps to get your head around what it's doing, your for-each loop could be converted to the other kind of for loop: <br> for (int i = 0; i < mHand.length(); i++) { if(mHand.charAt(i) == ltr){ count++; } } <br>
Perhaps you are wondering how to test your work. If so, you need to create a test program. Here's a brief one, to get you going.
public class ScrabbleTest {
public static void main(String[] args) {
ScrabblePlayer p = new ScrabblePlayer();
p.addTile('T');
p.addTile('X');
System.out.println(p.getTileCount('T'));
}
}