Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CS1699
Intermediate Programming and System Design Using a Mobile Robot
Lab 0: Java Warm-up
In this course, we will be using Symantec Visual Cafe’ 3.0a for Java 1.1.7a.  As an object-
oriented programming language, Java is similar in many ways to C++, so you will be able to start
using it very quickly, and then learn as you go. The Visual Cafe’ Integrated Development
Environment facilitates the construction of GUI’s for your systems, and shares many similarities
with other Visual IDE’s you may have used, such as Visual Basic, Visual C, etc.
This lab consists of a step-by-step illustration of building a tiny, and frankly pretty useless Java
system.  By going through it carefully, though, you will be introduced to many aspects of the
language and the programming environment, and this will make it easier for you to do the later,
more interesting labs on the robots.
***
1. Start Visual Cafe’.  This may take a while, especially if this is the first time Visual Cafe’ has
run on your machine.  When Visual Cafe’ has opened, you should see mostly blank space on
the screen.  If you instead see several open windows, select File/Close Project from the menu
bar.
2. Open a new project by selecting File/New Project.  Create an AWT Applet.  You can set this
to be the default project type by selecting it and then pushing the Set Default button.
Probably the most important feature of Java is that it is designed for portability: you
can design and build a single program that will run on a wide variety of platforms.
This is achieved in a straightforward fashion: when you write Java code, it is
compiled into an intermediate language called Java Byte Code.  Each operating
system then provides its own interpreter for byte code, called a Java Virtual Machine.
There are several main types of  Java projects, of which the most important are
Applets, Applications, and Beans.   Applets are programs that run within a browser,
typically on a client machine.  To ensure security when they are run on clients, there
are restrictions on what Applets can do.  Applications are stand-alone programs that
run on a local machine, and thus don’t have these security restrictions.  A Bean is a
reusable component that complies with a set of standards (“the JavaBean standards”)
to facilitate interoperability across systems and platforms.
AWT is the Java Abstract Window Toolkit.  It provides you with the tools to
construct portable GUIs that can run on any platform, giving you the look and feel of
that particular platform.  A more recent windowing toolkit, which is included in
Visual Cafe’ 3.0, is the Java Foundation Classes (JFC).  The JFC provides what are
called “Swing” components.  Swing components are not yet fully supported by many
browsers, so in this course we’ll stick to the AWT.
23. Next, save your (still empty) project.  Select File/Save As, and save your project to a new
directory on a floppy disk.  Go to your desktop and take a look at the files that were created
in that directory.  Visual Café’ will create several new files.
You’ll see that right now there’s a single .java file, namely, Applet1.java.
4. Return to Visual Cafe’ and take a minute to look at the windows that are open.  At the top
left is a Project Window, which shows you all the items in your project.  There are three tabs
at the bottom of the window that let you look at three views of your project:  its Objects,
Packages, and Files.  Examine each view of your current project.
5. Below the Project Window, you’ll see the Property List.  It lets you view and access the
properties of an object.   There’s currently only one object in your project, Applet1.  Take a
look at its properties.  We’re going to build a simple calculator, so change the name of this
object to Calculator.  If you’d like, you can also change some of the other fields, such as the
background and foreground colors and the font.
6. Now go back to your desktop, and look again at the files in your directory.   You’ll see that
Applet1.java has been changed to Calculator.java.
Visual Cafe’ files have several different extensions.  The most important ones to
know about for now are:
Œ .vep, .vpj, .ve2, and .cdb files contain various kinds of information about your
project, and are used by Visual Café’.  If you double-click a .vep file from your
desktop, the project with which it is associated will be opened.
Œ .java files contain Java source-code
Œ .class files contain Java Byte Code (compiled Java)
A note on terminology: We’ll use the terms object and instance interchangeably, and
we’ll  also use the terms method and function interchangeably.  You should know
these terms from C++.  Another fundamental term we’ll use is package.  If you’ve
programmed in Lisp or some other languages, you’ll know about packages already.
Otherwise, you can think of a package as very similar to a C++ library:  it’s a
collection of related files that are grouped together.
Java has special requirements concerning the naming of files.  These requirements are
intended to make directory and file naming more rational, by associating the names
given to files and directories in the operating system (and even the entire network)
with the names given to objects in a program.  The basic rule is that each class must
be stored in its own file, which has the same name as the class.  There’s a similar rule
for packages: every package must be stored in its own directory (folder), which has
the same name as the package.
37. Make Visual Café’ your active window again.  In addition to the Projects Window and the
Properties Window, there’s a third open window: the Form Designer.  This is where you
create your GUI, by inserting buttons, text fields, etc.  Visual Cafe’ automatically generates
Java code for the GUI you designed.  To see this, right click on the Calculator object in the
Objects tab of the Projects window, and select Edit Source.  A window containing the
automatically generated source code will open.  Take a look at it, just to get a sense of what
it’s like.  In particular, note that it defines a new class, called Calculator, which extends the
Applet1 class.  That is, the Calculator class inherits the contents of the Applet1 class.
8. You’re finally ready to design a GUI for your calculator.  Go back to the Form Designer for
the Calculator object, and add a button and three textfields.   The toolbar near the top of the
screen has tabs for various GUI components.  Using them, you can select the object you
want, and place it on the Form Designer, where it can be then be moved, resized, cut, or
pasted.   Make sure you’ve selected the AWT tab.  You’ll then find a button component at
the right end of the tab bar, and a text field 8th from the right.  After placing these
components on your Form Designer, give them reasonable names: name the button
AddButton, and name the text fields Addend1, Addend2, and Sum.  Also change the label on
AddButton to +.  Finally, adjust the size, shape and color of the objects as you see fit.
9. Again open the source code, and see what’s been added by Visual Cafe’.    Look in particular
at the line 
java.awt.Button AddButton = new java.awt.Button( );  
You can learn how to create a new object in Java from this statement.
410.  Select Project/Execute to execute the project you’ve built so far---but remember it’s just a
GUI that doesn’t do anything yet.  A message window will open up, followed by the
Symantec Just In Time Java compiler.  If there were any syntactic errors, they’d show up in
the message window, but since all you’ve got so far is automatically generated code, you
shouldn’t see any errors.  After compilation is complete, you will see an Applet Viewer: this
plays the role of a browser during development, so you can see what you’ve built so far.
11. Click the close button (X) to close the applet.
12. Now you need to get the program to actually do something, so again activate the source code
window, by selecting it under Windows on the menu bar.    The first thing to do is to declare
a variable of the type Calculator.  Do this by adding the line
Calculator mycalc;
right after the class declaration.  The resulting few lines will look like this:
public class Calculator extends Applet
{
    Calculator mycalc;
public void init( )
. . .
Java separates variable declaration from memory allocation for objects.  If you
specify
java.awt.Button AddButton;
Java will reserve a variable named AddButton of the type java.awt.Button, but it will
not yet allocate space for on object.  Memory will be allocated only when you further
specify
AddButton = new java.awt.Button( );
You can combine declaration and allocation into a single instruction, e.g.,
java.awt.Button AddButton = new java.awt.Button( );
As you’ve probably already figured out, java.awt.Button( ) is the default constructor
function for the java.awt.Button class.  You can have alternative constructor
functions that take parameters, but each constructor function for a class must have a
distinct signature.
You don’t need any destructors.  Java takes care of memory management tasks such
as space reclamation.
One more point: Recall that the Java designers wanted to integrate file and directory
naming with names used for objects in the code itself.  There’s a strict
correspondence between the name of a variable, method, or class, and the place in
which it is stored.  For example,the class java.awt.Button must be defined in the file
Button, which must be in the directory awt, which in turn must be in the directory
java.  The “top” of this directory path is determined by the CLASSPATH
environment variable.  You can modify this (by selecting Project/Options and then
making changes under the Directories tab), but for now you should leave this alone.
513. The init( ) method, as you may have guessed, is the method that is called when the applet is
first loaded into memory.  You’ll want an object---specifically, a Calculator object---to be
created at that time, so you’ll need to add the line 
mycalc = new Calculator( ); 
into the end the init() function, at the end.  The surrounding lines will look like this:
//{{INIT_CONTROLS
setLayout(null);
setSize(426,266);
//}}
mycalc = new Calculator( );
}
//{{DECLARE_CONTROLS
You should always place your code modifications outside the scope of the code that was
automatically generated by Visual Cafe’, i.e., place them outside of the double curly braces:
{{ and }}.  Never mess with the automatically generated code. (“Never” may be too strong,
but at least wait until you’re a Visual Café’ wizard.)
As you’re entering code, notice how Visual Cafe’ helps you.  It includes a code helper, and
unless it was turned off, it will appear after you type “new”, and will show you the possible
completions to your instruction. (If it has been turned off, you can turn it back on under
Tools/Environment Options/editing tab.)
 Visual Café’ also indicates where there may be errors in the code, by coloring the potential
problems red.  Try omitting the empty parameter list, ( ), by instead entering the line
mycalc = new Calculator;
Just be sure to put the parentheses back after you’ve seen what happens.
14. Now you’ll finally write the code to make addition occur when the AddButton is clicked.
Visual Cafe’ will help you again, this time by writing a stub for the new method you want to
create.  At the top of the source code, you’ll see a pull-down menu labeled “Objects”.  Select
the object you want: AddButton.   To the right, you’ll see another pull-down menu labeled
Events/Methods.  Select  the event for which you want to create a method:  MouseClicked.
Look at your source code:  Visual Cafe’ has added an empty AddButton_MouseClicked
method, as well as a new class called SymMouse.  This contains the code that “listens” for
mouse clicks, and invokes the right method to handle them.
615. It’s pretty obvious what our new method, AddButton_MouseClicked, should do.  It should
take the numbers that are entered into each Addend text field, add them together, and show
the sum in the Sum text field.   Before you write the code for this, there’s a little about types
in Java that you should know.
At this point, you may be asking: what about the rule that each class must be stored in
a separate file?  The truth is, we only gave you an abbreviated version of the rule.
The real rule is:
Œ Every file must contain at most one public class, and the file name must be the
same as the name of that public class.
Our current file is thus ok, because only the Calculator class is declared to be public.
The new class, SymMouse, has no modifier before the keyword class, so it’s a default
class, rather than a public one.
As an object-oriented language, Java allows the user to assign various access levels to
variables, methods, and classes.  The simplest ones, which you should know about
now are these:
Œ public:  visible everywhere.
Œ default (no modifier preceding class):  visible only in the variable, method, or
class’s own package.
Œ private:  visible only in the variable, method, or class’s own class.
There are only eight primitive (i.e., built-in) types in Java.  These are:
• boolean
• int, long, byte, short
• double, float
• char
Java specifies the exact length in bytes for each primitive type; you can find out more
about this by looking at any Java text or reference book.
Java handles primitive-type variables differently than it handles real, first-class
objects.   Remember how declaration and allocation are separated for objects?  This
separation does not occur for primitive variables.  The instruction
int i;
will both declare a new variable i and allocate memory for it.
Do not confuse ints with the members of the Integer class.   The Integer class, with a
capital “I”,  is not primitive.   It contains a number of useful methods.
Strings in Java are also non-primitive objects (of the class String).  However, because
they are so frequently used, Java will also perform automatic memory allocation
when you declare an object of type String.
716.  Add the variable declarations that you’ll need for the method AddButton_MouseClicked.
You’ll need three int variables:  one for each of the addends, and one of the sum; and you’ll
need two String variables, because the text that gets input to the text fields will be String
objects.  Your code should look like this:
void AddButton_MouseClicked(java.awt.event.MouseEvent event)
{
int sumval, add1, add2;
String input1, input2;
}
17. The methods for inputting and outputting text to a text field are getText and setText.   You
might have guessed this, but how can you find out more about the definitions of these
methods?  Visual Cafe’ will help you.  Type 
Addend1.getText( );        
in your source code, somewhere inside the AddButton_MouseClicked method.   Note the
syntax used to call a member function (here, getText) for an object of a certain type (here,
Addend1).  Put your mouse over the instruction you just typed and click right.  Then click Go
to Definition.    You’ll see a list of all the definitions for the getText method.  Addend1 is an
AWT TextComponent, so select and double-click that definition from the list.    Now a new
window will open, showing you the definition of the method you just selected (getText),
along with the definitions for all the other members of the selected class
(java.awt.TextComponent).  You can see that the method has an empty input list, and it
returns an object of type String.
Don’t worry too much if this step seems a little mysterious.  Visual Café’ provides you with
lots of different tools for navigating through the Java class hierarchy, and this step is just
meant to give you an illustration of one such tool.  In two more steps, you’ll see another such
tool.
18. Now you know how to write the instructions to read the input from your calculator’s GUI .
Your code should now read:
void AddButton_MouseClicked(java.awt.event.MouseEvent event)
{
    int sumval, add1, add2;
String input1, input2;
input1 = Addend1.getText( );
input2 = Addend2.getText( );
}
19. To add input1 and input2 together, you’re going to need to convert them to integers.  To try
and see how you might do the conversion, select Help/Java API Reference from the menu
bar.   Go to the Index tab, type String, and then select “string” from the index, and finally
select the topic java.lang.String.  This will provide you with lots of documentation about the
String class, including a complete list of its public members and methods.  You may have to
scroll down to see these.  First there’s an index, and then a more complete description of
each method.
8Take a moment to look through the members of the String class.  There’s one that converts
ints to Strings---valueOf(int I)---but unfortunately, you won’t find one that converts a String
to an integer.   Try a different tack.  Look at the Integer class (not int) in the API Reference.
There you’ll find a method called parseInt(String s), which takes String s and parses in into a
int value, which it returns.  That’s just what you need.
20. You can now add parseInt to your code.  But first, little review of some object-oriented
programming fundamentals is in order.
Now modify your code should look like this:
void AddButton_MouseClicked(java.awt.event.MouseEvent event)
{
    int sumval, add1, add2;
  String input1, input2;
    input1 = Addend1.getText( );
          input2 = Addend2.getText( );
          add1 = Integer.parseInt(input1);
   add2 = Integer.parseInt(input2);
}
You’ll see in the definition of parseInt that it is not only a public method, but also a
static one.   A method is static when it relates to the whole class, rather than an
individual object in the class.  (It may be easier to think first about static data
members.  A member is static if there’s only one for the whole class.  So, for
example, if you have a Student class for a database containing university records, you
may want to have  a static member NumberEnrolled.)
When you invoke a non-static method, you invoke it using the name of the object to
which it is related , e.g.
 Addend1.getText( );
But when you invoke a static member, you instead use the name of the class to which
it is related, e.g.,
Integer.parseInt(s);
921. Finally, add the code to actually sum the two integers, and then to display the result.  For the
latter, use the setText(s String) method:
void AddButton_MouseClicked(java.awt.event.MouseEvent event)
{
   int sumval, add1, add2;
  String input1, input2;
    input1 = Addend1.getText( );
          input2 = Addend2.getText( );
          add1 = Integer.parseInt(input1);
   add2 = Integer.parseInt(input2);
   sumval = add1 + add2;
   Sum.setText(String.valueOf(sumval));
}
22. Execute your project.  Congratulations, you’ve built an adding calculator!   More
importantly, you’ve reviewed some of the fundamentals of object-oriented programming,
learned about how those fundamentals are implemented in the Java, and learned the basics of
using Visual Café’ to build Java systems.  Save your work, by selecting File/Save All.  (Be
careful:  there’s a tendency to want to select Save, but that’s not sufficient in general.)    Now
extend your calculator in whatever ways you’d like, to gain additional familiarity with Java
and Visual Café’.
After this, it’s on to the robots!