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 trialyige yang
8,329 Pointsindex.of problem .java
how to solve this problem and how does it happen. THANK YOU.
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
UX Design Techdegree Graduate 22,796 PointsHello 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
UX Design Techdegree Graduate 22,796 PointsYou 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;
}