Variable Scope


Instance and Local Variables in the sayAPhrase Method




















 
/** Class documentation goes here.
 */
public class TalkingRobot
{
  // State: instance variables go here.
    private Clock clock;        // used by getTime and sayAPhrase
    private Random generator;   // used by sayAPhrase and respondTo

  // Constructors

    // constructor not shown here...

  // Methods

    // getTime method not shown here...

    /** Outputs a random phrase, based on time of day.
     */
    public void sayAPhrase()
    {
        // Print one of two phrases in the morning or one
        //    of three phrases in the afternoon/evening.
        int hr = this.clock.getHour();
        int randNum;
        if ( hr < 12 )
        {
            randNum = this.generator.nextInt(2);
            if ( randNum == 0 )
                System.out.println("Good morning!");
            else
                System.out.println("Have a great day!");
        }
        else
        {
            randNum = this.generator.nextInt(3);
            if ( randNum == 0 )
                System.out.println("Hi! How are you?");
            else if ( randNum == 1 )
                System.out.println("Half the day is gone!");
            else
                System.out.println("Today has been great!");
        }
    }

    // respondTo method not shown here...

}

Alyce Brady, Kalamazoo College