Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
1Elementary Application Editing Techniques in
NetBeans
CS288, Autumn 2005 Lab 001
Purpose
This document will look at how to define simple fields and methods for the Buildings
class. It will also introduce you to basic debugging within NetBeans, and how to use
command line arguments within the code. You have already set up the Building class
within the CS288 Java project using NetBeans before starting this exercise (Lab 000).
To continue with this exercise start NetBeans with the CS288 project open.
Note: In using this document it is possible to paste text directly into NetBeans. That
means when defining new terms in NetBeans their value can be copied directly from
here, which will remove the possibility of mistyping values. 
If you are reading the PDF version of the document, then clicking on the ‘Select’ icon
activates text selection:
Items can be selected and copied in the usual way after choosing this tool.
Setting Up Fields
We will modify the Building class to include some attributes of a physical building,
such as an office or home. To start with we will suppose that we want to record the
owner/tenant of a building together with the street name and number where the
building is physically located.
Right click on Fields for the Building class:
2Click on the Add Field option. When the dialog box appear fill in the values as shown
to create a new field streetName with type String:
Then click OK. Note we have declared access to the field as ‘private’. That means
direct access to the field is forbidden outside of the class itself. The Building class
view should now look like:
3Double clicking on streetName will bring the declaration into the source editor
window:
Next we will add a field for the street number of the Building. This field will be of
type ‘Double’. NOTE, Java has two closely related but DIFFERENT types: 
• double
• Double
The only difference between their names is that one begins with upper case D, the
other with lower case d. The ‘double’ type is a representation of a real number that is
a raw data type, rather than a proper Java class. The  ‘Double’ type is a proper class
that has various methods that can be called as with any Java class. The compiler will
be totally unforgiving if you confuse the two!
As above, add a new field to the Building class. Name the field streetNumber. Give
the new field the type Double. This type is not available on the drop down list of
default types (although watch out as ‘double’ is one of the defaults available). So you
must enter ‘Double’ by typing it in from the keyboard:
4Next add another field, occupantName of type String. At this point NetBeans should
display the class structure something like this:
Setting up Encapsulation Methods
The safe way to modify and access field values is by using methods specifically for
that purpose. We have already declared the fields for this class to be private, which
means there is no way to access them directly from outside of the class. 
5This technique is so common there are templates within NetBeans that can be set-up
from the menu. To protect access to a class field by use of such methods is known as
encapsulation. 
Within the project view double-click on the occupantName field. This will bring the
declaration of the occupantName field into view within the text editor pane of
NetBeans. 
Right click on the declaration within the text editor:
Choose the ‘Encapsulate Fields’ option as shown. A dialog box will now appear that
will let you choose which fields to encapsulate. To save time click on each field so
that all three will be encapsulated at the same time:
6Then click ‘Next’. A Refactoring pane should now open at the bottom of the main
NetBeans IDE:
Click on DoRefactoring. The project view will now have several new method entries:
7Also the source editor will contain templates for the various set and get methods:
Because we are only dealing with a very simple class these methods do little other
than return the values of the fields in question. However, for more complex classes it
may well be the case that the bare value of a field is not returned in full, but rather just
the salient attribute for that field. For example, it may be that a field is itself a
complex class and the get method only returns one aspect of that class.
8Note the use of the keyword ‘this’ in the set methods. Although this is correct Java,
for this example it is redundant. Also it can be somewhat confusing. To clarify the set
methods edit the source code as follows.
Edit the definitions of each of the set methods to change them to the following:
public void setStreetName(String newStreetName) {
        streetName = newStreetName;
    }
public void setStreetNumber(Double newStreetNumber) {
        streetNumber = newStreetNumber;
    }
public void setOccupantName(String newOccupantName) {
        occupantName = newOccupantName;
    }
The above text can be pasted directly into the NetBeans editor to avoid mistyping the
text. Next click on the ‘Clean and Build Main project’ icon. If the changes have been
correctly made the Output pane should look something like this:
Using Command Line Arguments in the Main Method
We will now edit the main method to allow values for an object to be initialised using
the command line arguments. This will allow a Building object to be given initial
values that can change with each invocation of the Java application without having to
recompile the application each time. In later labs you will see how to allow user input
in a friendlier manner, but for now we will have to live with command line options.
Double click on the main method in the project view to bring it into focus in the editor
pane. Create a new Building object to use in the main method by editing the method
to be this:
public static void main(String[] args) {
            Building b1 = new Building();
    }
9Type ‘b1.’ on the next line, don’t forget the period ‘.’. NetBeans will now open up a
dialog box of possible fields and methods that belong to the b1 object that can be
invoked at this point. Scroll down to the setOccupantName method and double click
it.
Next edit the resulting code so that it looks like this:
public static void main(String[] args) {
            Building b1 = new Building();
            b1.setOccupantName(args[0]);
    }
Note that the main method has as its parameter the String array args. The first value
of this array is used as the parameter for the setOccupantName method of object
b1 in the following line.
Repeat the above process (or just paste in the code below) so that the main method
looks like this:
public static void main(String[] args) {
            Building b1 = new Building();
            b1.setOccupantName(args[0]);
            b1.setStreetName(args[1]);
    }
We also want to use one of the command line arguments for the initial value of the
street number of b1. However to do so we must parse the string value into an integer
value. Edit the main method again to become this:
    public static void main(String[] args) {
            Building b1 = new Building();
            b1.setOccupantName(args[0]);
            b1.setStreetName(args[1]);
            
            Double stNum = Double.parseDouble(args[2]);
            b1.setStreetNumber(stNum);
    }
Variable stNum is just a placeholder that makes the code more readable.
We have now modified the main method so that initial values for the building object
b1 will  be read in from the command line arguments.  Next  we can define within
10
NetBeans what command line arguments should be used. Before that to check that
you have correctly made the changes in this section click on the Clean and Build Main
Project icon. Check that the compilation does not report any errors.
To add values for the command line parameters right click CS288 in the project pane.
Choose the properties option. Click on the running project field. 
Add “Mr Jones”, “High Street” and “32” to the arguments field as shown. 
Using the Debugger to check values at run time.
Right click on the b1.setStreetNumber(stNum); line within the main method. Select
the Toggle Breakpoint option from the menu. Click on the Debug Main Project icon. 
11
The Building application will now be run in debug mode. The code will be executed
until it reaches the breakpoint, when execution will stop and we can examine what has
happened to the b1 object so far.
A new pane will appear at the bottom of the NetBeans main window. Click on the
local variables tab and you should see something like this:
Note that stNum has the value 32.0, but this has not yet been assigned to the
streetNumber field. Click on the ‘Step Over’ icon. The local variables will change to
this:
The streetNumber field now also has the value 32.0. Click on the ‘Continue’ icon and
execution will continue until the end of the application.
Standard Output
12
Applications can print directly to standard output to provide a basic but more sensible
way to see values for object fields. Change the main method so that it becomes as
shown:
    public static void main(String[] args) {
            Building b1 = new Building();
            b1.setOccupantName(args[0]);
            b1.setStreetName(args[1]);
            
            Double stNum = Double.parseDouble(args[2]);
            b1.setStreetNumber(stNum);
            
System.out.println("Occupant name is " +
            b1.getOccupantName());
            System.out.println("Street Name is " +
b1.getStreetName());
            System.out.println("Street Number is " + 
b1.getStreetNumber());
    }
Click on the ‘Clean and Build Main Project’ icon. Click on the ‘Run Main Project’
icon. The output window should look like this:
init:
deps-jar:
compile:
run:
Occupant name is Mr Jones
Street Name is High Street
Street Number is 32.0
BUILD SUCCESSFUL (total time: 0 seconds)
The output window is used both for messages from the compiler and the run time
environment, but also to show print statements to standard output.
Summary
You have now added the following fields and methods to the Buildings class: 
• streetName
• streetNumber
• occupantName
Together with encapsulation methods for each field. Also you have added statements
that use command line arguments to initialise fields for an object. Also the application
prints to standard output. Finally you have used the debugger to check that values
were correctly assigned to fields during runtime.