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

João Sulzbach
João Sulzbach
2,611 Points

Don't know why my method getTileCount() in the ScrabblePlayer Java challenge isn't working.

Hello guys, according to the challenge, my code isn't working the way it should. Can someone please pinpoint what's wrong? Thanks!

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 count = 0;
  public int getTileCount(char tile){
    for (char letter : mHand.toCharArray()){
      if ( letter == tile ){
        count += 1;
      }
    }
    return count;
  }
}

1 Answer

Christopher Augg
Christopher Augg
21,223 Points

João,

Actually, your code should work as it is. However, you would not want count to be a public member variable as it could be accessed from outside the class violating encapsulation. In order to make it pass the test, you can place the count declaration into the method call. Again, your code is logically correct and works if compiled in Eclipse. The test must just be not accounting for your specific implementation or is forcing you to think about how to use variables in a way that does not violate encapsulation. i.e.

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

Hope this helps.

Regards,

Chris

João Sulzbach
João Sulzbach
2,611 Points

That makes sense! Thanks a lot Chris! :D