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 (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