Variable Scope


Client Code   TalkingRobot Code













Clock clock = new Clock();
TalkingRobot robot =
        new TalkingRobot(clock);











System.out.println("Timestamp: " +
        robot.getTime());
robot.sayAPhrase();









String response;
response =
    robot.respondTo("Do you want " +
        "lunch?");
System.out.println("Response was: " +
        response);

response =
    robot.respondTo("What are " +
        "local variables and " +
        "instance variables?");
System.out.println("Response was: " +
        response);



 
/** Class documentation goes here.
 */
public class TalkingRobot
{
  // State: instance variables go here.
    private Clock clock;
    private Random generator;

  // Constructors

    /**  Constructs a new TalkingRobot object.
     *      @param  aClock    clock to be used by robot
     */
    public TalkingRobot(Clock aClock)
    {
        // code not shown
    }

  // Methods

    /** Gets the time from the robot's clock.
     *      @return   the time in HH:MM AM (or HH:MM PM) format
     */
    public String getTime()
    {
        // code not shown
    }

    /** Outputs a random phrase, based on time of day.
     */
    public void sayAPhrase()
    {
        // code not shown
    }

    /** Responds to a user question with a random response.
     *      @param question  the user question
     *      @return the response
     */
    public String respondTo(String question)
    {
        // Print a lunchtime-related random phrase
        //    or a more general random phrase.
        int randNum = this.generator.nextInt(3);
        if ( question.contains("lunch") )
        {
            if ( randNum == 0 )
                return "Lunch... Not hungry yet.";
            else if ( randNum == 1 )
                return "Is it lunchtime already?";
            else
                return "I always like pizza.";
        }
        else
        {
            if ( randNum == 0 )
                return "No idea!";
            else if ( randNum == 1 )
                return "Your guess is as good as mine.";
            else
                return "What do you think?";

        }

    }

}

Alyce Brady, Kalamazoo College