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 Creating the MVP Counting Scrabble Tiles

Victoria Holland
Victoria Holland
6,159 Points

"Bad initializer for for-loop" error

I'm struggling with the Counting Scrabble Tiles exercise (getCountOfLetter method). Here is my code. I get a compiler error saying "Bad initializer for for-loop".

public class ScrabblePlayer {
  // A String representing all of the tiles that this player has
  private String tiles;

  public ScrabblePlayer() {
    tiles = "";
  }

  public String getTiles() {
    return tiles;
  }

  public void addTile(char tile) {
    tiles += tile;
  }

  public boolean hasTile(char tile) {
    return tiles.indexOf(tile) != -1;
  }

  public int getCountOfLetter(char letter) {
    int count = 0;
    int i = 0;
    for (letter : tiles) {

      if (letter == tiles.charAt(i)) {
        count ++;
      }
      i++;
    }
    return count; 
  }
}

2 Answers

Shlomi Bittan
Shlomi Bittan
6,718 Points

Well...i see to mistakes.

  1. In the loop you need to perform the equality check against the letter variable passed to the method. The code now check equality against a char at a given index of the tile string.
  2. The for each loop requires that the object on which to loop implement the Iterable interface. So you need to provide that object. The string object has a method that returns an array of char objects.

someString.toCharArray()

So the for loop actualy should look like this:

for (char currentChar : tiles.toCharArray()) {

      if (currentChar == letter) {
        count ++;
      }
      i++;
    }

By the way, you don't need the i variable.

Shlomi Bittan
Shlomi Bittan
6,718 Points

Hi Victoria, Your for loop does NOT declare a type for the 'letter' variable. Also, you can't use the same variable name as the one passes to the method. I suggest this fix:

 public int getCountOfLetter(char letter) {
    int count = 0;
    int i = 0;
    for (char currentChar : tiles) {

      if (currentChar == tiles.charAt(i)) {
        count ++;
      }
      i++;
    }
    return count; 
  }
Victoria Holland
Victoria Holland
6,159 Points

Thanks, but unfortunately I still can't get past this section. I tried your code but now it gives a compiler error saying "for-each not applicable to expression type".