Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects Creating the MVP Scrabble Tiles

yige yang
yige yang
8,329 Points

index.of problem .java

how to solve this problem and how does it happen. THANK YOU.

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

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

  public String getTiles() {
    return tiles;
  }

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


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

2 Answers

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

Hello yige yang

You did the first challenge well, impressive!!

This is how I approached the second 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 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;
}
Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,793 Points

You can also use for-each loop for this problem:

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;
  }