Part 2: Create a class called Rack to represent a player\'s tile rack in Scrabbl
ID: 3635604 • Letter: P
Question
Part 2: Create a class called Rack to represent a player's tile rack in Scrabble. This class shouldinclude:
• A private ArrayList named tiles that holds Tile objects.
• A public zero-parameter constructor method that creates the ArrayList
• A public method called size that returns the number of tiles on the Rack.
• A public method called getPoints that returns the total point value of all tiles on the Rack.
• A public method called toString that returns a String the tiles currently on the Rack, if
there are tiles and returns “Empty” if the Rack is empty.
• A public method that allows a Tile to be added to the Rack.
• A public method that removes a Tile from the Rack by character.
Explanation / Answer
//Tile class contain details of tile.
class Tile{
private char letter;
private int value;
Tile(char letter,int value){
this.letter=letter;
this.value=value;
}
public void setLetter(char letter){
this.letter=letter;
}
public void setValue(int value){
this.value=value;
}
public char getLetter(){
return this.letter;
}
public int getValue(){
return this.value;
}
}
//given the rack class which contain arraylist that hold different tiles..
class Rack{
private ArrayList<Tile> tiles;
Rack(){
this.tiles= new ArrayList<Tile>(); //ArrayList creation;
}
public void size(){
return tiles.size();
}
public void getPoints(){
int points;
for(Object ob:tiles)
{
points=points+ob.value; // adding values of all tiles in rack
}
return points;
}
public void addTile(Tile tile){
tiles.add(tile);
}
public void removeTile(Tile tile){
tiles.remove(tile);
}
public String toString(){
if (tiles.isEmpty())
return "Rack Empty";
else{
String name=" ";
for(Object ob:tiles)
name=name + " "+ob.getLetter(); // Storing names of all tiles in rack in variable called 'name'
return name;
}
}
}
Hope this code will work.....