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

Java, For each loop

Im trying to solve the challenge,

My current code is:

public int GetTileCount(char tile) { int count = 0; for(tile: mHand.toCharArray()) { if(hasTile(tile)) { count++; } } return count; }

Im not sure what I am doing wrong, would be great if you could help me

Thanks!

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

Alexander Bueno
Alexander Bueno
5,398 Points

in your for each loop you should specify the variable you are creating such as

for(char handTile: mHand.toCharArray()){
}

The issue that you are probably confused about is that you are trying to assign the tile you are taking in to each of the of the tiles in the player's hand, when you should be creating a variable (Example char handTile) to take hold of each individual letter per iteration of the loop in order to compare it to the letter you are getting as an argument for the method.

Your second issue is a simple one to fix all you have to do is compare the character that you recieved as an argument for the method and since you just want to make sure it matches anything in your hand then all you have to do is use an "==" to compare the letter with the tile.

if(tile == handTile){
   count++;
}

Using the "==" works fine here but if we were to be using capital letters than you would definitely have an issue since characters have a value called unicode. This would cause an issue because "a" does not have the exact same value as "A".

If you want to learn a little bit more about unicode here's a link. https://docs.oracle.com/javase/tutorial/i18n/text/unicode.html

Thanks for the help ! :)