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 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,694 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,733 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.