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

where is the letter variable getting its data from in this code? (getTileCount method)

its using letter in the for loop and for comparison but i dont know what the letter varaible is?

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 count = 0;
    for (char letter: mHand.toCharArray()) {
      if(letter == tile) {
            count += 1;
        }
    }
   return count;
  }

}

1 Answer

Rebecca Rich
PLUS
Rebecca Rich
Courses Plus Student 8,592 Points

The for (char letter: mHand.toCharArray()) { ... } loop syntax walks through all of the elements in the mHand.toCharArray(), each time assigning the element to the variable letter that can then be used inside the loop.

It would be equivalent to this:

for (int i = 0; i < mHand.length(); i++) {
    char letter = mHand.charAt(i);
    ...
}

okay so im just letting enhanced loops confuse me and the letter variable was just created for the for loop?

Rebecca Rich
Rebecca Rich
Courses Plus Student 8,592 Points

Yeah, the rest of your code seems fine. Indeed, it's just a different way of writing a for loop in Java; the letter variable was just created so that inside the for loop, you can walk through all of the letters in the scrabble hand and compare them to the letter you are looking for and trying to count the occurrences of. This has been a pretty popular question on these forums, so don't worry about it! It's good you came and asked about it.