Java Java Objects Creating the MVP Counting Scrabble Tiles

Michelle Huang
Michelle Huang
1,322 Points

I'm confused about the (char letter). Where is this coming from? Do I need to declare it as a, instance variable?

i'm confused with the tile, tiles, and letter variables here. I was having trouble completing the challenge and had to look at the answer, but I'm still having a hard time understanding the for loop

ScrabblePlayer.java
public class ScrabblePlayer {
  // A String representing all of the tiles that this player has
  private String tiles;

  public ScrabblePlayer() {
    tiles = "";
  }

  public String getTiles() {
    return tiles;
  }

  public void addTile(char tile) {
    tiles += tile;
  }

  public boolean hasTile(char tile) {
    return tiles.indexOf(tile) != -1;
  }
}
Example.java
// This code is here for example purposes only
public class Example {

  public static void main(String[] args) {
    ScrabblePlayer player1 = new ScrabblePlayer();
    player1.addTile('d');
    player1.addTile('d');
    player1.addTile('p');
    player1.addTile('e');
    player1.addTile('l');
    player1.addTile('u');

    ScrabblePlayer player2 = new ScrabblePlayer();
    player2.addTile('z');
    player2.addTile('z');
    player2.addTile('y');
    player2.addTile('f');
    player2.addTile('u');
    player2.addTile('z');

    int count = 0;
    // This would set count to 1 because player1 has 1 'p' tile in her collection of tiles
    count = player1.getCountOfLetter('p');
    // This would set count to 2 because player1 has 2 'd'' tiles in her collection of tiles
    count = player1.getCountOfLetter('d');
    // This would set 0, because there isn't an 'a' tile in player1's tiles
    count = player1.getCountOfLetter('a');

    // This will return 3 because player2 has 3 'z' tiles in his collection of tiles
    count = player2.getCountOfLetter('z');
    // This will return 1 because player2 has 1 'f' tiles in his collection of tiles
    count = player2.getCountOfLetter('f');
  }
}

1 Answer

kevin bush
kevin bush
4,113 Points

Hi Michelle Huang, The (char tile) is a parameter. This is what is called from your main function, such as with "player2.addTile('z')". In this example the 'z' will become the char tile for that instance. From the "public void addTile(char tile)" method it will take the char of z and bring that into the method renaming it tile only for the purpose of the addTile method. It then adds it to Tiles and once the method is done the char tile is gone. I hope this helps.