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

Tim Strand
Tim Strand
22,458 Points

Why bother defining getHand, addTile when i cant reference them?

I am stuck trying to create a loop to count the number of each letters tile in my hand. 1) i cant seem to reference any of my previous variables 2) i cant seem to use the same variable (tile in multiple spots of my getTileCount logic) unlike the Hangman example in class. Where we ref letter 4 times. public boolean applyGuess(char letter) { boolean isHit = mAnswer.indexOf(letter)>= 0; if (isHit) { mHits += letter; } else { mMisses += letter; } return isHit;

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 (int letter: mHand.toCharArray()) {

        tileCount += letter;
  }
  return tileCount;
          }

}

2 Answers

Geovanie Alvarez
Geovanie Alvarez
21,500 Points

You almost haved the only you need to check if the tile is equal to letter

public int getTileCount(char tile) {
  int tileCount = 0;


  for (char letter: mHand.toCharArray()) { // change the int to char
    if(tile == letter){ // <-------- here check if the tile is equal to letter
        tileCount++; // increment
    }
  }
  return tileCount;
}
Tim Strand
Tim Strand
22,458 Points

thanks for your prompt response. why does my incrementor result in 845 vs yours which results in 8? the correct response is 1 so i am still digging a bit but i am unclear what was wrong with my incrementor logic

Geovanie Alvarez
Geovanie Alvarez
21,500 Points

Well in your code you are increment each latter but in the challenge they wan to increment the specific char that is why you have to use the if statement