A Battery
is an object that implements the following interface:
interface BatteryI { // The current charge of the battery is a number between 0 // and MAX_CHARGE (inclusive). final int MAX_CHARGE = 5; // A call to recharge() sets the current charge to MAX_CHARGE. void recharge(); // A call to use() throws the NoPower exception if the current // charge is 0; otherwise it decrements the current charge by 1. void use () throws NoPower; }
Write class definitions for NoPower
and Battery
.
A Maze
is recursively built using two kinds of objects:
DeadEnd
, or
Hall
leading to two Maze
s: a left one and a right one.
Every Maze
object (whether it is a DeadEnd
or a Hall
):
String
that identifies it,
MazeVisitor
s.
Formally, a Maze
object implements the following interface:
interface MazeI { String toString (); boolean hasTreasure (); boolean hasElectricOutlet (); void accept (MazeVisitor rv) throws VisitorStuck; }
Given that the MazeVisitor
interface is:
interface MazeVisitor { void visitDeadEnd (DeadEnd r) throws VisitorStuck; void visitHall (Hall r) throws VisitorStuck; }
write class definitions for Maze
, DeadEnd
, and Hall
.
The goal of a TreasureSeeker
is to look for a DeadEnd
or Hall
object that has a treasure. To be able to search the maze, a TreasureSeeker
must implement the MazeVisitor
interface (defined in Problem II). In addition, every TreasureSeeker
will have an instance variable treasureLocation
of type String
in which it will save the location of the treasure.
The details of visiting a maze are as follows:
MazeVisitor
may fail by throwing a VisitorStuck
exception. Failures can be fatal or non-fatal:
class VisitorStuck extends Exception { boolean fatal; VisitorStuck (boolean f) { fatal = f; } }
DeadEnd
object, the TreasureSeeker
will look for the treasure. If it finds it, it saves it in the treasureLocation
and returns. Otherwise, it signals failure by throwing a non-fatal VisitorStuck
exception.Hall
object, the TreasureSeeker
will first look for the treasure in the current Hall
object. If it finds it, it saves it and returns. Otherwise, it searches the left Maze
. If a non-fatal exception occurs during that search, it will search the right Maze
. If the exception was fatal, it re-throws it.
Write the class TreasureSeeker
.
A Robot is-a TreasureSeeker
operating on batteries. Every Robot
has a Battery
initially charged to MAX_CHARGE
.
When visiting either a DeadEnd
or a Hall
, the Robot
will first try to use its Battery
. If there is enough charge, it will perform the same operations as the generic TreasureSeeker
. Otherwise, if there is not enough power, the Robot
will look for an electricOutlet
, and if it finds one, it will recharge its Battery
, and try to visit the DeadEnd
or Hall
again. If the Robot
can't find an electricOutlet
, it will throw a fatal VisitorStuck
exception.
Write the class Robot
.
Last modified: 05/19/99 10:14:25
yreimer@cs.uoregon.edu