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 Counting Scrabble Tiles

Cory Walker
Cory Walker
6,037 Points

Need help with this exercise

Can't figure this one out

ScrabblePlayer.java
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;
  }

  public int getCountOfLetter(char letter){
   int count = 0;
    count = tiles.getCountOfLetter(letter);
   return count; 
  }
}
//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. 

1 Answer

David Moody
David Moody
19,302 Points

Here is your code:

  public int getCountOfLetter(char letter){
   int count = 0;
    count = tiles.getCountOfLetter(letter);
   return count; 
  }

First, in that code, you cannot use getCountOfLetter since you are trying to create the method getCountOfLetter. You have to iterate through each tile. Basically, the user gives a letter, and the method returns how many times that letter appears in the tiles.

Second, because tiles is a string, you have to separate the string into a character array. The code for that is this:

tiles.toCharArray().

Third, you have to iterate through each tile and if the tile matches, you increase the count, using an advanced foreach loop. Like this:

public int getCountOfLetter(char letter) {
      int count = 0;
      for(char tile : tiles.toCharArray()) {
         if (tile == letter) {
            count++;
         }
       }
  return count;
  }