Chapter 5

Exercise 5.2

The documentation contains the following sections:

  • Overall description of the class: its purpose and how to use it
  • A brief summary of the fields
  • A brief summary of the constructors
  • A brief summary of the methods
  • A detailed description of the fields
  • A detailed description of the constructors
  • A detailed description of the methods

Exercise 5.4

Yes: public boolean endsWith(String suffix)

Exercise 5.5

Yes: public int length()

Exercise 5.7

Signature: public String trim()
Example: String trimmedText = text.trim();
Control characters are treated as whitespace: "...it trims all ASCII control characters as well"

Exercise 5.8

add the line: input = input.trim();
to the start()-method of SupportSystem

Exercise 5.9

add the line: input = input.toLowerCase();
to the start()-method of SupportSystem

Exercise 5.10

boolean

Exercise 5.11

if(input.equals("bye")) {
finished = true;
}

Exercise 5.12

Package: java.util
It generates random numbers
An instance is created by using one of the two constructors:
Random random = Random();
Random random = Random(long seed);
To generate a random integer:
random.nextInt();

Exercise 5.13

Random random = Random();
random.nextInt();

Exercise 5.14
import java.util.Random;


public class RandomTester
{
    private Random random;  // the random number generator

    public RandomTester()
    {
        random = new Random();
    }

    public void printOneRandom()
    {
        System.out.println(random.nextInt());
    }

    public void printMultiRandom(int howMany)
    {
        for(int i=0; i<howMany; i++) {
            printOneRandom();
        }
    }
}
Exercise 5.15
0,1,2,...,99,100
Exercise 5.16
public int throwDice()
{
    return random.nextInt(6) + 1;
}
Exercise 5.17
public String getResponse()
{
    int answer = random.nextInt(3);
    if(answer == 0) {
        return "yes";
    }
    else if(answer == 1) {
        return "no";
    }
    else {
        return "maybe";
    }

}
Exercise 5.18
private ArrayList responses;

public RandomTester()   // constructor
{
    responses = new ArrayList();
    responses.add("yes");
    responses.add("don't know");
    ...
}

public String getResponse()
{
    return responses.get(random.nextInt(responses.size()));
}
Exercise 5.19

See the modified Responder in: Code 5.3 p. 126

Exercise 5.20

When you add more responses these also get shown randomly together with the existing ones.
This is because the length of the list with responses is used when generating the random number.

Exercise 5.21

See http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html and
the rest of section 5.6 in the book.

Exercise 5.22
public class MapTester
{
private HashMap phoneBook = new HashMap();
public MapTester()
{
phoneBook.put("Homer Jay Simpson", "(531) 9392 4587");
phoneBook.put("Charles Montgomery Burns", "(531) 5432 1945");
phoneBook.put("Apu Nahasapeemapetilon", "(531) 4234 4418");
}
public void enterNumber(String name, String number) {
phoneBook.put(name, number);
}
public String lookupNumber(String name) {
return (String) phoneBook.get(name);
}
}
Exercise 5.23

It overrides the existing one.

Exercise 5.24

Both values stay in the map. HashMaps only uses the key to distinguish entries - not the values.

Exercise 5.25

phoneBook.containsKey("Homer Jay Simpson");

Exercise 5.26

It returns null.

Exercise 5.27

phoneBook.size()

Exercise 5.28

See the modified Responder in Code 5.4 p. 124

Exercise 5.29

Similarities between HashSet and ArrayList
Both contains a collection of objects
It is possible to add objects (with the add method)
It is possible to remove objects (with the remove method)
Both has a size()
Both has an iterator() to go through all the elements

Differences:
In a HashSet each object can only appear once in the set (because it is a Set). In a ArrayList an Object can appear multiple times.
An ArrayList is ordered a HashSet is not ordered.

Exercise 5.30

You can use regular expression to define how a string should be split. Some documentation on regular expressions in Java: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html#sum

Exercise 5.31

String[] words = s.split("[ \t]");

Exercise 5.32

Using a HashSet guaranties that there are no duplicate elements, but it does not keep the order of the words.

Exercise 5.33

It creates empty strings - which was probably not the intention. to fix it we could do this:

String[] words = s.split("[ \t]+");

Exercise 5.35

See the modified start() method of SupportSystem in: Code 5.6 p. 124
and the modified generateResponses() in Responder in: Code 5.7 p. 124

Exercise 5.37

The modifications needed to the Responder class in the project tech-support-complete:

Add a new field:

    private HashMap synonymMap;

Initialise it in the constructor:

    synonymMap = new HashMap();

Add this to the generateResponse method right after the if-block:

    else {
        //check if it is a synonym
        Object synonym = synonymMap.get(word);
        if(synonym != null) {
            return (String) responseMap.get(synonym);
        }
    }

To create an example replace the responseMap.put("crashes","Well....); with:
synonymMap.put("crashes", "crash");


Exercise 5.37

The modifications needed to the Responder class in the project tech-support-complete:

Add a new field:

    private HashMap synonymMap;

Initialise it in the constructor:

    synonymMap = new HashMap();

Add this to the generateResponse method right after the if-block:

    else {
        //check if it is a synonym
        Object synonym = synonymMap.get(word);
        if(synonym != null) {
            return (String) responseMap.get(synonym);
        }
    }

To create an example replace the responseMap.put("crashes","Well....); with:
synonymMap.put("crashes", "crash");

Exercise 5.41

Keyword examples:

@author
@version
@param
@return

These keywords get special attention so they stand out in the documentation.

Exercise 5.45

You create canvas by calling one of the three constructors.

You make it visible by calling the method: setVisible(true);

You draw a line with the method: drawLine(int x1, int y1, int x2, int y2)

You erase something with one of four different methods:
erase()
eraseCircle(int xPos, int yPos, int diameter)
eraseRectangle(int xPos, int yPos, int width, int height)
erase(Shape shape)

The method draw only draws the outline of a shape, whereas the fill method fills the internal of the shape with a color.

wait(int milliseconds) waits for a specified number of milliseconds before finishing.

Exercise 5.47+5.48

    public void drawFrame() {
int borderSize = 20;
Dimension size = myCanvas.getSize();
Rectangle r = new Rectangle(borderSize, borderSize, (int) size.getWidth() - 2*borderSize, (int) size.getHeight() - 2*borderSize);
myCanvas.draw(r);
}

Exercise 5.49

    public void bounce(int numberOfBalls)
{
int ground = 400; // position of the ground line
myCanvas.setVisible(true);
// draw the ground
myCanvas.drawLine(50, ground, 550, ground);
// create and show the balls
HashSet balls = new HashSet();
for(int i=0; i<numberOfBalls; i++) {
BouncingBall ball = new BouncingBall(50+32*i, 50, 16, Color.blue, ground, myCanvas);
balls.add(ball);
ball.draw();
}
// make them bounce
boolean finished = false;
while(!finished) {
myCanvas.wait(50); // small delay
Iterator it = balls.iterator();
while(it.hasNext()) {
BouncingBall ball = (BouncingBall) it.next();
ball.move();
// stop once ball has travelled a certain distance on x axis
if(ball.getXPosition() >= 550 + 32*numberOfBalls) {
finished = true;
}
}
}
Iterator it = balls.iterator();
while(it.hasNext()) {
BouncingBall ball = (BouncingBall) it.next();
ball.erase();
}
}

Exercise 5.50

HashSet is most suitable, because it guaranties that we only have one of each ball in the collection. The HashMap could be used for this asa well, but we do not need a map, so it would be a bad choice.

Exercise 5.51

        // create and show the balls
Random random = new Random();
HashSet balls = new HashSet();
for(int i=0; i<numberOfBalls; i++) {
Dimension size = myCanvas.getSize();
int x = random.nextInt((int) size.getWidth());
int y = random.nextInt((int) size.getHeight());
BouncingBall ball = new BouncingBall(x, y, 16, Color.blue, ground, myCanvas);
balls.add(ball);
ball.draw();
}

Exercise 5.52+5.53

Download: balls-inabox.zip

Exercise 5.55

public class NameGenerator
{
public String generatorStarWarsName(String firstName, String lastName, String mothersMaidenName, String cityOfBirth) {
String swFirstName = lastName.substring(0,3) + firstName.substring(0,2);
String swLastName = mothersMaidenName.substring(0,2) + cityOfBirth.substring(0,3);
return swFirstName + " " + swLastName;
}
}

Exercise 5.56

Strings are immutable and therefore can not be changed. The method that is called does not change the instance 's' but returns a new object with the string in upper case. The correct way to do it is:

String upperCaseS = s.toUpperCase();

Exercise 5.57

The variable a and b are contains values. When these values are passed as arguments to the method, the values get copied into the variables i1 and i2. In the method, we then swap the values of i1 and i2. This has no effect outside the method as i1 and i2 are local variables in the method. After calling the method the variables a and b will still contain the same values as before the method call.