Chapter 5:


C201 Home Page


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 - TechSupport 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?

5.2.2 Reading the 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 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

  1. Type bye in the Terminal Window to stop execution from Exercise 1.
    • The start() method will not finish until bye is read.
    • If BlueJ seems to have gone on vacation, close BlueJ and Open the project again.
  2. Open class SupportSystem.
  3. Place a breakpoint at the first executable statement of method start().
    •  boolean finished = false;
  4. Call the start() method.
    • Use Step to trace the execution of the method.
  5. What is your response when the following is executed?
    • String input = reader.getInput();
    • Type something into Terminal Window.
    • What is the value of input?
  6. Use Step Into to execute completely:
    • String response = responder.generateResponse();
    • What is the value of response?

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.3.2 Using library-class methods

Improvements to TechSupport

Exercise 4 - trim and toLowerCase

In BlueJ

  1. Change TechSupport 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. private TicketMachine t1;
    private TicketMachine t2;
    t1 = new TicketMachine(50);
    t2 = new TicketMachine(50);

    t2 == t1?

In BlueJ

  1. Change TechSupport 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 do repeat eventually.

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.
    • Copy and paste the above class into the Dice class source code.
  3. Compile and test by calling the methods:
    •  oneDie()
    • twoDie()
  4. Do the results appear random?
  5. What does the following do?
    • generator.nextInt(6)+1

 

Exercise 6.5 - Random

In BlueJ

  1. Add the method throw() that throws the die 100 times and prints the number of 1, 2, 3, etc.
    • Create an array of 6 integers named count.
    • Initialize the array variables to 0.
    • For each throw of the die, use the die number as the index of the array variable to increment.
      •  int n = generator.nextInt(6);
      • count[ n ] = count[ n ] + 1;
    • Print all 6 array variables.

5.4. Generating random responses

Exercise 7 - Random responses

In BlueJ

  1. Change oneDie() method to return Strings: one, two, three, four, five, or six.
     
    • Hint: int n = generator.nextInt( 6 )+1;
              if ( n == 1 ) return "one"
              else ...
       
  2. Change oneDie() method to use an ArrayList rather than if-statement.
     
    • Hint: ArrayList words = new ArrayList();
              words.add("one");                       // "one" is at index 0
                       :
              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 an 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 an object does not change the key-to-object mapping.

     HashMap englishToroman = new HashMap();

     englishToroman.put("one", "I");
     englishToroman.get("one");
 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("five");
    • englishToroman.get("four");
    • 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.
    • Modify to map SSN (social security number) as Strings to peoples names.
  3. Compile:
    • Test by calling the methods to map SSN to a name.
    • Test by calling the methods to map name to a SSN.
    • What happened?
  4. 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?
  5. 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.

5.6.3 Using a map for the TechSupport system

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?");
 }
 }

TechSupport start() method modified to generate a response to specific words as input.

    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:
    • input.startsWith("bye")
    • responder.generateResponse(input);

5.10 Writing class documentation

5.10.1 Using javadoc in BlueJ

Exercise 10 - Documentation
  1. Open the project Exercise8 and the Mappings class.
  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 an English number to Roman numerical translation.
    *
    * @version 1.0
    * @author Your Name
    */

    public class EnglishToRoman
     

  5. Regenerate the documentation.

5.11 Public versus private

Exercise 11 - Public/Private

In BlueJ

  1. Open the TechSupport class.
    • Note private and public methods.
  2. Create a TechSupport 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 TechSupport class.
    • Do you need to know that a Responder class object is one of the fields?
    • When calling TechSupport methods, are you allowed to know about fields or certain methods?
    • When calling TechSupport methods, are you allowed 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 ball 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:
    • Draw a circle.
    • Draw a rectangle.

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:

  • 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

 



C201 Home Page


Please send any comments to: jfdoyle@ius.edu 
Copyright © 2001-2004 by cgranda@ius.edu . All rights reserved.