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

Micah Dunson
Micah Dunson
34,368 Points

Need help with Java For loop

I'm fairly new to programming with Java and need some help. For this example I'm supposed to use a for loop to and count the number of tiles in a hand. From following along with the videos and the previous examples I have not had any real problems with my code until now. I'm attempting to apply the for loop similar to how I used it for the project and it does not seem to work no matter how I try and am not sure where I am making my mistake. Any help is greatly appreciated.

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

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

2 Answers

  public int getTileCount(char tile) {
    int letscount=0;
   for(char c : mHand.toCharArray()) {
    if(Character.toUpperCase(c) == Character.toUpperCase(tile)) {
       letscount++;
    } 
   }
    return letscount;
  } 

This is the simplest solution in my opinion. Feel free to ask questions.

Micah Dunson
Micah Dunson
34,368 Points

Hey thanks a lot. I definitely see where my problem was.

John Marley
John Marley
8,740 Points

Although this works, what happens if you want the char in the for loop to be something unspecific, something other than C? Or is this not important to the program? :)

Micah Dunson
Micah Dunson
34,368 Points

you can use what ever variable you like for char assignment. 'C' just happened to be used in this case, but you can use whatever.