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

Christiaan Hendriksen
Christiaan Hendriksen
5,982 Points

Expected 1 but got 8

I've tried a few ways to get this challenge completed, but I'm completely stuck. Any ideas?

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 tileToFind) {
    int tileCount = 0;
    for (char current: mHand.toCharArray()) {
      if (mHand.indexOf(tileToFind) >= 0) {
        tileCount++;
      }
    }
    return tileCount;
  }
}

2 Answers

Roman Kuzhelev
Roman Kuzhelev
7,853 Points

Let me figure out what currently your 'getTileCount' method is doing:

for each character in your string 
  if tileToFind exists amongst characters of your string
    increment a counter

Suppose that you have a string with 8 characters. Suppose also that as input you have provided a character from the set of those 8. As a result you will have 8 iterations, and on each iteration you will increment a counter due to the fact that the input character is amongst the characters of your string.

Consider the following code that could solve your issue and fulfill the requirements of the related task:

public int getTileCount(char tileToFind) {
    int tileCount = 0;
    for (char current: mHand.toCharArray()) {
      if (current == tileToFind) {
        tileCount++;
      }
    }
    return tileCount;
}
Christiaan Hendriksen
Christiaan Hendriksen
5,982 Points

Ah amazing, that makes sense. Thank you so much!