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

Return true

Help, I'm failing to give an expression that uses the index of a char in a String.

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

  public ScrabblePlayer() {
    tiles = "t";
  }

  public String getTiles() {
    return tiles;
  }

  public void addTile(char tile) {
    // TODO: Add the tile to tiles
  tiles += "t" ; 
  }

  public boolean hasTile(char tile) {
    // TODO: Determine if user has the tile passed in
    return false;

  }

}

1 Answer

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 Points

Hi, great to see you around.

This is how I approached the first problem. I took the field tiles declared and the top of class and added char tile to it using += operator.

public void addTile(char tile) {
    // TODO: Add the tile to tiles
    tiles+= tile;
  }

For the second task I created a boolean hasLetter and I set it to false. I then went for the for-loop to iterate through the characters contained inside tiles. I used *String.toCharArray().length * method to convert the tiles to an array of characters and get the number of letters.

Lastly, I used *String.indexOf( char) * which returns ** -1 ** if the character is not found, if the character is found, it returns a number that is greater or equal to zero.

public boolean hasTile(char tile) {
    // TODO: Determine if user has the tile passed in

    boolean hasLetter = false;
    for(int i =0; i<tiles.toCharArray().length; i++){

   hasLetter = ( tiles.indexOf(tile) >=0);

    }
    return hasLetter;
}

The for-each also works fine as demonstrated below

public boolean hasTile(char tile) {
    // TODO: Determine if user has the tile passed in
    boolean hasLetter = false;
    for(Character letter: tiles.toCharArray()){

      hasLetter =tiles.indexOf(tile)>=0;
    }
    return hasLetter;
  }

Happy coding Nkosinolwazi Moyo