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

So back to that ScrabblePlayer. I found that it's not enough to know if they just have a tile of a specific character. W

So basically i finished this challenge but do not entirely understand how this works. If someone could explain this to me that would be great.

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

}

2 Answers

Kevin Faust
Kevin Faust
15,353 Points

Hey Yasir, this was a tricky question and I'll try to break it down as simple as I can:

public int getTileCount(char tTile) {
    int count = 0;

In the line above, we basically got our method and we can pass in any letter and that letter will be known as tTile inside our method.

When we write "count", we're just going to have a fresh counter that currently has a value of 0. As we loop later on, we will increase that counter everytime that tTile letter matches a character inside our mHands.

    for (char tile: mHand.toCharArray()) {
      if(tile == tTile) {
        count++;
      }
    }

Here is where the main action happens. Our main goal is to check if the character we pass in matches a character in our mHands so to first do that, we change our string our letters inside mHands into an array of characters.

After that, we loop through each letter and then check if it equals to the letter we passed in. If it matches, then we increase our counter by 1. We keep doing this until we loop through our entire array of characters.

    return count;
  }

and this as you already know just returns that count variable which at first was 0 but now contains how many matches the letter we passed in has to mHands.

I hope that helped and happy coding!

Kevin

Jordan Bester
Jordan Bester
4,752 Points

Hey why was this an int instead of :

Public String getTileCount? if someone could explain that would be awesome.