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 For Each Loop

Issue with Scrabble Player challenge: GetTileCount method is missing return statement

I need to create the method getTileCount to check to see how many of a given tile are in a player's hand. However, the compiler tells me that the method I've written below is missing a return statement, and I'm not sure why. Can someone explain what I'm doing wrong? Thanks!

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) {
   return mHand.indexOf(tile) > -1;
  }

  public int getTileCount(char tile) {
    int tileCount = 0;
    for (char letter: mHand.toCharArray()) {
      if (mHand.indexOf(letter) >= 0) {
        tileCount += 1;
      }    
      return tileCount;
    }
  }
}
Valentin Bona
Valentin Bona
1,060 Points

Return statement should be outside for loop

2 Answers

Richard Ling
Richard Ling
8,522 Points

Hi Kathryn,

The error is in the last method at the end of your code, getTileCount(). The return statement should be outside the loop, so move it underneath the next closing bracket.

There is another error with your code in the same method, but let me know if you'd like help with it or want to take a crack yourself first :)

Thanks, Rich

Thanks, Rich! I figured it out.

First let me ask you this. Do you want to return tileCount inside of the for loop? The way you have the method set up would end the loop after 1 call, but moving it outside of it will wait for it to finish looping before returning. Also, it appears the error goes away when you do this.

  public int getTileCount(char tile) {
    int tileCount = 0;
    for (char letter: mHand.toCharArray()) {
      if (mHand.indexOf(letter) >= 0) {
        tileCount += 1;
      }    
    }
    return tileCount;
  }