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

Java

Can someone help me with this task please?

ScrabblePlayer.java
public class ScrabblePlayer {
  private String mHand;
  public int counter;
  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 getTileCount() {
  for (char letter : mHand.toCharArray()) {
  counter += 1;
     return counter;
  }

  }
}

You need to add a char parameter to your method heading and increment the counter only if the tile in each iteration matches what was passed in. I can break it down for you more if you need me to.

yes please break it down more

2 Answers

Okay it looks like your for loop is already in place so now inside you need to add an if statement that will ck to see if the current iteration matches the char that was passed in, if it does then increment the count variable that you created. After the for loop ends simply return the count. Like this:

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

   return count;
}

ok thanks :)

for some reason I can't return "count" any idea why?

I just tested the code and it works. You may need to check where your curly braces are and make sure that your return statement is in the right place. I will give you the entire code to see where my return statement is:

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()){
      if(letter == tile){
         count++;
      }
   }

   return count;
}



}