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

Edward Wilson
Edward Wilson
10,142 Points

How do I use an enhanced for-loop and toCharArray() to count how many times a certain char letter is in a string?

tile = a specific char, and mHand = the String My code so far: public int getTileCount(char tile){ int counter = 0; for(tile:mHand.toCharArray()){ counter++; } return counter; }

the compiler doesn't like that I use 'tile' in the for-loop.

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 counter = 0;
    for(tile:mHand.toCharArray()){
      counter++;
    }
    return counter;
  }

}

2 Answers

Christopher Augg
Christopher Augg
21,223 Points

Edward,

Please refer to my earlier posted answer and comments Here. Especially my comment that begins with "The for each loop is traversing each character of mHand. On the first iteration ..."

Let me know if the information helps or not. I will gladly walk you through the process further if it does not.

Regards,

Chris

Edward Wilson
Edward Wilson
10,142 Points

Thanks, your answer helped.