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

It's telling me counter is returning 1 when it should be returning 0

I don't see why it should be returning 1 if n is inputed and n is not one of the 8 tiles of the hand. I cannot find an error in my code help would be appreciated.

ScrabblePlayer.java
public class ScrabblePlayer {
  private String mHand;
  public int counter = 0;
  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) {
    for (char letter: mHand.toCharArray()) {
      if (tile == letter) {
       counter += 1; 
      } 
    }
    return counter;
  }
}

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Try putting the counter variable inside method instead of as a public variable.

Craig, I appreciate the help it worked! I am still confused though because in reality shouldn't the code as I had it work? I figure that as long as nothing else modifies the counter value besides the if conditional, making it a 'public int' should work. Also, if I had just declared the counter variable by typing 'public int counter;' at the top, what does java set the integer to initially? 0? Blank space?