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

Marko Kallaspoolik
Marko Kallaspoolik
10,455 Points

Challange Task (Java Objects)

I need a help to solve this task: to correct existing hasTile method to return true if the tile is in the tiles field, and false if it isn't. The task of this challenge is to practice returning the result of the expression that uses the index of a char in a String. Thank you....

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

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

  public String getTiles() {
    return tiles;
  }

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

  }

  public boolean hasTile(char tile) {
    boolean isInTheTilesField = tiles.indexOf(tile) != -1;
    if (isInTheTilesField) {
      return true;
    } else {
    // TODO: Determine if user has the tile passed in
    return false;
  }
  }
}

2 Answers

andren
andren
28,558 Points

Technically the code you have written would actually work, but the challenge wants you to complete the task without using an if statement as that is pretty redundant for this task.

The expression you have written (tiles.indexOf(tile) != -1) evaluates to True or False on its own, so using an if statement is not necessary. You can just return the Boolean the expression results in directly, like this:

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

That results in the same result as you current code but is more efficient.