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

Noah Schill
Noah Schill
10,020 Points

The hand was "sreclhak" and 'e' was checked. Expected 1 but got 8.

I don't understand why it isn't filtering the incorrect letter through? It should come out as one.

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 (char letter : mHand.toCharArray()) {
      if (mHand.indexOf(tile) > -1) {
        counter ++;
      }
    } 
    return counter;
  }

}

1 Answer

Rebecca Bompiani
Rebecca Bompiani
16,948 Points

Hi Noah-

You're so close! The problem comes in on the if portion inside your for loop. What you have now says: "For each char in mHand, if the tile exists ANYWHERE in mHand, add one to the counter" Because the char does exist in the hand, it adds one for each char in the hand (8);

The fix to this is: "For each char in mHand, if the tile matches the char, add one to the counter"

Try:

  public int getTileCount(char tile) {
    int counter = 0;
    for (char letter : mHand.toCharArray()) {
      if (letter==tile) {
        counter ++;
      }
    } 
    return counter;
  }
Noah Schill
Noah Schill
10,020 Points

Thank you so much! I didn't realise it was such a simple task. I have a habit of making things harder than they should be :D!