Chapter 5:



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.
| Exercise 1 - TechSupport
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?
|
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 String
generateResponse()
{ return "That
sounds interesting. Tell me more...";
} |
|
String comparisions
- "Edward".startsWith("Ed") - True because
"Edward" starts with "Ed".
- "Edward".startsWith("rd") - False because
"Edward" does not starts with "rd".
- input.startsWith("bye") - True when "bye" is
at the beginning of input String, otherwise false.
- "Edward".equals("Edward") - True.
- "Edward".equals("edward") - False.
| Exercise 2 - Reading the code
In your head
- 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
- 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.
- 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.
- What is your response when the following is
executed?
- String input = reader.getInput();
- Type something into Terminal Window.
- What is the value of input?
- Use Step Into to execute completely:
- String response =
responder.generateResponse();
- What is the value of response?
|
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.
|
5.3.2 Using library-class methods
-
| Immutable objects - An
object, that once created, its state cannot be
changed. |
Improvements to
TechSupport
- trim - 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 - 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 TechSupport 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 whether the same object is
referenced.
- 4 == 3 is false.
- 4 == 4 is true.
- private TicketMachine t1;
private TicketMachine
t2;
t1 = new TicketMachine(50);
t2 = t1;
t1 == t2 is
true because both reference the same TechSupport
object.
| Exercise 5 - equals and ==
In your head
- '3' == 3?
- private TicketMachine t1;
private
TicketMachine t2; t1 = new TicketMachine(50); t2 = new
TicketMachine(50);
t2 == t1?
In BlueJ
- Change TechSupport 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 do repeat eventually.
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 of the 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.
- Copy and paste the above class into the
Dice class source code.
- Compile and test by calling the methods:
- Do the results appear random?
- What does the following do?
|
| Exercise 6.5 - Random
In BlueJ
- 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
- 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
...
- 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.
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.
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.
- put - The key "one" is defined to map to "I"
using put method
by:
HashMap
englishToroman = new HashMap();
englishToroman.put("one", "I"); |
- 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("five");
- englishToroman.get("four");
- 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.
- Modify to map SSN (social security number) as
Strings to peoples names.
- 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?
- 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.
|
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.
| 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"
- What is input:
- String input = reader.getInput();
- What is:
- 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 -
- listNotes - We need a NoteBook
method that prints all notes along with their index numbers to the
terminal window.
Exercise 10 - Documentation
- Open the project Exercise8 and the
Mappings class.
- 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 an English number to Roman numerical
translation. * * @version 1.0 * @author Your
Name */
public class EnglishToRoman
- 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 the TechSupport class.
- Note private and public methods.
- Create a TechSupport 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 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
- 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 ball
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:
- Draw a circle.
- Draw a rectangle.
|
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:
- 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


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