Chapter 5
More sophisticated behavior

powered by FreeFind

Modified: 

Overview

Chapter 4 examined some of the ways objects may be grouped together into collections. Here we will look at several types of collections, random behavior, and writing program documentation.

5.1 Documentation for library classes

The Java class library is extensive. Documentation of the classes in HTML is on the text CD for installation onto your computer or is available by searching the web.

5.2 The TechSupport system

Exercise 1 - SupportSystem class

In BlueJ

  1. Open project chapter05\tech-support1.
  2. Create a SupportSystem object.
    • Call the start() method.
      • Ask questions of SupportSystem.
      • Type "Bye" to finish. Did it work?
      • Type " bye" to finish. Did that work?
      • Type "bye" to finish. Did that work?
    • Call the start() method again.
      • Ask questions of SupportSystem.
      • Type "bye" to finish.

 

5.2.2 Reading the SupportSystem code

  public class SupportSystem
 {
   private InputReader reader;
   private Responder responder;
   public SupportSystem()
  {
     reader = new InputReader();
     responder = new Responder();
   }
    public void start()
   {
      boolean finished = false;
      printWelcome();

      while( !finished ) {
          String input = reader.getInput();
          if(input.startsWith( "bye" )) {
               finished = true;
          }
          else {
               String response = responder.generateResponse();
               System.out.println(response);
          }
      }
      printGoodbye();
  }
    private void printWelcome()
   {
          System.out.println("Welcome to the DodgySoft Technical Support System.");
          System.out.println();
          System.out.println("Please tell us about your problem.");
          System.out.println("We will assist you with any problem you might have.");
          System.out.println("Please type 'bye' to exit our system.");
   }
    private void printGoodbye()
   {
          System.out.println("Nice talking to you. Bye...");
   }
 }

 

  public class Responder
 {
   public Responder()
  {   }
   public String generateResponse()
   {
        return "That sounds interesting. Tell me more...";
   }
 }


String comparisions

Exercise 2 - Reading the code

In your head

  1. What is?
    1. "RAYMOND".startsWith("Ray")
    2. "RAYMOND".startsWith("AY")
    3. "RAY".equals("Ray")
    4. !"RAY".equals("Ray")
       
  2. What will the following Java statements do? Will printGoodbye()  be executed?
    public void start()
   {
      boolean finished = false;

     while( !finished )
     { }
     printGoodbye();
  }
  1. What will the following Java statements do? When will printGoodbye()  be executed?
    public void start()
   {
      boolean finished = false;

      while( !finished )
     {
          String input = reader.getInput();
          if(input.startsWith("bye"))
         {
               finished = true;
          }
      }
      printGoodbye();
  }


In BlueJ

Typing bye in the Terminal Window stops execution (from Exercise 1).

  • The start() method will not finish until "bye" is read.
  • If BlueJ seems to have gone on vacation:
    • close BlueJ
    • Open the project again.
  1. Open class SupportSystem.
     
  2. Place a breakpoint at the first executable statement of method start().
    •  boolean finished = false;
       
  3. Call the start() method.
    • Use Step to trace the execution of the method.
       
  4. Determine where your typed response is held when the following is executed?
    • String input = reader.getInput();
    • Type something into Terminal Window; not "bye".
    • Check the Debugger. What is the value of input?
       
  5. Determine the response value:
    • String response = responder.generateResponse();
    • What is the value of response?
       
  6. Trace through "bye" execution using Step.


5.3 Reading class documents

Exercise 3 - Java Documentation

In BlueJ

  1. Click Help in upper-right corner.
  2. Click on Java Class Libraries.
    • A browser window should open to the Sun Java website.
  3. Find help on the String class.
  4. Find help on the startsWith method.
  5. Find help on the equals method.


5.3.2 Using library-class methods

Simple improvements to SupportSystem

Exercise 4 - trim and toLowerCase

In BlueJ

  1. Change SupportSystem method start() to finish when leading, trailing blanks and uppercase characters entered for bye.
  2. Test.
  3. Can the improvement be written another way?


5.3.3 Checking string equality

Testing for "bye" at the start of input, even with our improvements, behaves incorrectly on input such as "Byelection". We will finish execution only on input of "bye" by testing for equality.

Exercise 5 - equals and ==

In your head

  1. '3' == 3?
     
  2. int x = 3;
    x == 3?
     
  3. int x = 3;
    x+1 == 4?
     
  4. String f1 = "Fred";
    String f2 = "Fred";

    f1 == f2?
    f1.equals(f2)?
     
  5. private TicketMachine t1;
    private TicketMachine t2;
    t1 = new TicketMachine(50);
    t2 = new TicketMachine(50);

    t2 == t1?

In BlueJ

  1. Change SupportSystem method start() to finish when input is only "bye" using the equals method.
  2. Test.


5.4 Adding random behavior

Random behavior is observable in games of chance and real-life. Randomness in computer models is produced by generating pseudorandom numbers. True random numbers never recur in the same sequence but pseudorandom numbers eventually do repeat when the generated sequence is completed and begins again. For example, a pseudorandom sequence of number between 1-3 is: 2, 3, 3, 1, 1, 1, 3,  2, 3, 3, 1, 1, 1, 3, 2, 3, 3, 1, 1, 1, 3, 2, 3, 3, 1, 1, 1, 3.


5.4.1 The Random class

The following simulates throwing two dies in a dice game.

 import java.util.Random;

 public class Dice
 {
  private Random generator;
   public Dice()
  {
       generator = new Random();
  }
   public void twoDie()
  {
       System.out.println( oneDie() + " " + oneDie() );
   }
   public int oneDie()
  {
        return generator.nextInt(6)+1;
  }
 }

 

Exercise 6 - Random

In BlueJ

  1. Create a new project named Exercise6.
     
  2. Create a new class named Dice.
    • Open the Dice class.
    • Delete all existing code.
    • Copy and paste the above class into the Dice class source code.
       
  3. Compile and test by calling the methods several times:
    •  oneDie()
    • twoDie()
       
  4. Do the results appear random?
     
  5. Examine oneDie. What does the following do?
    • generator.nextInt(6)+1
       
  6. Examine twoDie. What does the following do?
    • oneDie() + " " + oneDie()

 

Exercise 6.5 - Random

In BlueJ

  1. Add a field named count, an array of integers to Dice class.
    • In the Dice constructor:
      • Assign count to a array of 6 ints.
      • Initialize all 6 count array variables to 0.
         
  2. Add the method throw10000() that throws the die 10000 times and counts the number of 0, 1, 2, 3,4, 5 thrown.
    • For each 10000 throws of the die, use the die number (0-5) as the index of the array variable to increment.
      •  int n = generator.nextInt(6);    
    • The results in the count array should be similar to:
       
      0 1 2 3 4 5
      1684 1648 1665 1699 1643 1661

       

  3. Create a Dice object.
    • Inspect the object and the count field.
    • Call the throw10000() method.
    • Inspect the object and the count field.
    • What is the total of all variables in count?
    • What else can you say about the results?
    • Which number should you bet on?
       
  4. Redo 3 several times. Is there a consistent pattern?
     
  5. Create a Dice object.
    • Inspect the object and the count field.
    • Call the throw10000() method 10 times.
    • Inspect the object and the count field.
    • Is the number of 0's, 1's, etc. about the same or is there a bias?


5.4. Generating random responses

 import java.util.Random;

 public class Dice
 {
  private Random generator;
   public Dice()
  {
       generator = new Random();
  }
   public int oneDie()
  {
        return generator.nextInt(6)+1;
  }
 }

 

Exercise 7 - Random responses

In your head

  • Change oneDie() method to return Strings rather than int: one, two, three, four, five, or six.
     
    • Hint:

      int n = generator.nextInt( 6 )+1
      if ( n == 1 ) return "one"

In BlueJ

  • Use an ArrayList rather than if-statement.
    • Add an ArrayList field named words.
       
    • Add to the Dice constructor:
      • initialize words field to an ArrayList object (i.e.  new ArrayList() ).
      • add "one" at index 0, "two" at index 1, etc.
        • Hint:

          words = new ArrayList()
          words.add("one")                       // "one" is at index 0
           

    • Change oneDice() to return the word corresponding to the index (0="one", 1="two", ...)

              int n = generator.nextInt(6);        // n is 0-5

              return words.get( n );                  // Return object at index n


Responder class with random responses, see project tech-support2.

  public class Responder
 {
 private Random randomGenerator;
 private ArrayList responses;
 public Responder()
 {
     randomGenerator = new Random();
     responses = new ArrayList();
     fillResponses();
 }
  public String generateResponse()
 {
    int index = randomGenerator.nextInt( responses.size() );
    return (String) responses.get(index);
 }
  private void fillResponses()
 {
    responses.add("That sounds odd. Could you describe that problem in more detail?");
    responses.add("No other customer has ever complained about this before. \n" +
                           "What is your system configuration?");
    responses.add("That sounds interesting. Tell me more...");
    responses.add("I need a bit more information on that.");
    responses.add("Have you checked that you do not have a dll conflict?");
    responses.add("That is explained in the manual. Have you read the manual?");
    responses.add("Your description is a bit wishy-washy. Have you got an expert\n" +
                           "there with you who could describe this more precisely?");
    responses.add("That's not a bug, it's a feature!");
    responses.add("Could you elaborate on that?");
 }
 }


5.5 Packages and imports


5.6 Using maps for associations

Examples:

ArrayList is not a map since only the object is stored at a numerical index. Removing an object can change the index of other objects, hence no fixed pairing is defined.

HashMap uses a key rather than an index. The key is mapped to an object. Removing any other object does not change the key-to-object mapping.

     HashMap englishToroman = new HashMap();

     englishToroman.put("one", "I");
     englishToroman.put("two", "II");
     englishToroman.put("three", "III");
     englishToroman.put("four", "IV");
     englishToroman.get("one");

 

The following translates English words for Strings "one" to "six" to Roman "I" to "VI". 

 import java.util.HashMap;

 public class EnglishToRoman
 {
 HashMap englishToroman;
 public EnglishToRoman()
 {
     englishToroman = new HashMap();

     englishToroman.put("one", "I");
     englishToroman.put("two", "II");
     englishToroman.put("three", "III");
     englishToroman.put("four", "IV");
     englishToroman.put("five", "V");
     englishToroman.put("six", "VI");
 }
  public String translate(String english)
 {
      return (String) englishToroman.get(english);
 }
 }

 

Exercise 8 - Mappings

In your head

  1. From the object diagram, are the HashMap keys in any obvious order?
     
  2. What is the result of the following?
    • englishToroman.get("four")
    • englishToroman.get("two")
    • englishToroman.get("english")
       
  3. Is (String) really necessary for:
    • return (String) englishToroman.get(english)

In BlueJ

  1. Create a new project named Exercise8.
     
  2. Create a new class named Mappings.
    • Open the Mappings class.
    • Copy and paste the above EnglishToRoman class into the source code.
    • Change the field name from englishToroman.
    • Modify constructor to:
      • construct a HashMap object (i.e. change the constructor name).
      • map 3 SSNs (social security numbers) as Strings to peoples names.
         
  3. Compile and correct syntax errors.
     
  4. Compile:
    • Test by calling the translate method to map a valid SSN to a name.
    • Test by calling the translate method to map a valid name to a SSN.
    • What happened?
       
  5. Add the same SSN twice to the mapping but with different names.
    • Test by calling the methods to map that SSN to a name.
    • What happened?
       
  6. Use the Help in upper-right corner. A browser window should open to the Sun Java website.
    • Find help on the HashMap class.
    • Find out how to check whether a given key is in a map.

Exercise 8.5 - Mappings

In BlueJ - Create a simple album that maps picture title to an image filename.

  1. Download and run the HW7.exe file to extract the initial project files.
    1. Open the HW7 project.
    2. The class view should appear as at right.
    3. Test by creating a PictureViewer object. Use picture parameter "Fishing.jpg" and delay parameter of 6.
     
  2. Create a new class named myPics.
    • Open the myPics class.
    • Copy and paste the following class into the source code.
       
       import java.util.HashMap;

       public class myPics
       {
           private HashMap titleTofilename;

           public myPics()
           {

           }
      }

       

    • Modify constructor to:
      • construct the HashMap object and assign to the field titleTofilename.
      • map 3 picture titles to filenames in the HashMap as below (remember put):
         
        title filename
        fish fishing.jpg
        chair rocking.jpg
        hangout local.jpg

         

  3. Compile and correct any errors.
     
  4. We can now translate a title to a filename.
    • Modify the translate method from Exercise 8.
       
    •  public String translate(String english)
       {
            return (String) englishToroman.get(english);
       }

       

    • Is return (String) required?
    • Test by translating "chair" title to filename.
       
  5. Add a method to view the image filename:
    1. Create the view method with one String parameter. Nothing is returned.
    2. For now, view the Fishing.jpg image file each time. Recall how to view an image filename Fishing.jpg:
      •  new PictureViewer( "Fishing.jpg", 4);
    3. Test the view method.
       
  6. Modify to view any image filename by changing Fishing.jpg to the parameter name.
     
  7. Modify view to translate the title to the image filename:
    1. Use translate method to translate title to filename.
    2. Test by viewing the title "chair".
    3. Test by viewing the title "IUS". What happened?
       
  8. Use the Help in upper-right corner. A browser window should open to the Sun Java website.
    • Find help on the HashMap class.
    • Find out how to check whether a given key is in a map.
       
  9. Modify view method to only view a title key that is actually in the map.
    • Test by viewing the title "chair".
    • Test by viewing the title "IUS". What happened?

 


5.6.3 Using a map for the TechSupport system

The Responder class with HashMap, responds to a given word in the map by returning an associated string.

  public class Responder
 {
 private HashMap responseMap;
 public Responder()
 {
     randomGenerator = new Random();
     responsesMap = new HashMap();
     fillResponses();
 }
  public String generateResponse(String word)
 {
    return (String) responsesMap.get(word);
 }
  private void fillResponses()
 {
     responseMap.put("crash",
        "Well, it never crashes on our system. It must have something\n" +
        "to do with your system. Tell me more about your configuration.");
    responseMap.put("crashes",
        "Well, it never crashes on our system. It must have something\n" +
        "to do with your system. Tell me more about your configuration.");
    responseMap.put("slow",
        "I think this has to do with your hardware. Upgrading your processor\n" +
        "should solve all performance problems. Have you got a problem with\n" +
        "our software?");
 }
 }


To class SupportSystem start() method modified to generate a response to specific words as input. The only change is to pass the input to the responder object in order to generate a more appropriate response string.

    public void start()
   {
      boolean finished = false;
      printWelcome();

      while(!finished) {
          String input = reader.getInput();
          if(input.startsWith("bye")) {
               finished = true;
          }
          else {
               String response = responder.generateResponse(input);
               System.out.println(response);
          }
      }
      printGoodbye();
  }

 

Exercise 9 - Maps

For the Terminal input of:

"crashes"
"crashs"
 

  1. What is input:
    • String input = reader.getInput();
       
  2. What is the result of:
    • input.startsWith("bye")
    • responder.generateResponse(input);

 

5.10 Writing class documentation


5.10.1 Using javadoc in BlueJ
 

Exercise 10 - Documentation
  1. Use the myPics class from Exercise 8.5.
     
  2. On the BlueJ menu, select Tools | Project Documentation | Regenerate
     
  3. Note the documentation generated.
     
  4. Add the following comments along with your name; documentation must be placed after the import:
    import java.util.HashMap;

    /**
    * This class implements Picture Viewing.
    *
    * @version 1.0
    * @author Your Name
    */

    public class myPics

     

  5. Regenerate the documentation.

 

5.11 Public versus private

Exercise 11 - Public/Private

In BlueJ

  1. Open project chapter05\tech-support1.
     
  2. Open the SupportSystem class.
    • Note private and public methods.
       
  3. Create a SupportSystem object.
    • Which of the methods can be called?

 

5.11.1 Information hiding

The private keyword hides information making it only accessible inside a class. This prevents accidental or purposeful access to class fields, methods and constructors.

Exercise 12 - Public/Private

In your head

  • In the myPics class.
    1. What is public and private?
    2. What do you need to know to view a picture?
    3. Do you need to know that a HashMap class object is one of the fields?
    4. Do you need to know about the translate method to view a picture?
    5. Do you need to know about constructors?

 

5.11.2 Private methods and public fields

 

5.12 Learning about classes from their interfaces

We'll examine the class interfaces in the balls project to understand how to use the classes without understanding how they are implemented.

Exercise 13 - Class interface

In BlueJ

  1. Open the chapter05\balls project.
     
  2. Create a BallDemo object.
    • Call drawdemo method.
    • Call bounce method.
       
  3. In BlueJ menu:
    • Open Tools
    • Project Documentation
    • Regenerate
       
  4. Read Canvas documentation and from it:
    • Create a Canvas object.
    • Make it visible.
    • Draw a circle.
    • Display your name by drawing a text string.
    • Draw a rectangle.
       
  5. Open Canvas and read the code to discover how to set the background color.
    • The Color parameter is defined in the java.awt class, to pass the color red as a parameter use:

      java.awt.Color.red

 

5.13 Class variables and constants

 

5.13.1 The static keyword

 public class Test
 {
    private static int count = 0;
    private           int i = 0;

    public Test()
    {
        count = count + 1;
        i = i + 1;
    }

    public int getCount()
    {
        return count;
    }
 }

After constructor execution:

  • new Test( );
  • new Test( );

 

5.13.2 Constants

Exercise 14 - Constants

In BlueJ

  1. Open a new project named static.
  2. Create a new class named Test.
  3. Copy and paste the above Test class definition.
  4. Create three Test objects.
    • Inspect two objects.
    • Show static fields.
    • What are the values of i and count?
  5. Change:

    private static int count = 0;

    to

    private static final int count = 0;

  • Why the error?

5.14 Summary