Exercise 8A (Inheritance)
Implement a class Animal
. It should define a variable holding
the animal's name and the following methods:
Animal
creates an Animal object with the
given name passed as parameter;makeSound
prints out the sound of the generic animal
(just print out some bogus string like "@#%&").
The dog, the cat and the parrot are special types of animals. Implement
a specific class for each of them! Each specific class has a constructor
and overrides makeSound
such as to print out the sound the
specific animal makes.
Furthermore, the parrot class should implement a method repeat
that prints out the string parameter passed into it twice.
Finally implement two specific dog classes representing the Chiwawa and
the Rottweiler breeds. Their makeSound
methods are expected
to print out "bau!" and "BAU!" respectively.
Exercise 8B (Matrices)
The purpose of this exercise is to implement a game of battleship.
The game is played on a grid of 10x10 cells.
The computer-player is your enemy. It can randomly deploy a number of ships on
the grid. Each ship occupies one cell. The computer-player has no weapons.
The human-player tries to destroy all ships using as few turns as possible.
At each turn he or she can shoot two different weapons: cannons and torpedos.
The cannon can be shot at a cell at position (row, column) which is hit.
The torpedo can be shot from a cell at position (row, column) in a
direction given by the values -1, 0 and 1 as shown in the figure. The effect
is that all cells on the torpedo's trajectory are hit.
Part 1
Implement a class Cell
representing a cell on the game's 10x10 grid.
It should store the following attributes:
Cell
should furthermore have the following methods:
toString
that returns:
' '
if the cell has not been hit and it is not
occupied;'X'
if the cell was occupied and has been hit
(that is, a ship was destroyed);'#'
if the cell was empty and has been hit
(that is, a ship was missed).Part 2
Implement a class BattleShip
that holds 10x10 cells.
BattleShip
should have the following methods:
random
from
java.lang.Math
- if the resulting random value
is less than 0.2 the cell is marked as occupied, otherwise it is
marked as not occupied).getNumberOfShips
returns the number of occupied and not hit
cells;shootCannon
is passed two integers row and
column, and marks the cell at that position as hit;launchTorpedo
is passed two integers row and
column as well as a direction (-1, 0 or 1), and marks
all cells on the torpedo's trajectory as hit.toString
returns the string that represents the whole grid
(10 lines of 10 character each), calling each cell's
toString
method.Part 3
Implement a client class for BattleShip
. It should:
BattleShip
;System.in
. The commands are: