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

Brian Maimone
PLUS
Brian Maimone
Courses Plus Student 1,644 Points

Trouble with For loop challenge. Appreciate help.

Don't play scrabble. And not sure which variables/strings to compare to determine a "match". I have no syntax errors but my tileCount returns 8 no matter, what so not making right comparisons.

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; } //modifier returnType nameOfMethod (Parameter List) public int getTileCount(char tile) { int tileCount = 0; for (char letter: mHand.toCharArray()) { if (mHand.indexOf(tile) >= 0) { tileCount += 1; } } return tileCount; }

public boolean hasTile(char tile) { return mHand.indexOf(tile) > -1; } }

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;
  }
  //modifier returnType nameOfMethod (Parameter List)
  public int getTileCount(char tile) {
   int tileCount = 0;
    for (char letter: mHand.toCharArray()) { 
      if (mHand.indexOf(tile) >= 0) {
        tileCount += 1; }
    }
    return tileCount;
   }

  public boolean hasTile(char tile) {
   return mHand.indexOf(tile) > -1;
  }
}

2 Answers

Chase Marchione
Chase Marchione
155,055 Points

You're very close! The issue is what you're checking in the if statement inside your for loop. Here's a way of checking if the letter matches the tile (specifically, you want to check if the chars match):

  public int getTileCount(char tile) {
   int tileCount = 0;
    for (char letter: mHand.toCharArray()) { 
      if (letter == tile) {
        tileCount += 1; }
    }
    return tileCount;
   }

Hope this helps!