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

i have to know how many tile of a specific character they actually have by adding a new method "getTileCount"

it uses the "for" each loop through the character and increment a counter if it matches i have to return the count thx guys !

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;
  }
}

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

You can use the toCharArray() method of the String class to turn the string mHand into an array of chars that you can loop through, using the for each loop. Initialize an int variable to zero to keep track of the count. Then in each iteration of the loop increment that variable if the current character in the array is the same as tile:

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 character: mHand.toCharArray()) {
      if (character == tile) {
        count++;  
      }
    }
    return count;
  }
}

wow thx a lot man !