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

Peter Taylor
PLUS
Peter Taylor
Courses Plus Student 4,275 Points

Why won't the if statement allow boolean conversion

Error from compiler says 'if' statement below can't convert to boolean. Any ideas on why that is?

I can't seem to replicate the code from the video correctly. No matter what I do it throws up that I this boolean conversion error.

ScrabblePlayer.java
public class ScrabblePlayer {
    private String mHand;
  private boolean mH;

    public ScrabblePlayer() {
        mHand = "";
    }

    public String getHand() {
       return mHand;
    }

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

    public boolean hasTile(char tile) {

      if(mHand.indexOf(tile){
        return true;
      }
      else{
        return false;
      } 
    }
}

1 Answer

The indexOf function returns a index (integer), not if the item is in the array (boolean).

However, here's one trick: the indexOf function returns -1 if the item is not in the array.

So, to fix your hasTile function, you could do this:

public boolean hasTile(char tile) {
    if (mHand.indexOf(tile) > -1) {
        return true;
    } else {
        return false;
    }
}

I hope you understand.

Good luck! ~Alex

If you got any questions, please ask below :)

Did you try this in the challenge? Because it doesn't pass.

You have the right idea but what happens if the tile is found at index 0?

Whoops XD

Wasn't thinking.

I was busy on a different thing, also, so I didn't check.

I fixed it.