Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Introduction to Java and software design
Nội dung xem thử
Mô tả chi tiết
JONES AND BARTLET T COMPUTER SCIENCE
TEAMFLY
Team-Fly®
SWING UPDATE
Nell Dale
University of Texas, Austin
Chip Weems
University of Massachusetts, Amherst
Mark Headington
University of Wisconsin–La Crosse
INTRODUCTION to
java Software and
Design
TM
Copyright © 2002, 2001 by Jones and Bartlett Publishers, Inc.
All rights reserved. No part of the material protected by this copyright notice may be reproduced or utilized
in any form, electronic or mechanical, including photocopying, recording, or any information storage or
retrieval system, without written permission from the copyright owner.
ISBN: 0-7637-2030-5
This text (ISBN 0-7637-2030-5 © 2002) represents an update of the original © 2001 edition (ISBN 0-7637-
1064-4)
Library of Congress Cataloging-in-Publication Data
Dale, Nell B.
Introduction to Java and software design : swing update / Nell Dale, Chip Weems, Mark Headington.
p. cm.
ISBN 0-7637-2030-5
1. Java (Computer program language) 2. Computer software—Development. I. Weems,
Chip. II. Headington, Mark R. III. Title.
QA76.73.J38 D343 2001
005.13'3—dc21 2001038230
Chief Executive Officer: Clayton Jones
Chief Operating Officer: Don W. Jones, Jr.
V.P., Managing Editor: Judith H. Hauck
V.P., Design and Production: Anne Spencer
V.P., Manufacturing and Inventory Control: Therese Bräuer
Senior Acquisitions Editor: Michael Stranz
Development and Product Manager: Amy Rose
Production Assistant: Tara McCormick
Editorial Assistant: Amanda Green
Cover Design: Kristin E. Ohlin
Project Coordination: Trillium Project Management
Composition: Northeast Compositors, Inc.
Text Design: Anne Spencer
Printing and Binding: Courier Westford
Cover printing: John Pow Company, Inc.
This book was typeset in QuarkXPress 4.1 on a Macintosh G4. The font families used were Rotis Sans Serif,
Rotis Serif, and Prestige Elite. The second printing was printed on 45 lb. Utopia Book Matte.
Printed in the United States of America
04 03 02 01 00 10 9 8 7 6 5 4 3 2 1
World Headquarters
Jones and Bartlett Publishers
40 Tall Pine Drive
Sudbury, MA 01776
978-443-5000
www.jbpub.com
Jones and Bartlett Publishers
Canada
2406 Nikanna Road
Mississauga, ON L5C 2W6
CANADA
Jones and Bartlett Publishers
International
Barb House, Barb Mews
London W6 7PA
UK
DaleJVTTL 7/12/01 9:04 AM Page ii
To Al, my husband and best friend, and to our children and
our children’s children.
N.D.
To Lisa, Charlie, and Abby with love.
C.W.
To Professor John Dyer-Bennet, with great respect.
M.H.
To quote Mephistopheles, one of the chief devils, and tempter of Faust,
…My friend, I shall be pedagogic,
And say you ought to start with Logic…
…Days will be spent to let you know
That what you once did at one blow,
Like eating and drinking so easy and free,
Can only be done with One, Two, Three.
Yet the web of thought has no such creases
And is more like a weaver’s masterpieces;
One step, a thousand threads arise,
Hither and thither shoots each shuttle,
The threads flow on, unseen and subtle,
Each blow effects a thousand ties.
The philosopher comes with analysis
And proves it had to be like this;
The first was so, the second so,
And hence the third and fourth was so,
And were not the first and second here,
Then the third and fourth could never appear.
That is what all the students believe,
But they have never learned to weave.
As you study this book, do not let the logic of algorithms bind your
imagination, but rather make it your tool for weaving masterpieces of
thought.
J. W. von Goeth, Faust, Walter Kaufman trans., New York, 1963, 199.
I
ntroduction to Java and Software Design represents a significant transition in the
development of the Dale series, with much that is new. This book has been developed from the ground up to be a Java text. It is not a “Java translation” of our
previous texts. However, we have retained our familiar easy-to-read style and clear
approach to introducing new topics. The chapters retain the same overall organization with each chapter containing a full problem-solving case study, testing and
debugging hints, summary, and five types of end-of-chapter exercises. Also, some
topics—such as problem solving—are independent of the programming language and
thus contain familiar discussions.
The text uses real Java I/O classes rather than ones we supply. We have seen
many introductory programming texts that introduce either C- or Pascal-like command-line I/O classes or simplified windowing classes that automatically handle
events. However, our view is that event-driven I/O is the dominant model not only in
Java but in the modern world of programming in general. Students come to our
classes already familiar with event-driven interfaces and expect to learn how to write
programs that have them.
Event handling is now a fundamental control structure and must be treated that
way from the start. We therefore introduce event handling even before branching
and looping. On the other hand, it is easy for students to be overwhelmed by the
sheer number and complexity of Java I/O classes. We have taken great care to select
a tiny but sufficient subset of the library to illustrate all of the fundamental concepts.
The result is that when students are finished with the course, they can write real Java
programs without being dependent on a text-supplied library. They also have developed the ability to extend their knowledge of I/O classes to include the many
optional features that are available.
There is some confusion, which we would like to address, about what the term
“Java 2” refers to. Java 2 refers to the second version of the Sun Java Software
Development Kit (compilers, debuggers, and other tools). We do not cover these specific tools, as they are often hidden inside of an integrated development environment, and there are too many different environments to cover them all at a useful
level of detail. It was in version 1.2 that the Java class library was heavily extended
with new classes such as Swing. Other than Swing and the comparable interface, most
of the new classes are well beyond the introductory computer science curriculum. The
remaining classes that might be presented at this level are unnecessary for covering the
curriculum. They are bells and whistles that may be interesting in their own right, but
omitting them has no impact on learning the fundamentals of problem solving and software design. The Java language itself has not changed since version 1.1. Thus, the Java
that students learn from this text is fully compatible with Java 2, as well as with version
1.3 of the language.
In this book we consciously chose the AWT library over Swing for pragmatic reasons. At this point, Swing is not available on all platforms, and our experience has been
that some Swing implementations aren’t stable or are inconsistent with others. These are
the kinds of problems that greatly trouble beginners, so we’ve chosen to avoid them by
using the older, more reliable AWT package in this first edition. In addition, at this level
the programming differences between AWT and Swing are quite trivial. For those students and instructors who would like to experiment with Swing, Appendix H describes
how to convert our AWT programs to Swing, and provides as an example a Swing version of the case study program from Chapter 6.
All of the programs In this book have been tested with Symantec Café® and
Metrowerks CodeWarrior®. The program code is available for download from the Jones
and Bartlett web site at www.jbpub.com/disks.
Chapter Coverage
Chapter 1 begins with basic definitions, computer concepts, problem-solving techniques,
ethical issues, and a case study. We introduce objects from the very beginning, with
their definition in this first chapter and the consistent use of object-oriented terminology.
In Chapter 2 we examine the String class and aspects of its interface. Through the
next several chapters, we introduce new library classes and point out their design features. We also tread carefully through the process of declaring a reference variable,
instantiating an object, assigning it to the variable, and using the object. These are difficult but essential concepts for beginners to grasp. Our goal is for students to gradually
develop a complete and deep understanding of what an object is, how it works, and
what makes its interface well-designed. Then, by Chapters 7 and 8, students are ready to
build significant and realistic classes.
Chapter 2 further covers sequential control flow, and simple output to system.out.
This gets students off to a quick start with a working program and past the mechanics
of program entry and execution. Then, in Chapter 3 we switch to using the Frame class
and a Label for output. Simple event handling is then introduced for a WindowClosing
event. The WindowClosing event is conceptually simpler than others because it doesn’t
need to be registered. Its handler can be written with a simple syntactic template that
uses Java’s anonymous inner-class mechanism to avoid becoming bogged down in general class syntax at this early stage.
In Chapter 4, we turn to the numeric types and expression syntax. We cover type
conversions, precedence rules, the use of numeric types, and additional methods that
vi | Preface
can be applied to String objects. We also reinforce the distinction between the reference
and primitive types in this chapter. Students gain further experience with Frame output
and event handling in this chapter.
With Chapter 5, we take the next step in event handling by introducing the essential elements of an input dialog. Students learn how to use a TextField for data input
and a Button to signal when the field is ready. The Button class is the first event source
they see that must be registered. The concepts of an event source, an action listener, and
an event handler are covered in the simplest context possible. Together, these constructs
enable the students to implement a program with an event loop for reading a series of
inputs. One of the key pedagogical differences in moving to event-driven I/O is that the
looping control structure isn’t required, as it would be in a command-line I/O environment.
Along the way, students are introduced to the syntax for a specific user-defined
class and method that conforms to the ActionListener interface. This experience with the
syntax, though limited, simplifies its formal introduction in Chapter 7. We also examine
the conversion of strings to numeric values. The chapter closes with a discussion of
object-oriented design that introduces the CRC card (Classes, Responsibilities, and Collaborators) as a mechanism for organizing an object oriented design.
The primary goal of Chapter 6 is to introduce branching and the boolean type. But
the motivation for its use, in the end, is for students to be able to handle events from
multiple sources in a single event handler. Students then have learned all of the basic
user interface elements necessary to write a wide range of interactive programs.
Chapters 7 and 8 are the heart of the text. In these chapters we bring together all of
the informal discussion of classes and objects to formally introduce the mechanisms for
defining new classes, methods, and derived classes. Students learn how to read the documentation for a class hierarchy and how to determine the inherited members of a class.
They also see how the classes are related through Java’s scope rules. Package syntax is
introduced so that multifile programs can be written and user-defined classes can be
created and imported to other code. The key object-oriented concepts of encapsulation,
inheritance, and polymorphism are treated thoroughly, and their use is demonstrated in
the case studies.
Users who are familiar with procedural languages may wonder, at this point, “What
happened to looping?” The answer is that event driven I/O has permitted us to postpone
it to Chapter 9, where it naturally fits with file I/O and prepares students for the upcoming chapters on arrays. As always, we cover the basic concepts of looping using only
the while loop. Object-oriented languages haven’t changed the basic fact that beginners
have to make conceptual leaps to understand looping. Because there is more syntax to
learn in an object-oriented language, it is tempting to relegate all those “old-fashioned”
control structures to a single chapter and just breeze by them as if they are suddenly
made easier in the presence of the additional complexity.
We find that students are still well-served by a careful study of the basic programming elements. We focus on how loops are used in algorithms while introducing only
the minimum syntax necessary to illustrate the concepts. In that way, students don’t
develop the misperception that the different forms of control structures are bound to the
different syntactic structures in a language. This approach also avoids the situation that
we commonly see in which a student is focused on their confusion over choosing
Preface | vii
among different looping statements when they are really still unsure of the underlying
algorithmic mechanism that they wish to express. For those instructors who feel
strongly that they prefer to show students all of the control structure syntax at one
time, Chapter 10 covers the additional branching and looping structures in a manner
that enables appropriate sections to be covered as extensions to Chapters 6 and 9.
Chapter 10 is the “ice cream and cake” section of the book, covering the additional
control structures that make the coding of certain algorithms easier. In addition to the
switch, do, and for statements, Chapter 10 introduces the concept of exception handling.
We show students how to use a try-catch statement to catch exceptions. Because we’ve
already covered inheritance, it is a simple matter to define new exception classes that
can be thrown between sections of user code. Students then are able to write code that
is robust in the face of errors that cannot be handled directly with testing and branching.
Chapters 11, 12, and 13 are devoted to composite data structures. In Chapter 12, the
basic concept of a composite structure is introduced and illustrated with the Java array.
In Chapter 13, we show how an array can be used to implement a general-purpose list
class. Our prior class designs have been in the context of specific applications, and this
is the first taste of an object-oriented design that does not have a predefined client.
Then, in Chapter 13, we extend the discussion of arrays to multiple dimensions, and
through a case study we show how they can be used to represent mathematical matrices. Given this numerically motivated case study, it is also natural to review the limitations of floating-point numbers as they are represented in the computer.
Chapter 14 concludes the text with a quick tour of the concept of recursion and
some example algorithms. As in our previous texts, this chapter is designed so that it
can be assigned for reading along with earlier chapters. The first half of the chapter can
be covered after Chapter 6, although the contrasting iterative examples won’t be readable until after Chapter 9. The second half of the chapter can be read after Chapter 11,
as it applies recursion to arrays.
Chapter Features
Goals Each chapter begins with a list of learning objectives for the student. These
goals are reinforced and tested in the end-of-chapter exercises.
Problem-Solving Case Studies A full development of a problem from its statement to a
working Java application is developed. In chapters beginning with 5, the CRC card
design strategy is employed to develop object-oriented designs that are then translated
into code. Test plans and sample test data are also presented for many of these case
studies.
Testing and Debugging These sections consider the implications of the chapter material
with regard to testing of applications or classes. They conclude with a list of testing and
debugging hints.
Quick Checks These questions test the student’s recall of major points associated with
the chapter goals. Upon reading each question, the student immediately should know
viii | Preface
the answer, which he or she can verify by glancing at the answer at the end of the
section. The page number on which the concept is discussed appears at the end of each
question so that the student can review the material in the event of an incorrect
response.
Exam Preparation Exercises To help the student prepare for tests, these questions
usually have objective answers and are designed to be answerable with a few minutes
of work. Answers to selected questions are given in the back of the book, and the
remaining questions are answered in the Instructor’s Guide.
Programming Warm-Up Exercises These questions provide the student with experience
in writing Java code fragments. The student can practice the syntactic constructs in
each chapter without the burden of writing a complete program.
Programming Problems These exercises require the student to design solutions and
write complete Java applications.
Case Study Follow-Up Exercises Much of modern programming practice involves
reading and modifying existing code. These exercises provide the student with an
opportunity to strengthen this critical skill by answering questions about the case study
code, or making changes to it.
Supplements
Instructor’s ToolKit CD-ROM
Also available to adopters on request from the publisher is a powerful teaching tool
entitled Instructor’s ToolKit. This CD-ROM contains an electronic version of the Instructor’s Guide, a computerized test bank, PowerPoint lecture presentations, and the complete programs from the text (see below).
Programs
The programs contain the source code for all of the complete Java applications and
stand-alone classes that are found within the textbook. They are available on the
Instructor’s ToolKit CD-ROM and also as a free download for instructors’ and students
from the publisher’s Web site: www.jbpub.com/disks. The programs from all of the case
studies, plus several programs that appear in the chapter bodies are included. Fragments
or snippets of code are not included nor are the solutions to the chapter-ending Programming Problems. These application files can be viewed or edited using any standard
text editor, but in order to compile and run the applications, a Java compiler must be
used.
Student Lecture Companion: A Note-Taking Guide
Designed from the PowerPoint™ presentation developed for this text, the Student Lecture Companion is an invaluable tool for learning. The notebook is designed to encourage students to focus their energies on listening to the lecture as they fill in additional
Preface | ix
details. The skeletal outline concept helps students organize their notes and readily recognize the important concepts in each chapter.
A Laboratory Course in Java
Written by Nell Dale, this lab manual follows the organization of the text. The lab manual is designed to allow the instructor maximum flexibility and may be used in both
open and closed laboratory settings. Each chapter contains three types of activities:
Prelab, Inlab, and Postlab. Each lesson is broken into exercises that thoroughly demonstrate the concept covered in the chapter. A disk that contains the applications, application shells (partial applications), and data files accompanies the lab manual.
Acknowledgments
We would like to thank the many individuals who have helped us in the preparation of
this text. We are indebted to the members of the faculties of the Computer Science
Departments at the University of Texas at Austin, The University of Massachusetts at
Amherst, and the University of Wisconsin–La Crosse.
We extend special thanks to Jeff Brumfield for developing the syntax template
metalanguage and allowing us to use it in this text.
For their many helpful suggestions, we thank the lecturers, teaching assistants, consultants, and student proctors who run the courses for which this book was written, and
the students themselves.
We are grateful to the following people who took the time to review the manuscript
at various stages in its development: John Connely, California Polytechnic State University; John Beidler, University of Scranton; Hang Lau, Concordia University; Thomas
Mertz, Millersville University; Bina Ramamurthy, State University of New York College
at Buffalo; James Roberts, Carnegie Mellon University; David Shultz, University of New
Mexico; Kenneth Slonneger, University of Iowa; Sylvia Sorkin, Community College of
Baltimore County.
We also thank Brooke Albright, Bobbie Lewis, and Mike and Sigrid Wile along with
the many people at Jones and Bartlett who contributed so much, especially J. Michael
Stranz, Jennifer Jacobson, Anne Spencer, and W. Scott Smith. Our very special thanks
go to Amy Rose, our Project Manager, who taught us a lesson in professionalism while
she was winning her gold stars.
Anyone who has ever written a book—or is related to someone who has—can appreciate the amount of time involved in such a project. To our families—all the Dale clan
and the extended Dale family (too numerous to name); to Lisa, Charlie, and Abby; to
Anne, Brady, and Kari—thanks for your tremendous support and indulgence.
N. D.
C. W.
M. H.
x | Preface
TEAMFLY
Team-Fly®
Preface v
1
Overview of Programming and Problem Solving 1
1.1 Overview of Programming 2
What Is Programming? 2
How Do We Write a Program? 3
Theoretical Foundations: Binary Representation of
Data 8
1.2 How Is a Program Converted into a Form That a Computer Can Use? 9
1.3 How is Interpreting a Program Different from Executing It? 13
1.4 How Is Compilation Related to Interpretation and Execution? 14
1.5 What Kinds of Instructions Can be Written in a
Programming Language? 16
Object-Oriented Programming Languages 18
1.6 What Is a Computer? 19
1.7 Ethics and Responsibilities in the Computing Profession 22
Software Piracy 24
Privacy of Data 24
Use of Computer Resources 25
Software Engineering 26
1.8 Problem-Solving Techniques 27
Ask Questions 27
Look for Things That Are Familiar 28
Solve by Analogy 28
Means-Ends Analysis 29
Divide and Conquer 30
The Building-Block Approach 31
Merging Solutions 31
Mental Blocks: The Fear of Starting 32
Algorithmic Problem Solving 33
Problem-Solving Case Study: A Company Payroll Program 33
Summary 40
Quick Check 41
Exam Preparation Exercises 42
Programming Warm-Up Exercises 44
Case Study Follow-Up Exercises 44
2
Java Syntax and Semantics, and the Program Entry
Process 47
2.1 Syntax and Semantics 48
Theoretical Foundations: Metalanguages 49
Syntax Templates 51
Naming Program Elements: Identifiers 52
Matters of Style: Using Meaningful, Readable Identifiers 54
2.2 Data Types 54
Background Information: Data Storage 55
2.3 Classes and Objects 56
2.4 Defining Terms: Declarations 59
Matters of Style: Capitalization of Identifiers 63
2.5 Taking Action: Executable Statements 64
Beyond Minimalism: Adding Comments to a Program 70
Program Construction 71
Blocks 73
2.6 Program Entry, Correction, and Execution 75
Entering a Program 75
Compiling and Running a Program 76
Finishing Up 77
xii | Contents
Problem-Solving Case Study: Display a Date in Multiple Formats 78
Testing and Debugging 81
Summary of Classes 82
Summary 83
Quick Check 83
Exam Preparation Exercises 86
Programming Warm-Up Exercises 88
Programming Problems 90
Case Study Follow-Up Exercises 91
3
Event-Driven Output 93
3.1 Classes and Methods 94
Frames 94
Background Information: The Origins of Java 101
3.2 Formatting Output 103
Using GridLayout for Tabular Output 103
Alignment of Text within Labels 104
3.3 Handling Events 105
3.4 Register an Event Listener 106
3.5 Event-Handler Methods 108
Problem-Solving Case Study: Display a Date in Multiple
Formats 112
Testing and Debugging 115
Summary of Classes 116
Summary 117
Quick Check 117
Exam Preparation Exercises 118
Programming Warm-Up Exercises 119
Programming Problems 121
Case Study Follow-Up Exercises 122
4
Numeric Types and Expressions 123
4.1 Overview of Java Data Types 124
4.2 Numeric Data Types 126
Integral Types 126
Floating-Point Types 128
Contents | xiii
4.3 Declarations for Numeric Types 129
Named Constant Declarations 129
Software Engineering Tip: Using Named Constants Instead of
Literals 130
Variable Declarations 130
4.4 Simple Arithmetic Expressions 131
Arithmetic Operators 131
Increment and Decrement Operators 135
4.5 Compound Arithmetic Expressions 136
Precedence Rules 136
Type Conversion and Type Casting 138
May We Introduce: Blaise Pascal 144
4.6 Additional Mathematical Methods 145
Matters of Style: Program Formatting 146
4.7 Additional String Operations 149
The length Method 149
The substring Method 151
4.8 Formatting Numeric Types 153
Software Engineering Tip: Understanding Before Changing 154
Problem-Solving Case Study: Map Measurements 155
Testing and Debugging 160
Summary of Classes 161
Summary 162
Quick Check 162
Exam Preparation Exercises 164
Programming Warm-Up Exercises 168
Programming Problems 171
Case Study Follow-Up Exercises 173
5
Event-Driven Input and Software Design Strategies 175
5.1 Getting Data into Programs 176
5.2 Entering Data Using Fields in a Frame 177
5.3 Creating a Data Entry Field 179
5.4 Extracting a Value from a Field 180
5.5 Creating a Button 182
5.6 Creating and Registering a Button Event Listener 184
xiv | Contents