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 (Retired) Creating the MVP Strings and Chars

Tommy Choe
Tommy Choe
38,156 Points

if(mHand.indexOf(tile)) why wouldn't this code work?

I thought I had the code right but the quiz keeps telling me that there is a compiler error. It won't show me anything on the preview either. Is this a wrong way to code this problem?

public boolean hasTile(char tile) { boolean holdsTile; if (mHand.indexOf(tile)) { holdsTile = true; } else { holdsTile = false; } return holdsTile; }

ScrabblePlayer.java
public class ScrabblePlayer {
    private String mHand;

    public ScrabblePlayer() {
        mHand = "";
    }

    public String getHand() {
       return mHand;
    }

    public void addTile(char tile) {
        // Adds the tile to the hand of the player
      mHand += tile;
    }

    public boolean hasTile(char tile) {
      boolean holdsTile;
      if (mHand.indexOf(tile)) {
        holdsTile = true; 
      } else {
        holdsTile = false; 
      }
      return holdsTile;
    }
}
Tommy Choe
Tommy Choe
38,156 Points

I have the answer now but I wanted to see if this was a viable way to code this. Thanks!

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Truthy and falsey concepts don't really exist in Java. You need to coerce your expression into a boolean. Even if it did, when something is not found it returns -1. Since truthy acceptable languages use 0 for false and any not 0 value for true, this would not work correctly.

Quick tip: You can return the results of an expression. Anytime you feel yourself returning true or false in an if statement, try something like this:

return mHand.indexOf(tile) >= -1