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

Mads Andersen
Mads Andersen
8,401 Points

bad initializer for for-loo

Why doesnt this code work, it keeps saying: 'bad initializer for for-loop'. Can you explain the reason to me?

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 int getTileCount(char tile){

    int counter = 0;

    for(tile : mHand.toCharArray())
    {
      if(mHand.indexOf(tile) > 0){
        counter++;
                                 }
    }
    return counter;
                                    }
                            }

1 Answer

Hi Mads,

The problem is that you used tile from the getTileCount parameter list as the name for the first variable in the for each loop. Instead, consider declaring a new variable inside of the loop:

public int getTileCount( char tile ) {
      int count = 0;

      for ( char letter : mHand.toCharArray() ) {
          if ( letter == tile ) {
              count++; 
          }
      }
    return count;
  }
Jared Swain
Jared Swain
3,153 Points

thank you for the answer I was having the same problem. Can any one explain how the for-loop knows what char it is searching when the values are different in getTileCount( ) and the for( ). Also why his original code was not excepted. I'm very new to java but in my experience his original should have worked.