Java Reference
In-Depth Information
Code 5.3
continued
The Responder
source code with
random responses
responses.add( "That is explained in the manual. \n" +
"Have you read the manual?" );
responses.add( "Your description is a bit \n" +
"wishy-washy. Have you got an expert \n" +
"there with you who could describe \n" +
"this more precisely?" );
responses.add( "That's not a bug, it's a feature!" );
responses.add( "Could you elaborate on that?" );
}
}
In this version, we have put the code that fills the response list into its own method, named
fillResponses , which is called from the constructor. This ensures that the responses list will
be filled as soon as a Responder object is created, but the source code for filling the list is kept
separate to make the class easier to read and understand.
The most interesting code segment in this class is in the generateResponse method. Leaving
out the comments, it reads
public String generateResponse()
{
int index = randomGenerator.nextInt(responses.size());
return responses.get(index);
}
The first line of code in this method does three things:
It gets the size of the response list by calling its size method.
It generates a random number between 0 (inclusive) and the size (exclusive).
It stores that random number in the local variable index .
If this seems a lot of code for one line, you could also write
int listSize = responses.size();
int index = randomGenerator.nextInt(listSize);
This code is equivalent to the first line above. Which version you prefer, again, depends on
which one you find easier to read.
It is important to note that this code segment will generate a random number in the range
0 to listSize-1 (inclusive). This fits perfectly with the legal indices for an ArrayList .
Remember that the range of indices for an ArrayList of size listSize is 0 to listSize-1 .
Thus, the computed random number gives us a perfect index to randomly access one from the
complete set of the list's elements.
The last line in the method reads
return responses.get(index);
 
Search WWH ::




Custom Search