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 trialLuiz Fernando Bojikian da Costa Vital
7,193 PointsI can't solve "Code Challenge: For Each Loop" of Java Objects. Can anyone help me please?
I've tried many times but I just can't figure it out :(
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 letter){
int count = 0;
for (char c : mHand.toCharArray()){
if (hasTile(letter)){
count ++;
}
}
return count;
}
}
2 Answers
Grigorij Schleifer
10,365 PointsHi Fernando,
if you use your code your count will be always equals to the number of characters in the mHand.
Allow me to explain why:
I added one more curly bracket and the return statement I have missed in your code.
public int getTileCount(char letter){
int count = 0;
for (char c : mHand.toCharArray()){
// the for loop checks every character of the mHand array so if mHand has 8 characters, there will be 8 loops
// so for every character the compiler enters the if loop
// If you have a "letter" that is inside mHand the if-condition will be true and count will increase by 1
// because the hasTile() method proofs if there is a letter inside mHand
// but this letter stays in mHand and next time the "hasTile(letter) will be true again and counter will be increase again
// and so on .....
if (hasTile(letter)){
count ++;
}
}
return count;
}
So you need to modificate your if statement to:
public int getTileCount(char letter){
int count = 0;
for (char c : mHand.toCharArray()){
if (letter == c){
// here you are looking for a specific character inside mHand
// and the compiler "climbs" from first char to the next char
// and the condition is only true if letter is inside mHand not always
count ++;
}
}
return count; // return value added
} // bracket added
Hope that helps
Grigorij
Luiz Fernando Bojikian da Costa Vital
7,193 PointsHi Grigorij!
Thanks a lot! I can see what I was doing wrong now.
Thanks again!
Cheers, Luiz