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 trial

Java

Colby Wise
Colby Wise
3,165 Points

Trouble with Code Challenge getTileCount

Can you please help me correctly implement the getTileCount counter. I believe i've constructed the 'for each' loop to loop from the tile to the hand but the method is not being recognized... the error I got most recently is quite unhelpful from a debugging standpoint: "Bummer! Did you forget to create the method getTileCount that accepts a char?"

public int getTileCount(){

int counter = 0; for (char tile : mHand.toCharArray()){

 if(mHand.indexOf(tile) > -1){
    counter += 1;       
  } 
 //Integer.toString(counter);
 // System.out.printf("The number of tiles is %s\n", counter);
 // return counter;

} return counter; }

2 Answers

Colby,

for each loop is basically dividing (String in our case) to an array of chars. This means we have to instantiate new char variable so that we can use it to compare output (char letter) to input (char tile).

In other words - without creating new char variable (letter) we wouldn't be able to compare whatever for each loop returns to char (tile) we are looking for in a given hand. Think of it as of breaking down a mechanism into smaller pieces and then comparing each one of those to separate spare piece we have - in this way we can easily count how many times separate piece is actually being used in the original mechanism.

Hello Colby,

you were almost there! Just couple things to be fixed. Overall your code should look like this:

  public int getTileCount(char tile) {
    int count = 0;
    for (char letter : mHand.toCharArray()) {
      if (letter == tile)
        count++;
    }
    return count;
  }
Colby Wise
Colby Wise
3,165 Points

Many thanks. Question: Why do we create a new variable [char letter] in the for each loop? Im used to implementing loops in other languages from 1 to length (x)... in this case is [char letter] = 1?