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