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

David Barnes
David Barnes
919 Points

While using the toCharArray() method

What does this compiler error mean: ./ScrabblePlayer.java:22:error: char cannot be dereferenced for(int count:tile.toCharArray()){

Code: public int getTileCount(char tile) { for(int count:tile.toCharArray()){ ; } }

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) {
    for(int count:tile.toCharArray()){
      ;
    }
  }
}

1 Answer

Benjamin Larson
Benjamin Larson
34,055 Points

Hi David,

I think the error you are getting is because the for-loop declaration is expecting a char variable and not an int.

You'll need to declare the counter outside of the for loop and then return it at the end. Inside the loop, you'll want to check if the current char in the mHand member variable is equal to the tile that is being passed in as an argument. So you'll need a conditional inside of the loop. Here's how I did it, but give it a try first before just copying and pasting :D

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