Chapter 5
More sophisticated behavior
|
|
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
- User enters question at keyboard (we will see how to do user input).
- TechSupport system responds with useful information. Version 1 has only 1
possible response. Later versions will implement more useful behavior.
| Exercise 1 - SupportSystem class In BlueJ
- Open project chapter05\tech-support1.
- 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 String generateResponse()
{
return "That sounds interesting. Tell
me more...";
} |
|
String comparisions
- "Raymond".startsWith("Ray") - True because "Raymond" starts with
"Ray".
- "Raymond".startsWith("ay") - False because "Raymond" does not
starts with "ay".
- input.startsWith("bye") - True when "bye" is at the beginning of
input String, otherwise false.
- "Raymond".equals("Raymond") - True.
- "Raymond".equals("raymond") - False.
| Exercise 2 - Reading the code
In your head
- What is?
- "RAYMOND".startsWith("Ray")
- "RAYMOND".startsWith("AY")
- "RAY".equals("Ray")
- !"RAY".equals("Ray")
- What will the following Java statements do? Will printGoodbye()
be executed?
public void start()
{
boolean finished = false;
while( !finished )
{ }
printGoodbye();
} |
- 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.
- Open class SupportSystem.
- Place a breakpoint at the first executable statement of method
start().
- boolean finished = false;
- Call the start() method.
- Use Step to trace the execution of the method.
- 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?
- Determine the response value:
- String response = responder.generateResponse();
- What is the value of response?
- Trace through "bye" execution using Step.
|
5.3 Reading class documents
-
| Java standard library documentation - Details all
classes in Java library. |
| Exercise 3 - Java Documentation In BlueJ
- Click Help in upper-right corner.
- Click on Java Class Libraries.
- A browser window should open to the Sun Java website.
- Find help on the String class.
- Find help on the startsWith method.
- Find help on the equals method.
|
5.3.2 Using library-class methods
-
| Immutable objects - An object, that once created,
its state cannot be changed. Recall mutator methods can change an
object's state. |
Simple improvements to SupportSystem
- trim - Trims spaces from front and back of a string. Can allow spaces around "bye" to stop iteration.
- " a b c ".trim() is "a b c"
- (input.trim()).startsWith("bye") trims the blanks and tests that result
starts with "bye"
- toLowerCase - Converts uppercase to lowercase. Can allow "Bye", "BYE", etc. to stop iteration.
- "AbC".toLowerCase() is "abc"
- " AbC ".toLowerCase().trim() is "abc"
- input.trim().toLowerCase().startsWith("bye") trims the blanks, converts
to lowercase and tests that result starts with "bye".
| Exercise 4 - trim and toLowerCase In BlueJ
- Change SupportSystem method start() to finish when
leading, trailing blanks and uppercase characters entered for bye.
- Test.
- 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.
- equals - Returns true when two strings are equal.
- "AbC".equals("AbC") is true.
- "AbC".equals("ABC") is false.
- input.trim().toLowerCase().equals("bye") trims the blanks, converts to
lowercase and tests that result is equal "bye".
- == - Tests for equality of primitive types such as int, double,
boolean, char and also String objects whether the same object is referenced.
- 4 == 3 is false.

- 4 == 4 is true.
- "Fred" == "Fred" is true.
- class Station {
private TicketMachine t1;
private TicketMachine t2;
t1 = new TicketMachine(50);
t2 = t1;
t1 == t2 is true because both reference the same TicketMachine
object.
| Exercise 5 - equals and == In your head
- '3' == 3?
- int x = 3;
x == 3?
- int x = 3;
x+1 == 4?
- String f1 = "Fred";
String f2 = "Fred";
f1 == f2?
f1.equals(f2)?
- private TicketMachine t1;
private TicketMachine t2;
t1 = new TicketMachine(50);
t2 = new TicketMachine(50);
t2 == t1?
In BlueJ
- Change SupportSystem method start() to finish when input
is only "bye" using the equals method.
- 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; - Uses the Java library class Random.
- generator = new Random(); - The object of class Random is
named generator.
- generator.nextInt(6) - Generates the next integer between 0 and 5
inclusive from a pseudorandom sequence.
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
- Create a new project named Exercise6.
- 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.
- Compile and test by calling the methods several times:
- Do the results appear random?
- Examine oneDie. What does the following do?
- Examine twoDie. What does the following do?
- oneDie() + " " + oneDie()
|
| Exercise 6.5 - Random In BlueJ
- 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.
- 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 |
- 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?
- Redo 3 several times. Is there a consistent pattern?
- 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.
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.
- 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.
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
- Packages contain libraries of Java classes not automatically part of the
Java language.
- import class name makes the package of classes
available in a program. For example:
- import java.util.ArrayList
Makes just the ArrayList class available.
- import java.util.*
Makes all classes in the package available.
5.6 Using maps for associations
-
| Map - A collection that associates a fixed pair
consisting of a key and a related value. The key maps to the
value. |
Examples:
- Dictionary associates the word as a key and the definition as the
value.
- Phone book associates the name as a key and the phone number as the
value.
- An MP3 player associates the song title as a key and the sound file as
the value.
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.
- put - The key "one" is defined to map to "I" using put
method
by:
HashMap englishToroman = new
HashMap();
englishToroman.put("one", "I");
englishToroman.put("two", "II");
englishToroman.put("three", "III");
englishToroman.put("four", "IV"); |
- get - The object "one" is mapped to "I" which is retrieved using
get method by:
| 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
{ |
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
- From the object diagram, are the HashMap keys in any obvious order?
- What is the result of the following?
- englishToroman.get("four")
- englishToroman.get("two")
- englishToroman.get("english")
- Is (String) really necessary for:
- return (String) englishToroman.get(english)
In BlueJ
- Create a new project named Exercise8.
- 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.
- Compile and correct syntax errors.
- 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?
- 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?
- 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.
- Download and run the HW7.exe file to extract
the initial project files.
- Open the HW7 project.
- The class view should appear as at right.
- Test by creating a PictureViewer object. Use picture
parameter "Fishing.jpg" and delay parameter of 6.
- 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 |
- Compile and correct any errors.
- 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.
- Add a method to view the image filename:
- Create the view method with one String parameter.
Nothing is returned.
- For now, view the Fishing.jpg image file each time. Recall how to view an image filename
Fishing.jpg:
- new PictureViewer( "Fishing.jpg", 4);
- Test the view method.
- Modify to view any image filename by changing
Fishing.jpg to the parameter name.
- Modify view to translate the title to the image
filename:
- Use translate method to translate title to
filename.
- Test by viewing the title "chair".
- Test by viewing the title "IUS". What happened?
- 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.
- 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.
| 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"
- What is input:
- String input = reader.getInput();
- What is the result of:
- input.startsWith("bye")
- responder.generateResponse(input);
|
5.10 Writing class documentation
-
| Documentation - Should provide enough details that
other programmers do not need to examine the source code. |
5.10.1 Using javadoc in BlueJ
- javadoc - Creates documentation from comments.
Exercise 10 - Documentation
- Use the myPics class from Exercise 8.5.
- On the BlueJ menu, select Tools | Project Documentation |
Regenerate
- Note the documentation generated.
- 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 |
- Regenerate the documentation.
|
5.11 Public versus private
-
Access modifiers - Define the visibility of a
field, constructor or method.
Public - Defines the element accessible
inside the same class or outside the class.
Private - Defines the element accessible
only inside the same class |
| Exercise 11 - Public/Private In BlueJ
- Open project chapter05\tech-support1.
- Open the SupportSystem class.
- Note private and public methods.
- Create a SupportSystem object.
- Which of the methods can be called?
|
5.11.1 Information hiding
-
| Information hiding - Principle that internal class
implementation details should be hidden from outside the class. |
The private keyword hides information making it only accessible
inside a class. This prevents accidental or purposeful access to class fields,
methods and constructors.
-
| Need to know - One should not need to know class
implementation details to use a class. |
-
| Not allowed to know - Does not allow access from
outside the class. |
| Exercise 12 - Public/Private In your head
- In the myPics class.
- What is public and private?
- What do you need to know to view a picture?
- Do you need to know that a HashMap class object is one of
the fields?
- Do you need to know about the translate method to view a
picture?
- Do you need to know
about constructors?
|
5.11.2 Private methods and public fields
- private - methods that are private can only be accessed by other
methods of the same class. This hides the methods from external calls. Methods
not intended for external use should be private.
- public - Fields that are public can be accessed and changed
externally without using
mutator methods. The values of the fields cannot be
controlled, hence the state of the object cannot be controlled.
5.12 Learning about classes from their interfaces
-
| interface - Describes what a class does and how it
is used without examining the implementation. |
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
- Open the chapter05\balls project.
- Create a BallDemo object.
- Call drawdemo method.
- Call bounce method.
- In BlueJ menu:
- Open Tools
- Project Documentation
- Regenerate
- 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.
- 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
-
class or static variable - A field having one copy
used by all objects. Each object has own version of regular (non-static)
field.
instance variable - A field having one copy per object. |
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( );
|
- class variable - A single count variable is accessible by all
Test objects.
- instance variable - Each object has its own variable i.
5.13.2 Constants
-
| final - Defines a constant, a value that cannot
change. |
| Exercise 14 - Constants In BlueJ
- Open a new project named static.
- Create a new class named Test.
- Copy and paste the above Test class definition.
- Create three Test objects.
- Inspect two objects.
- Show static fields.
- What are the values of i and count?
- Change:
private static int count = 0;
to
private static final int count = 0;
|
5.14 Summary