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

Scrabble count tiles

one of the promts when i did something wrong says i need to get char for the getTileCount method. So i must use the char t which i put as input, to go through the loop but the for-each-loop requires me to initialize char?? to go through the string? I must have understood this wrong. Would you please let me know what i am doing wrong?

Thank you

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

1 Answer

Michelle, almost there. The issue is in your for loop. You need to access each char in mHand, and compare it to t. The easiest way is to use indexOf() to get each char, but you need a loop counter (i) to traverse mHand:

public class ScrabblePlayer {
   private String mHand;

   public int getTileCount(char t){
      int mCount = 0;

      for (int i = 0; i < mHand.length(); i++) {
         if(mHand.charAt(i) == t){
            mCount++; 
         }
      }
      return mCount;
   }

   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;
   }

}

I need to use the for each loop for this. I am not sure why but it keeps returning the number of letters in a string not number of character the promter is looking for