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

Antone Bagnall
Antone Bagnall
6,744 Points

For Each loop

Hi,

I'm not entirely sure what this task is asking me to do, does it want me to count how many tiles of each letter the player has?

Also, I'm a bit confused as to how I use a For Each loop to do this. Any help would be greatly appreciated.

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 getTileCount(char letter) {
  int counter = 0;

    for( char tile : mHand.toCharArray()){

      if(tile.indexOf(letter) >= 0) {

      counter++;
      }
    }
    return counter;
  }




}

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Very close!

You want to check how many times the tile is in the hand, so you loop over each letter in the hand and compare it to the tile passed in.

Instead of seeing if it exists anywhere in the hand, why not check to see if the tile equals the letter?

Hope that helps!

Antone Bagnall
Antone Bagnall
6,744 Points

Brilliant!!!

Thanks for your help!