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 Creating the MVP Current Progress

Can't solve the challenge

Create a new method named getCountOfLetter that returns an int, and requires a parameter of type char named letter. For this task, just make it return 0. What is the answer for it?

public class ScrabblePlayer {
  // A String representing all of the tiles that this player has
  private String tiles;

  public ScrabblePlayer() {
    tiles = "";
  }

  public String getTiles() {
    return tiles;
  }

  public void addTile(char tile) {
    tiles += tile;
  }

  public boolean hasTile(char tile) {
    return tiles.indexOf(tile) != -1;
  }
}

2 Answers

Vladut Astalos
Vladut Astalos
11,246 Points

You have to add a new method to your existing code. The instructions for this challenge are pretty specific, anyway if you are stuck your method should look like this:

public int getCountOfLetter(char letter){
    return 0;
} 

Oh yes, I had written getCounOfLetter, that is why I couldn't solve it. I'm struggling with the second challenge though, could you help me? Now in your new method, have it return a number representing the count of tiles that match the letter that was passed in to the method. Make sure to check Example.java for some example uses.

Vladut Astalos
Vladut Astalos
11,246 Points

Now you have to declare a variable of type int that will count the letters and initialize it with 0. Then with a for-each loop you check for every letter in your 'tiles' string if matches with the letter that you passed in as parameter. In order to do that you need to convert your 'tiles' to an char array. Then every time a letter match you increase that counter by 1.

public int getCountOfLetter(char letter){
    int count = 0;
    for(char tile : tiles.toCharArray()){
      if(tile == letter){
        count += 1;
     }
    }
    return count;
}
Albert González
Albert González
22,953 Points

For the increment it's better "count++;"