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