next up previous
Next: Moor: solution of the Up: Unit 11 Previous: Example: traversal of a

Moor: representation of a moor

To represent a moor, we realize a class Moor that exports the following functionalities:

Moreover, in the class we override the toString() method of Object in such a way that it prints a moor by using the '*' character for a land zone, and the 'o' character for a water zone.

In realizing the class, we choose to represent the moor by means of a matrix of boolean, in which the value true represents a land zone, and the value false represents a water zone.

public class Moor {

  private boolean[][] moor;

  public Moor(int rows, int columns, double probLand) {
    moor = new boolean[rows][columns];
    for (int r = 0; r < rows; r++)
      for (int c = 0; c < columns; c++)
        moor[r][c] = (Math.random() < probLand);
  }

  public int getNumRows() {
    return moor.length;
  }

  public int getNumColumns() {
    return moor[0].length;
  }

  public boolean land(int r, int c) {
    return (r >= 0) && (r < moor.length) &&
      (c >= 0) && (c < moor[0].length) &&
      moor[r][c];
  }

  public String toString() {
    String res = "";
    for (int r = 0; r < moor.length; r++) {
      for (int c = 0; c < moor[0].length; c++)
        res = res + (moor[r][c]? "*" : "o");
      res = res + "\n";
    }
    return res;
  }
}


next up previous
Next: Moor: solution of the Up: Unit 11 Previous: Example: traversal of a