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

I feel like I'm on the right track, but just can't push it over the finish line...

Here's my code:

  public int getTileCount(char tile) {
    int count ;
    for (char letter: mHand.toCharArray()){
      count = 0;
      if(mHand.indexOf(tile)>-1){
        int newCount = count +=1;
       count = newCount;
      } else {
        count = 0;
      }
    }

      return count;
    }

What am I missing???

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

      return count;
    }
}

2 Answers

Chase Marchione
Chase Marchione
155,055 Points

Hi Shadd,

  • Instead of attempting two counter variables here, we can conveniently do the job with just one. We're only returning the value of one counter variable, and we wouldn't want to try to declare the same new counter variable every time an if statement runs, too.

  • We don't need to set the counter variable back to 0 every time we run the for loop or if the letter and tile aren't equal. If we reset the counter every single time there isn't a match, it would be like we're cancelling out that we found any other matches.

There are multiple ways to write getTileCount, but a convenient way is to up the counter if the letter and tile match, and otherwise, not have anything extra done:

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

      return count;
    }
}

Hope this helps!

The classic "keep it simple stupid". I was way over thinking it lol

Thank you