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

Getting count as the no. of characters in the word , and not able to increase the count if a character i appearing twice

Please check the code and let me know the corrections to made in the if block inside for each loop

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 aTile){
    int tileCount=0;
    for (char tile: mHand.ToCharArray()){
      if (mHand.indexOf(aTile)>=0){
      tileCount+=1;
      }
    }
    return tileCount;
  }
}

1 Answer

Hi there,

You were correct until here:

if (mHand.indexOf(aTile)>=0){

You are looping through your mHand as you have converted it to a charArray(). That's correct. At each loop, you are taking the next letter in the array and assigning that to your loop variable called tile. So, you want to see if the character you passed into the method as a parameter, aTile, is equal to any of the letters in your charArray. So you want to compare each tile with aTile and increment tileCount where they are equal.

  public int getTileCount(char aTile){
    int tileCount=0;
    for (char tile: mHand.ToCharArray()){
      if (tile == aTile){
        tileCount+=1;
      }
    }
    return tileCount;
  }

I hope that makes sense!

Steve

There's another post on it here

Got the logic...Thanks Steve