Lab 4: Javadoc - Department of Computer Science

advertisement
Lab 4: Javadoc
Wile E. Coyote was doing his best to catch the Road Runner. For years he spent countless hours
and most of his family fortune in futile attempts to chase that extremely fast (and extremely
lucky) bird. Wile did not only fail to catch the Road Runner, but also found himself in various
situations where he himself would fall into his own traps. He didn’t mind the pain as much as he
minded the humiliation.
One day Wile realized that in order to outsmart the Road Runner he must be smarter than the
Road Runner. And so, Wile decided to go to San Jose State University, disguised as a foreign
exchange student from Death Valley, CA, and get his degree in Computer Science, assuming
that all the math, physics and programming would make him smarter than the Road Runner, who
seems to know nothing but how to run fast and say “beep beep.”
In his first semester Wile took CS 46A. During the fourth lab Wile was asked by the lab manual
to write a program that prompts the user for a double, finds its absolute value and raises it to the
power of 5 (the double, not the user). Wile spent some time planning his algorithm and
eventually wrote the following program:
/**
This class reads a double number from the user and finds
the value of |number|^5 (absolute value to the power of 5).
@author Wile E. Coyote
@version 1.0
*/
import javax.swing.JOptionPane;
public class Calculate
{
public static void main(String[] args)
{
//getting a number from the user
String input = JOptionPane.showInputDialog(
"Enter a number or press cancel to exit: ");
while(input != null)
{
double number = Double.parseDouble(input);
double answer = number;
// Finding number’s absolute value:
if (answer < 0)
answer = -answer;
double positiveNumber = answer;
// finding answer ^5
for (int i = 0; i < 5 ;i++)
answer = positiveNumber * answer;
// printing result
System.out.println("|" + number + "|^5 = " + answer);
//getting a number from the user
String input = JOptionPane.showInputDialog(
"Enter a number or press cancel to exit: ");
}
System.exit(0);
}
}
Take a look at Wile’s code and find the portion of code where the absolute value is found and
where the number is raised to the 5th power. Note that Wile implemented his program using an
if statement and a for loop. Also, he used an extra variable called positiveNumber.
Wile’s roommate, Duffy Duck, who also took CS 46A with Wile, wrote a similar program:
/**
This class reads a double number from the user and finds
the value of |number|^5 (absolute value to the power of
5). To do that the program uses the abs and the pow
methods from the Math class.
@author Duffy Duck
@version 1.0
*/
import javax.swing.JOptionPane;
public class CalculateBetter
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
"Enter a number or press cancel to exit: ");
while(input != null)
{
double number = Double.parseDouble(input);
double answer = Math.abs(number);
answer = Math.pow(answer, 5.0);
// printing result
System.out.println("|" + number + "|^5 = " +
answer);
String input = JOptionPane.showInputDialog(
"Enter a number or press cancel to exit: ");
//getting a number from the user
String input = JOptionPane.showInputDialog(
"Enter a number or press cancel to exit: ");
}
System.exit(0);
}
}
How did Duffy Duck find the absolute value and the 5th power of the number? Duffy used the
abs and the pow methods from the Math class, thus not needing to use an extra variable. When
Wile saw Duffy’s program he wondered how did Duffy know about these methods and how to
use them. In fact, he wondered, how can anyone know how to use all the available Java
methods?
The answer is simple. No one is expected, nor should they even try, to master the entire Java
libraries. There are so many classes and methods available that it would be practically
impossible to learn them all. However, Java programmers have a tool they can utilize to find
classes and methods they can use in their code, just like Duffy used the two methods from the
Math class.
Open your favorite web browser and go to:
http://java.sun.com/j2se/1.4.1/docs/api/index.html
This is the API specification for the Java 2 Platform. In other words, this is a library containing
all the available packages, classes and methods that are part of the official and standard Java
language. The main frame lists all the various packages and the smaller frame on the bottom left
lists all the classes. Find the Math class and click on it. Now in the main frame, find the
specification for the abs method. Notice that there are several abs methods.
Problem 1: How do these several abs methods differ from one another? List two differences in
a file called abs.txt.
Take a look at the summary of the method. Here we can see the method’s signature – the name
of the method, the parameter we send to it (if any) and the return value (if any). There is also a
short description of the method. Find the method used by Duffy Duck and click on it. Now we
get a more elaborate description of the method, what it does, special cases it handles etc.
This API documentation is very handy and allows us to find classes and methods to use in our
own programs. It also provides us with just enough information to know how to use these
methods and objects of these classes, and all without us worrying about the actual
implementation and code. We don’t really know how these methods are implemented, and we
don’t really care. All we know is that we send a number to the abs method and the return value
is the number’s absolute value. Cool.
Problem 2: Write a Java program to calculate the number of seconds that have passed since the
stroke of midnight in London on New Years Eve, 1970. Your program should not be long, just a
few lines of code. (Hint – don’t try and calculate the result yourself, browse through the Java
API and find some help there…). Save your file as Seconds.java.
So this is why commenting is so important…
Notice that all the documentation is in an HTML format. Now that you know some HTML you could
build such pages for the various classes you design in your homework assignments. Of course,
this could use up a lot of time and energy. Luckily, we have a tool called javadoc, which is
provided as part of the Java Development Kit. And so, if we follow the rules and comment our
code properly, with one line in the DOS command prompt we can generate similar API pages
based on our code. This could be a very useful thing for two reasons: First, that would enable
other people to familiarize themselves with your work, thus enabling them to use it in their own
programs. Second, building such pages is crucial for your getting a good grade in this lab.
In order to generate javadoc pages we first need to worry about proper commenting of our code.
The javadoc tool would look for specific standard structures in our comments and for special
javadoc tags, all beginning with the ‘@’ sign. In fact, we already encountered these tags in lab 2
(@author, @version, @return etc), only then you didn’t really know what they meant and pretty
much copied them from the examples. Let’s look at another class written by Wile E. Coyote as
an example and officially introduce you to the various tags:
/**
This class describes Train objects. A train has a name and
speed in miles per hour (speed must be between 0 and the
constant MAX_SPEED). Train objects will be used to run over
the Road Runner.
@author Wile E. Coyote
@version 1.0
*/
public class Train
{
/**
Constructs a new Train object with speed 0.
@param aName - this Train's name.
*/
public Train(String aName)
{
name = aName;
speed = 0;
}
/**
Increases this Train's speed.
@param moreMPH - by how much to increase this Train's
speed.
@throws IllegalArgumentException if newSpeed is bigger than
MAX_SPEED.
*/
public void accelerate(int moreMPH)
{
checkMaxSpeed(speed + moreMPH);
speed += moreMPH;
}
/**
Decreases this Train’s speed.
@param lessMPH - by how much to decrease this Train's
speed.
@throws IllegalArgumentException if newSpeed is negative.
*/
public void decelerate(int lessMPH)
{
checkMinSpeed(speed - lessMPH);
speed -= lessMPH;
}
/**
Returns this Train's name.
@return this Train's name.
*/
public String getName()
{
return name;
}
/**
Returns this Train's current speed.
@return this Train's current speed.
*/
public int getSpeed()
{
return speed;
}
/**
Returns true if this Train is moving, false if it is idle.
@return true if this Train is moving, false if it is idle.
*/
public boolean isMoving()
{
return (speed != 0);
}
/**
Stops this Train by changing its speed to 0.
*/
public void stop()
{
speed = 0;
}
/**
Returns a String representation of this Train.
@return a String representation of this Train.
*/
public String toString()
{
return "[Train " + name + " is now going at " + speed +
" MPH]";
}
/**
Checks if the value of newSpeed is bigger than MAX_SPEED,
thus illegal.
@param newSpeed - the speed to test.
@throws IllegalArgumentException if newSpeed is bigger than
MAX_SPEED.
*/
private void checkMaxSpeed(int newSpeed)
{
if (newSpeed > MAX_SPEED)
{
throw new IllegalArgumentException(
"can't go faster than " + MAX_SPEED + ".");
}
}
/**
Checks if the value of newSpeed is negative, thus illegal.
@param newSpeed - the speed to test.
@throws IllegalArgumentException if newSpeed is negative.
*/
private void checkMinSpeed(int newSpeed)
{
if (newSpeed <= 0)
{
throw new IllegalArgumentException(
"can't have negative speed.");
}
}
// instance fields
private String name;
private int speed;
private final int MAX_SPEED = 500;
}
As in lab 2, we see how our code begins with a brief description of the class, what it does and
what is the function of an object of this class. This description can be as long and as elaborate as
you think is necessary. Remember, this is a general description, not a detailed one and should
give an overall picture of the class, so only include information you think is important.
After the class description we find two tags:
1. @author Wile E. Coyote – this tag is where you should put your own name. You
wrote the class and you should take credit for it. Also, that way no one can “borrow”
your class and claim it is their idea, though other people should be more then welcome to
use your code.
2. @version 1.0 – here you should put the version number of your class. This is quite
useful for commercial purposes, when you rewrite or update an older class and want to
let people know this is a newer version.
Following the class declaration we see that the constructor and all methods are preceded by a
short description of what the method does. Note that all comment blocks start with a “/**”
which contains two stars. This is important to generate the javadoc later on. Again, the
information you supply here should be part of a general description of what each method does.
Immediately after the method description we have several tags:
1. @param paramName – here we specify the name of the parameter the method receives and
its function in the method. If we have more than one parameter the @param tag should
appear the same amount of times as the number of parameters received. Each parameter
should be described in a separate line.
2. @return – here we specify what our method returns. There is no need to specify the type
we return, since this information is clear from the method’s signature, but it is important
to specify what our return value symbolizes. If the method is declared as void, that is
there is no return value, the @return tag does not need to be included in the comment.
3. @throws exceptionType – if our method throws an exception we will specify the type
of exception involved and the reasons for it to be thrown. If a method throws more than
one exception the @throws tag should appear the same amount of times as the number of
exceptions thrown. If no exception is thrown the @throws tag can be omitted.
These comments are the important ones for generating the javadoc pages. Regular comments
starting with “//”, such as the one just before our instance fields in the Train class, will not be
included in the javadoc pages, though that does not mean you should not include them in your
code. Another important thing to note is the use of the phrase this Train in the comments.
Remember that this code will be used to create various Train objects, each with a different name
and speed. Thus, when we write this Train we mean the implicit parameter – the parameter
that precedes the method call. By the way, if a method is static we use the class name instead of
an implicit parameter, just like Duffy Duck called the pow method by stating Math.pow(answer,
5.0).
One more thing, as you can see, writing a Train class in order to run over the Road Runner did
not really work well for our friend Wile E. Coyote:
Maybe he should come up with a better idea…
Ready or not, here it comes
Ok, while Wile is trying to escape from the train we will go on and generate some javadoc
pages. Copy the Train class into TextPad and create the file Train.java. Save the file in your
working directory (we will assume you are saving your file at J:\Lab4>). Now open the DOS
command prompt and go to that directory. When there, issue the following command:
j:\Lab4> javadoc –version –author Train.java
This is the javadoc command. Note that we added the words –version and –author to our
command line. This enables us to tell the javadoc tool that we are using the @version and the
@author tags, since the javadoc default does not include these tag.
After you typed the command look in your working directory and you should find several HTML
files. Open the file index.html. You should now be looking at a page that is similar in format to
the API pages we saw at the beginning of the lab, only this one describes our Train class. Here
are screen shots of the HTML file showing the class summary, method summary and method
details:
Look over the class documentation. Can you see the class description we wrote? How about the
various method descriptions? Find the place where the @version and the @author tags are used
in the HTML file. Now look at the details of the accelerate method. Can you see where the
@param and @throws tags are used?
Problem 3: Take a closer look at the content of your javadoc page. Does it give details of all
the elements in the Train class? Obviously not, otherwise, why would we ask this question?
Which elements are not included (hint: there are 5 missing elements)? What do these 5 element
have in common? Write you answer is a file called whatsMissing.txt and save it.
Look at the five missing elements. They are all private. javadoc is used to give us information
of how to use a class or method. Private methods and private instance fields can only be used by
the class itself, not by other programs that use that class. And so, as programmers who merely
use objects and methods of the class, we don’t need to know anything about private element of
the class. Hence, javadoc will not include any information about private elements of a class.
However, that does not mean you shouldn’t include comments for private elements in your code.
After all, in 5 years when someone else would need to maintain and update code you wrote your
comments will be quite useful.
Speaking of HTML
Here’s another interesting piece of information – you can imbed HTML tags in your javadoc
pages. First, if you have a long description you can add tags to format your text, like the <P>,
<BR> etc. You can also add links. For example, when you write your name in the @version tag,
you can add an <A> tag with your e-mail address at the HREF attribute (using the mailto: value).
Back to Wile E. Coyote
is a very useful tool. Though you’re not likely to use it as often to generate javadoc
pages for your own code, you are very likely to use the online API documentation to find other
Java classes and methods and use them in your own code (it is possible to download the entire
API to your hard drive, but it is extremely big and available for free online anyway, so why
bother?). However, when you write your code always keep in mind that at some point you may
want to generate javadoc pages for it, so follow the rules and comment your code accordingly.
(plus, the Computer Science department requires you to follow these rules).
javadoc
As for out friend Wile E. Coyote – he decided to go back to some less sophisticated and more
straight forward ways to catch the Road Runner…
Problem 4: In a last attempt to outsmart the Road Runner, Wile E. Coyote builds an elevator
that can take him from hit lookout point forty-two floors up on the top of the cliff, down to the
valley where the Road Runner roams. Look at the following method signatures and write the
proper comments and code for the Elevator class. The method checkFloor needs to check that
the requested floor is between 1 and 42 (inclusive). Feel free to use the Train class for
inspiration. Save your well-commented code in the file Elevator.java.
class Elevator:
Constructor:
public Elevator()
Methods:
public void up(int amount)
public void down(int amount)
public void move(int newFloor)
public int getFloor()
public String toString()
private void checkFloor(int testFloor)
Instance Fields:
private int floor;
private final int MAX_FLOOR = 42;
Problem 5: Generate the proper javadoc pages for the Elevator class.
Lab submissions:
Submit a floppy disk to your lab instructor with the following files Do not submit any .class
files):
1.
2.
3.
4.
5.
abs.txt
Seconds.java
whatsMissing.txt
Elevator.java
All the HTML files that are part of the javadoc pages for the Elevator
class.
Download