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

Shane May
Shane May
5,114 Points

getTileCount challenge! I'm getting an output of 9 instead of 1 and I'm not sure why. Please help.

getTileCount challenge! I'm getting an output of 9 instead of 1 and I'm not sure why. Please help.

ScrabblePlayer.java
public class ScrabblePlayer {
  private String mHand;

public int getTileCount(char letter){
  int count = 0;
 for(int i=0;i<=mHand.length();i++){
   if(mHand.indexOf(letter) >= 0){
     count++;
   }
 }
  return count;
}

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

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

When the hand is "sreclhak" the confition mHand.indexOf(letter) > = 0 will always be true when the letter is 'e' since there is an 'e' in "sreclhak"; therefore your code ends up incrementing count 9 times.

You can use the method toCharArray() to turn mHand into an array of characters. Then use a for each loop to loop through that array, comparing each character with the variable letter. If they are the same increment count. Here's the code:

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 count = 0;
    for(char character: mHand.toCharArray()) {
      if(character == letter) {
        count++;
      }
    }
    return count;
  }
}
Shane May
Shane May
5,114 Points

That worked thank you. At first I tried to do the for each loop but I got confused by the error I got for declaring letter twice (char letter)....for(char letter: mHand.toCharArray()). So I went to a for loop. Thank you for clearing that up for me. I Don't know why I didn't call one char letter and another character and test to see if they are the same.