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

Diego Marrs
Diego Marrs
8,243 Points

What am I doing wrong?

I get this error when I run my code, I can't understand what it means:

./ScrabblePlayer.java:23: error: bad initializer for for-loop
    for (tile : count) {
         ^

My code:

ScrabblePlayer.java
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 String getTileCount() {
    int count = 0;
    for (tile : count) {
      count += 1;
    }
    return count;
  }
}

You need to add a type before your "tile".

for(char tile : mHand){
  // add code here
}

It will loop through your mHand, taking each character and storing it in your char tile variable. Make sure that you add code that will reference the "tile" variable in your for loop code block.

Diego Marrs
Diego Marrs
8,243 Points

Ah, okay. What code could I add to reference 'tile' in my 'for' loop? I tried many things, and it didn't work.

5 Answers

The assignment probably has you doing it this way:

public int getTileCount(char tile){

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

Yes that's right my bad.

I changed it, thank you.

public int getTileCount(char tile) {

   int count = 0;
   for(int i = 0; i < mHand.length(); i++){

      if(mHand.charAt(i) == tile)
     count++;
     }
   return count;
}

I haven't ran it but that should work.

Paste your entire code, and I'll look at it.

Diego Marrs
Diego Marrs
8,243 Points

Nevermind, fixed it. Thanks for the help!

No problem :)