Transcript PowerPoint

BlueJ Chapter 5
More sophisticated behavior:
Library classes and documentation
Java constructs to be discussed in
this chapter:
String
ArrayList
Random
HashMap
HashSet
Iterator
String Tokenizer
Static
final
1. Review

Arraylist

Useful class from the Java library


store an arbitrary number of objects
Knowing how to use the libraries is essential
to becoming an advanced Java programmer
Too big to memorize, thousands of classes
 Learn how to read the API
 HOW it’s implemented doesn’t matter
 ALL is well documented so others can use it

This chapter’s project




A technical support system
DodgySoft software company
Decided to get rid of people answering
phones for tech support and replace them
with an online support system.
The program holds a dialog with the user,
responding to questions.
Prototype tech-support1
(the simplified version)
Support System
Input Reader
Responder
Developing the system



The prototype support system starts out
very dumb.
Always gives the same response
First understand how it works, then
improve upon it.
2. Refer to the API



One method used in the start method of the
SupportSystem class is startsWith
Find documentation for the String class for a
description of how the method works
(Appendix F of the BlueJ book tells how to set up BlueJ to access a local
copy of the API to run faster, can we do this?
3. Interface vs. Implementation




Interface = describes what a class does and how
it can be used
Please note: the word interface is also used a number of different ways in
Java, like the I in GUI, or the interface type of class definition.
Implementation = complete source code to
define a class
If an interface is well written you don’t need to
see the implementation.
4. String equality

Remember, if Word is a String


(Word = = “bye”) is true if the String Word
and the String “bye” occupy the same
memory location
Word.equals(“bye”) is true if the 2 strings
have the same content.
Improving the system




First improvement:
Vary the responses
Start with random responses
unrelated to user input
Create an ArrayList of
possible string responses
5. Random numbers







import java.util.random;
// create an instance of the Random class
Random randGen;
randGen = new Random();
int index –=randGen.nextInt();
System.out.println(index);
Note: Only create one instance of Random and store it within a
class definition. Don’t create a new Random instance every time you
want a new number or it won’t be very random!
Range of random numbers


Random numbers generated are
>= -2,147,483,648 and <= 2,147,483,647
nextInt(n) generates a number from 0
(inclusive) to n (exclusive)
Add random to Responder class






Import java.util.Random
Declare a field of type Random
Declare a field of type ArrayList
Create the Random and ArrayList objects
Fill the ArrayList with some responses
Select and return a random phrase when
generateResponse is called.
6. Review: ArrayLists









// import the package to use
import java.util.ArrayList;
// create a list
ArrayList<String> myList = new ArrayList<String>();
// the size method returns the number of elements in
the list
int size = myList.size();
// the get method returns an element at an index
// you must cast to the type of result you want
String nthAnswer = myList.get(n); // no need to cast
Which is easier to read?





int index =
randomGenerator.nextInt(responses.size());
return responses.get(index);
int listSize = responses.size();
int index = randomGenerator.nextInt(listSize);
return responses.get(index);
7. importing packages

we could just import java.util.*;

better to specify which classes are used
import java.util.Random;
 import java.util.ArrayList:


all classes in java.lang are automatically
imported.

these are the most used classes like String
and System
stop here


You’ve finished the notes for part 1
Do the part 1 exercises.
8. Maps

A collection that stores key/value pairs.
Values can be looked up using the key.

Example: phonebook





key = name
value = phone number
look up a name to get a phone number
does not use an index (position of the entry in
the book) to find info, uses alphabetical order of
keys
9. HashMap

a special kind of map.








put inserts an entry into the map
get retrieves a value for a given key
HashMap phoneBook = new HashMap();
// add numbers to book
phoneBook.put(“Li Wei”, “(410) 335-1234”);
phoneBook.put(“Ann Day”, “(301) 555-1212”);
// look up a number
String s = (String) phoneBook.get(“Li Wei”);
Improving tech support

map responses to key words
If they say:
Respond:
slow
Upgrading your hardware should solve
performance problems
bug
Our software engineers are working on the
problem right now.
expensive
Our cost is very competitive, Have you really
noticed our features?
Anything else
Otherwise, generate a random response
to start with, just use single key words
Goal for tech-support

User enters complete sentences


input will not be stored as a single string, but
a set of strings containing each word in the
question
Matching responses are selected if any
keywords are recognized in the question.

the set of strings (words in the question) is
sent to the responder to check every word
and generate a response.
10. Set

a collection that stores each individual
element



no specific order
no repetition of elements
must be able to:


add elements
retrieve elements
11. Java collections
General collection type
Construct used
List
ArrayList
Keeps things in order
Map
HashMap
Key to value connection
Set
Unique elements in no order
HashSet
12. Iterator






an object that allows you to iterate (travel) over
all elements of a collection
import java.util.Iterator;
hasNext method returns true/false
next method gets the next object
good for accessing collections that don’t have an
index
it keeps track and visits every element.
example of an iterator





always starts at the beginning and moves
to the end
in an ArrayList:
ArrayList myList = new ArrayList();
Iterator it = myList.iterator();
while(it.hasNext()){


}
System.out.println(it.next());
13.Using sets






import java.util.HashSet;
import java.util.Iterator;
add words from the input into the set
HashSet myset = new HashSet();
mySet.add(word1);
mySet.add(word2); // how to get the words?
14. Tokenizing strings







StringTokenizer class
like an iterator
String input = readInputLine();
HashSet words = new HashSet();
StringTokenizer tk = new StringTokenizer(input);
while (tk.hasMoreTokens())
words.add(tk.nextToken());
Finishing tech support

When changing the input to produce a set of
words instead of a single string:




must also adjust SupportSystem and Responder
classes
the result of the getInput method is now a HashSet
the parameter into generateResponse is now a
HashSet
if no words in the set are recognized, generate a
random response.
Documentation




A serious problem in real-world projects
A commercial application may have
hundreds of thousands of lines of code in
thousands of classes
Nobody should have to read your actual
code to understand how it works.
The documentation should explain
everything.
15. javadoc in BlueJ


Generate documentation function in main
menu
Interface view option in editor shows a
preview of the documentation for a single
class.
class documentation

should include





class name
overall purpose
version number
author’s name
documentation for each constructor and
method
documentation for each constructor
and method

should include:







name of method
return type
parameter names and types
description of purpose of method
description of each parameter
description of value returned.
Additionally a Read Me file is usually included in
each project.
16. javadoc comments

/**

this is a javadoc comment

*/

key symbols starting with @ are recognized
@version
@author
@param
@return
17. Good programming practices



To ensure better modularization of an
application, internal detail of a class’s
implementation should be hidden from other
classes. This is information hiding.
If changes in one part of a program do not
make it necessary to also make changes in
another part of the program it is weak coupling
or loose coupling.
This is good because it makes programs easier
to maintain and upgrade.
18. Public vs. private

Access modifiers


define the visibility of a field, constructor or
method.
things marked private are within the
implementation and don’t need
documentation externally. (like javadoc)
stop here


you’ve finished the notes for part 2
do the exercises before continuing to the
ball project at the end of the chapter
Ball project
Ball Demo
2 ways to produce graphical output on canvas
Bouncing Ball
behavior of a bouncing ball
Canvas
Provides a window to draw on
Altering the Ball Demo



Good practice to study these concepts
The Canvas class should not need any
modification
A canvas can be used by creating an
instance and making it visible using the
setVisible method.
19. Class variables and constants

static variables exist one per CLASS. not one for
each instance of the class.





// in bouncingBall
private static final int gravity = 3;
private int xPosition;
private int YPosition;
If 3 instances of Bouncing Balls are created



there will be one gravity variable
3 xPositions and 3 yPositions
each ball has an individual x and y position, but all
have the same gravity.
Constants

private final int size = 10;

must be initialized when declared.


are usually class variables
private static final int size = 10;
Summary



You should be able to read and write class
library descriptions
Know essential classes from the library
Use javadoc for standardized
documentation
20. Vocabulary







interface
implementation
map
set
javadoc
access modifier
information hiding





coupling
class variable
static
constant
final