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

returning the result of an expression that uses the index of a char

in hasTile method how do i return true if the tile is in the tiles field or false if it isn't solving it by returning the result of the 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;
  private char result;

  public ScrabblePlayer() {
    tiles = "";
  }

  public String getTiles() {
    return tiles;
  }

  public char getResult(){
  return result;
  }

  public void addTile(char tile) {
    tiles += "tile";
    // TODO: Add the tile to tiles
  }
public boolean hasTiles(char tile){
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 Simbarashe Mazambani

This is how I approached the problem. I first 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.

thank you, you are a superman.