Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects (Retired) Creating the MVP For Each Loop

Perplexed by getTileCount

I keep getting the error

./ScrabblePlayer.java:11: error: cannot find symbol if (letter == tile){ ^ symbol: variable letter location: class ScrabblePlayer 1 error

I can't seem to figure out why.

Thanks AJ

ScrabblePlayer.java
public class ScrabblePlayer {
  private String mHand;

  public ScrabblePlayer() {
    mHand = "";
  }

  public int getTileCount(char tile){
    int count = 0;
    for(char letter : mHand.toCharArray());{
      if (letter == tile){
      count ++;
      }
    }
   return count;
  }

  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;
  }
}

3 Answers

Simon Coates
Simon Coates
28,692 Points

you have an errant semicolon. try:

  public int getTileCount(char tile){
    int count = 0;
    for(char letter : mHand.toCharArray()){
      if (letter == tile){
      count ++;
      }
    }
   return count;
  }

I demoed:

class Main {
  public static void main(String[] args) {
    //String noun ="barney the dinosaur";
    String mHand="this is such a fun string!";

    for(char letter : mHand.toCharArray());    {
    System.out.println("how often do i print.");
    }
  }
}

I think the ; ends the for, making the {} an unrelated scope in which the letter variable doesn't exist. The above demonstrates this. It only prints the once - reflecting its detachment from the for loop. It's horrible that this is valid code, but i'd assume the ; creates a empty statement attached to the loop.

Kourosh Raeen
Kourosh Raeen
23,732 Points

Hi AJ - You have a semicolon in your for loop that shouldn't be there. The line:

for(char letter : mHand.toCharArray());{

should be

for(char letter : mHand.toCharArray()) {

Thank you guys. I very much appreciate the explanation Simon.