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

returning the result of the expression that uses the index of a char in a String.

tiles.indexOf(tile) should return -1 and hence false if char tile is not inside String tiles,elsewise true as the function hasTiles is meant to return a boolean variable,i dont see why the code isng not worki

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

  public ScrabblePlayer() {
    tiles = "";
  }

  public String getTiles() {
    return tiles;
  }

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

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

}

1 Answer

andren
andren
28,538 Points

If this was coded in JavaScript, Python, PHP or something like that then that might work, but Java is not a language that translates non-Booleans to a Boolean automatically. -1 is not equivalent to false, it is equal to -1 and nothing else. Java is a very strict language as far as type conversion is concerned.

When you state that your function returns a Boolean it needs to return an actual Boolean, not an int. So in this case you need to use a comparison to have your code actually return a Boolean. Like this:

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

  public ScrabblePlayer() {
    tiles = "";
  }

  public String getTiles() {
    return tiles;
  }

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

  public boolean hasTile(char tile) 
  {
    // Check that `indexOf` does not return -1 and return the Boolean that comparison produces
    return tiles.indexOf(tile) != -1; 
  }
}