Tải bản đầy đủ (.pdf) (91 trang)

Java software solutions foundations of program design 4th edition phần 9 ppsx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (371.76 KB, 91 trang )

APPENDIX J an HTML tutorial 731
<CENTER><H1>Students in Action</H1></CENTER>
<HR>
<CENTER><I>Dedicated to helping our local community
by using the volunteer effort of college
students.</I></CENTER>
<HR>
<P>This semester, our planned actions are:</P>
<UL>
<LI> to help a local food drive for flood
victims in the Midwest</LI>
<LI> to visit local adult care centers</LI>
<LI> to teach Java to grade-school students</LI>
</UL>
<P>Our group is active, energetic, and always in
need of donations of equipment, effort, and money.
We are always willing to help staff and plan
community events.</P>
<P>As always, our president (at x222) is eager and
willing to answer questions and hear suggestions on
how we can be more active in our community.</P>
</BODY>
</HTML>
Figure J.7 shows the display of this document. As you can see from Fig. J.7,
although the content of the Web page has not changed since Fig. J.1, the presen-
tation has changed dramatically.
links
The World Wide Web would not be a “web” without links between documents.
A link connects one document to another. The destination of the link can be a
local file or a remote file hosted on another computer. Links are displayed in a
number of different ways, but the most popular and recognizable is underlined


blue text. In most browsers, when you move your pointing device (a mouse or
other device) over a link in a graphical browser, the destination of the link is dis-
played somewhere on the screen. The most popular browsers display the desti-
nation link on the bottom of the display window.
732 APPENDIX J an HTML tutorial
The link tag, <A>, takes one attribute that defines its destination. Inside the
link tags (also known as anchor tags), the URL of a new document is specified.
For example, the following HTML creates two links:
figure J.7 Lists and lines added to the Web page
APPENDIX J an HTML tutorial 733
<A HREF=” Lewis’ Home
Page Link</A>
<A HREF=””>Yahoo Internet Search Link</A>
The text associated with the <A> and </A> tags is what the browser will usually
display as underlined blue text. No checking is done on the validity of the desti-
nation until the user selects (or clicks on) the link. Therefore when one writes a
Web page, all links should be tested (that is, clicked on or exercised). Following
the selection of a link by a user, the browser will attempt to load the contents of
the destination. When a successful connection is made to the destination link
(either as a remote computer or another file on your own computer), the browser
will display the contents of the destination page.
Links are very useful for breaking up a document based on content. Links have
been the driving force behind the popularity of HTML and the Web because they
allow users to read documents located on computers throughout the world. The
following HTML has five example links in it. The first three represent links to
local documents that describe the Students in Action projects and are located on
the same server. The fourth link represents an absolute URL, which can refer to
any document in the Web. The fifth link is a mailto link. This is a special type of
link that allows users to send mail by clicking on the link. In the following case,
the mail would be sent to

<HTML>
<HEAD>
<TITLE>Students in Action</TITLE>
</HEAD>
<BODY>
<HR>
<CENTER><H1>Students in Action</H1></CENTER>
<HR>
<CENTER><I>Dedicated to helping our local community
by using the volunteer effort of college
students.</I></CENTER>
<HR>
<P>This semester, our planned actions are:</P>
<UL>
<LI> to <A HREF=”food.html”>help a local food drive</A>
for flood victims in the Midwest</LI>
<LI> to <A HREF=”adult.html”>visit local adult care
centers</A></LI>
734 APPENDIX J an HTML tutorial
Figure J.8 shows how a browser would display this page.
color and images
Some of the most popular browsers (Netscape Navigator and Microsoft Internet
Explorer) have introduced common extension attributes to the
<BODY> tag to
allow a background color or images for the document to be specified.
Background images or color can dramatically improve the aesthetic appearance
on a color-capable display.
The first attribute is the BGCOLOR attribute. This attribute is used to set the
background color of the entire document. For example, the following will set the
background color to red in an HTML document:

<BODY BGCOLOR=RED>
There are two basic methods for defining a color in HTML. The first, as seen
in the previous example, uses a standard color name. Note that the display of
HTML code is solely under the control of a browser; therefore these names are
not truly standard but are common color names that most browsers support. Be
sure to check all browsers your users may have to see what specific color names
are accepted before choosing an appropriate color. A few de facto standard names
for colors that are accepted by both Netscape’s and Microsoft’s browsers are
black, blue, gray, green, navy, purple, red, yellow, and white. The second method
of choosing a color is to change the color name to an RGB value. An RGB value
is a sequence of three numbers that represents the amount of red, green, and blue
<LI> to <A HREF=”grade.html”>teach Java to grade-
school students</A></LI>
</UL>
<P>Our group is active, energetic, and always in
need of donations of equipment, effort, and money.
We are always willing to help staff and plan
community events.</P>
<P>As always, our <A HREF=”mailto:”>
president</A> (at x222) is eager and willing to answer
questions and hear suggestions on how we can be more
active in our community.</P>
<P>Visit our <A HREF=””>University Home
Page</A>.</P>
</BODY>
</HTML>
APPENDIX J an HTML tutorial 735
that will be used to create the color. The numbers represent the various strength
of the colors involved (0=off, 255=full on). The combination of three values pro-
duce a specific color. The RGB values are represented as three pairs of hex char-

acters preceded by a number sign (#) and surrounded by double quotes. For
figure J.8 Links added to the Students in Action Web page
736 APPENDIX J an HTML tutorial
example, to represent the color in which red is 50, green is 150, and blue is 255,
the <BODY> tag would look like the following:
<BODY BGCOLOR=”#3296FF”>
There are many good shareware programs available on the Internet that will help
you determine the RGB values for a particular color.
In addition to setting the background to a single color, it is also possible to tile
the background with a particular image. Most graphical browsers have imple-
mented an extension to the <BODY> tag that will take a GIF or JPEG image and
repeat it both horizontally and vertically (that is, tile it) to create a background
pattern. Some images can be fairly simple, such as a single-color image. Others
can be more complex, representing a repeating pattern such as bathroom tiles or
a stone mosaic. To use an image as a background, use the BACKGROUND attribute
in the <BODY> tag and follow it with the name of the image file in quotes. For
example, the following piece of HTML code uses the STONE.GIF image as a tiling
background image:
<BODY BACKGROUND=”STONE.GIF”>
Care should be given to the type of image and strength of its colors. Many
times, using an interesting image can make the document’s text difficult to read.
Many pages on the Web have free images that you can copy and use as back-
grounds.
Graphic images can be included in an HTML document in other ways as well.
Most popular browsers can show both GIF and JPEG image formats. To include
an image, use the <IMG> tag. The SRC attribute of the <IMG> tag can be used to
describe the URL of the graphic image file. For example, the following HTML
fragment will include an image called
new.gif:
<IMG SRC=”new.gif”>

The following HTML code is the Students in Action Web page modified to use
an image as a banner that introduces the organization, and a new image to draw
attention to a portion of the page that may have changed recently.
APPENDIX J an HTML tutorial 737
<HTML>
<HEAD>
<TITLE>Students in Action</TITLE>
</HEAD>
<BODY>
<HR>
<CENTER><IMG SRC=”SIA.gif”></CENTER>
<HR>
<CENTER><I>Dedicated to helping our local community
by using the volunteer effort of college
students.</I></CENTER>
<HR>
<P>This semester, our planned actions are:</P>
<UL>
<LI> to <A HREF=”food.html”>help a local food drive</A>
for flood victims in the Midwest</LI>
<LI> to <A HREF=”adult.html”>visit local adult care
centers</A></LI>
<LI> to <A HREF=”grade.html”>teach Java to grade-
school students</A> <IMG SRC=”new.gif”></LI>
</UL>
<P>Our group is active, energetic, and always in
need of donations of equipment, effort, and money.
We are always willing to help staff and plan
community events.</P>
<P>As always, our <A HREF=”mailto:”>

president</A> (at x222) is eager and willing to answer
questions and hear suggestions on how we can be more
active in our community.</P>
<P>Visit our <A HREF=””>University Home
Page</A>.</P>
</BODY>
</HTML>
Figure J.9 shows how a browser would display this page.
738 APPENDIX J an HTML tutorial
figure J.9
Images added to the Students in Action Web page
APPENDIX J an HTML tutorial 739
applets
The <APPLET> tag is used to execute an applet in a document. The <APPLET> tag
has many possible attributes; however, its only required attribute is the CODE
attribute. The CODE attribute names the class file of the applet that should exe-
cute in the document. The browser will load that applet’s class file from the same
URL as the document that contains the <APPLET> tag. For example, to execute
the Marquee applet, the following HTML fragment is used:
<APPLET code=Marquee>
</APPLET>
A browser displaying this HTML code will load the Marquee.class file into
the browser and execute it. Other attributes for the <APPLET> tag include:
◗ HEIGHT—used to define the space in pixels reserved for the display height
of the applet
◗ WIDTH—used to define the space in pixels reserved for the display width of
the applet
◗ CODEBASE—used to define an alternate URL for the location of the class file
In this example, we will reserve 50 pixels for the height and 100 pixels for the
width. In the following code fragment, we also reset the location of the class code

to another site:
<APPLET CODE=Marquee WIDTH=100 HEIGHT=50
CODEBASE=” /></APPLET>
When inserted between the <APPLET> and </APPLET> tags, the <PARAM> tag
allows you to pass parameters to the Java applet at run time. The
<PARAM> tag
has two required attributes that allow it to pass information to the applet pro-
gram. The attributes are
NAME and VALUE. By defining a NAME and VALUE pair, the
applet can use and decipher the information it is passed at run time. The follow-
ing example sends two parameters, a state and city, to the Map applet:
<APPLET CODE=Map WIDTH=100 HEIGHT=5
CODEBASE=” /><PARAM NAME=”state” VALUE=”pennsylvania”>
<PARAM NAME=”city” VALUE=”philadelphia”>
</APPLET>
The following HTML code is the Students in Action Web page with an added
applet that scrolls a message across the document as the page is browsed:
740 APPENDIX J an HTML tutorial
<HTML>
<HEAD>
<TITLE>Students in Action</TITLE>
</HEAD>
<BODY BGCOLOR=”WHITE” TEXT=”BLACK”>
<HR>
<CENTER><IMG SRC=”SIA.gif”></CENTER>
<HR>
<CENTER><I>Dedicated to helping our local community
by using the volunteer effort of college
students.</I></CENTER>
<HR>

<P>This semester, our planned actions are:</P>
<UL>
<LI> to <A HREF=”food.html”>help a local food drive</A>
for flood victims in the Midwest</LI>
<LI> to <A HREF=”adult.html”>visit local adult care
centers</A></LI>
<LI> to <A HREF=”grade.html”>teach Java to grade-
school students</A> <IMG SRC=”new.gif”></LI>
</UL>
<P>Our group is active, energetic, and always in
need of donations of equipment, effort, and money.
We are always willing to help staff and plan
community events.</P>
<P>As always, our <A HREF=”mailto:”>
president</A> (at x222) is eager and willing to answer
questions and hear suggestions on how we can be more
active in our community.</P>
<APPLET CODE=”Marquee.class” WIDTH=500 HEIGHT=50>
<PARAM NAME=text
VALUE=”Join us for our Spring picnic in April!”>
<PARAM NAME=delay VALUE=”100”>
<PARAM NAME=bgcolor VALUE=”255255255”>
<PARAM NAME=fgcolor VALUE=”000000128”>
</APPLET>
<P>Visit our <A HREF=””>University Home
Page</A>.</P>
</BODY>
</HTML>
K
java exceptions and errors

This appendix contains a list of run-time exceptions and errors produced by the
Java language and the classes of the Java standard class library. It is not an
exhaustive list, but it does contain most of the exceptions and errors that arise in
programs within the scope of this text.
Both exceptions and errors indicate that a problem has occurred while a pro-
gram was executing. Exceptions can be caught and handled under programmer
control using the Java try statement. Errors represent more serious problems
and generally should not be caught. Some exceptions and errors indicate the same
type of problem, such as NoSuchMethodException and NoSuchMethodError. In
these cases, the particular situation in which the problem arises determines
whether an exception or an error is thrown.
exceptions
AccessControlException (java.security)
Requested access to a critical system resource is denied.
ArithmeticException (java.lang)
An illegal arithmetic operation was attempted, such as dividing by zero.
ArrayIndexOutOfBoundsException (java.lang)
An index into an array object is out of range.
ArrayStoreException (java.lang)
An attempt was made to assign a value to an array element of an incompatible
type.
AWTException (java.awt)
A general exception indicating that some problem has occurred in a class of
the java.awt package.
BindException (java.net)
A socket could not be bound to a local address and port.
ClassCastException (java.lang)
An attempt was made to cast an object reference to an incompatible type.
ClassNotFoundException (java.lang)
A specific class or interface could not be found.

CloneNotSupportedException (java.lang)
An attempt was made to clone an object instantiated from a class that does not
implement the Cloneable interface.
742 APPENDIX K java exceptions and errors
EmptyStackException (java.util)
An attempt was made to reference an element from an empty stack.
EOFException (java.io)
The end of file has been encountered before normal completion of an input
operation.
Exception (java.lang)
The root of the exception hierarchy.
FileNotFoundException (java.io)
A specified file name could not be found.
GeneralSecurityException (java.security)
The root of all security exceptions.
IllegalAccessException (java.lang)
The currently executing method does not have access to the definition of a
class that it is attempting to load.
IllegalArgumentException (java.lang)
An invalid or inappropriate argument was passed to a method.
IllegalComponentStateException (java.awt)
An operation was attempted on a component that was in an inappropriate
state.
IllegalMonitorStateException (java.lang)
A thread attempted to notify or wait on another thread that is waiting on an
object that it has not locked.
IllegalStateException (java.lang)
A method was invoked from an improper state.
IllegalThreadStateException (java.lang)
An operation was attempted on a thread that was not in an appropriate state

for that operation to succeed.
IndexOutOfBoundsException (java.lang)
An index into an object such as an array, string, or vector was out of range.
The invalid index could be part of a subrange, specified by a start and end
point or a start point and a length.
InstantiationException (java.lang)
A class could not be instantiated using the newInstance method of class
Class because it is abstract, an array, or an interface.
APPENDIX K java exceptions and errors 743
InterruptedException (java.lang)
While one thread was waiting, another thread interrupted it using the interrupt
method of the
Thread class.
InterruptedIOException (java.io)
While one thread was waiting for the completion of an I/O operation, another
thread interrupted it using the interrupt method of the Thread class.
InvalidClassException (java.io)
The serialization run time has detected a problem with a class.
InvalidParameterException (java.security)
An invalid parameter has been passed to a method.
IOException (java.io)
A requested I/O operation could not be completed normally.
JarException (java.util.jar)
A problem occurred while reading from or writing to a JAR file.
MalformedURLException (java.net)
A specified URL does not have an appropriate format or used an unknown
protocol.
NegativeArraySizeException (java.lang)
An attempt was made to instantiate an array that has a negative length.
NoRouteToHostException (java.net)

A path could not be found when attempting to connect a socket to a remote
address and port.
NoSuchElementException (java.util)
An attempt was made to access an element of an empty vector.
NoSuchFieldException (java.lang)
An attempt was made to access a nonexistent field.
NoSuchMethodException (java.lang)
A specified method could not be found.
NullPointerException (java.lang)
A null reference was used where an object reference was needed.
NumberFormatException (java.lang)
An operation was attempted using a number in an illegal format.
ParseException (java.text)
A string could not be parsed according to the specified format.
744 APPENDIX K java exceptions and errors
ProtocolException (java.net)
Some aspect of a network communication protocol was not executed correctly.
RuntimeException (java.lang)
The superclass of all unchecked runtime exceptions.
SecurityException (java.lang)
An operation that violates some kind of security measure was attempted.
SocketException (java.net)
An operation using a socket could not be completed normally.
StringIndexOutOfBoundsException (java.lang)
An index into a String or StringBuffer object is out of range.
TooManyListenersException (java.util)
An event source has registered too many listeners.
UTFDataFormatException (java.io)
An attempt was made to convert a string to or from UTF-8 format, but the
string was too long or the data were not in valid UTF-8 format.

UnknownHostException (java.net)
A specified network host name could not be resolved into a network address.
UnknownServiceException (java.net)
An attempt was made to request a service that the current network connection
does not support.
errors
AbstractMethodError (java.lang)
An attempt was made to invoke an abstract method.
AWTError (java.awt)
A general error indicating that a serious problem has occurred in a class of the
java.awt package.
ClassCircularityError (java.lang)
A circular dependency was found while performing class initialization.
ClassFormatError (java.lang)
The format of the bytecode in a class file is invalid.
Error (java.lang)
The root of the error hierarchy.
APPENDIX K java exceptions and errors 745
ExceptionInInitializerError (java.lang)
An exception has occurred in a static initializer.
IllegalAccessError (java.lang)
An attempt was made to reference a class, method, or variable that was not
accessible.
IncompatibleClassChangeError (java.lang)
An illegal operation was attempted on a class.
InstantiationError (java.lang)
An attempt was made to instantiate an abstract class or an interface.
InternalError (java.lang)
An error occurred in the Java interpreter.
LinkageError (java.lang)

An error occurred while attempting to link classes or resolve dependencies
between classes.
NoClassDefFoundError (java.lang)
The definition of a specified class could not be found.
NoSuchFieldError (java.lang)
A specified field could not be found.
NoSuchMethodError (java.lang)
A specified method could not be found.
OutOfMemoryError (java.lang)
The interpreter has run out of memory and cannot reclaim more through
garbage collection.
StackOverflowError (java.lang)
A stack overflow has occurred in the Java interpreter.
ThreadDeath (java.lang)
The stop method of a thread has caused a thread (but not the interpreter) to
terminate. No error message is printed.
UnknownError (java.lang)
An error has occurred in the Java Virtual Machine (JVM).
UnsatisfiedLinkError (java.lang)
All of the links in a loaded class could not be resolved.
VerifyError (java.lang)
A class failed the bytecode verification procedures.
VirtualMachineError (java.lang)
The superclass of several errors relating to the Java Virtual Machine (JVM).

L
java syntax
This appendix contains syntax diagrams that collectively describe the way in
which Java language elements can be constructed. Rectangles indicate something
that is further defined in another syntax diagram, and ovals indicate a literal

word or character.
Compilation Unit
Package Declaration Import Declaration Type Declaration
Package Declaration
package Name ;
Import Declaration
Type Declaration
Interface Declaration
Class Declaration
import Name Identifier.
*
;
748 APPENDIX L java syntax
Class Declaration
Modifier
class Identifier Class BodyClass Associations
Class Associations
implements Name Listextends Name
Class Body
Class Member
}{
Class Member
Block
Interface Declaration
Class Declaration
Method Declaration
Constructor Declaration
Field Declaration
static
Interface Declaration

Modifier
interface Identifier Interface Body
extends Name List
Interface Body
Interface Member
}{
Interface Member
Interface Declaration
Class Declaration
Method Declaration
Field Declaration
APPENDIX L java syntax 749
Field Declaration
Modifier
Type Variable Declarator
,
;
Variable Declarator
Identifier
= Expression
Array Initializer
Type
Primitive Type
[
Name
]
Modifier
public
private
protected

static
final
abstract
native
synchronized
transient
volatile
Primitive Type
boolean
char
byte
short
int
long
float
double
Array Initializer
Expression
Array Initializer
{ }
,
Name
Identifier
.
Name List
Name
,
750 APPENDIX L java syntax
Method Declaration
Modifier

Parameters
void
Type Identifier Throws Clause Method Body
Parameters
( )
IdentifierType
,
Throws Clause
throws Name List
Method Body
Block
;
Constructor Declaration
Modifier
ParametersIdentifier Throws Clause Constructor Body
Constructor Body
{ }
Block StatementConstructor Invocation
Constructor Invocation
this ;Arguments
Expression
super
Arguments
.
APPENDIX L java syntax 751
Block
{ }
Block Statement
Block Statement
Class Declaration

Statement
Local Variable Declaration ;
Local Variable Declaration
Type Variable Declarator
,
final
Statement
Try Statement
Throw Statement
Return Statement
For Statement
Empty Statement
Break Statement
Do Statement
While Statement
Switch Statement
If Statement
Basic Assignment
Statement Expression
Synchronized Statement
Block
Continue Statement
Labeled Statement
752 APPENDIX L java syntax
If Statement
if ( ) Statement
else Statement
Expression
Switch Statement
switch ( )

Switch Case
Expression { }
Switch Case
case
default
Expression :
:
Block Statement
While Statement
while ( ) StatementExpression
For Statement
for
For Init
;
Expression
;
For Update
)( Statement
For Init
Local Variable Declaration
Statement Expression
,
For Update
Statement Expression
,
Do Statement
do ( )whileStatement ;Expression
APPENDIX L java syntax 753
Return Statement
return

Expression
;
Throw Statement
throw
Expression
;
Synchronized Statement
( Expressionsynchronized ) Block
Empty Statement
;
Break Statement
break
Identifier
;
Continue Statement
continue
Identifier
;
Labeled Statement
Identifier : Statement
Basic Assignment
ExpressionIdentifier = ;
Try Statement
Blocktry catch
finally
Block
Block
( )
Type Indentifier
754 APPENDIX L java syntax

Expression
Instance Expression
Conditional Expression
Bitwise Expression
Logical Expression
Relational Expression
Equality Expression
Arithmetic Expression
Assignment
Primary Expression
Unary Expression
Cast Expression
Primary Expression
this
Primary Suffix
Literal
super . Identifier
( )Expression
Allocation
Name
Primary Suffix
[
]
Expression
Identifier.
.
.
Allocation
.
this

class
Arguments
APPENDIX L java syntax 755
Arguments
( )
Expression
,
Allocation
new Primitive Type
Array Initializer
Name
Array Dimensions
Arguments
Class Body
Array Dimensions
[ ]Expression
[ ]
Statement Expression
Postfix Expression
Prefix Expression
Assignment
;
Assignment
ExpressionExpression =
+=
-=
*=
/=
%=
<<=

>>=
>>>=
&=
^=
|=

×