"Purchase this book NEW and receive FREE!
The Student Resource Disk for Java
• Borland® JBuilder™ 7 Personal • Sun Java™ 2 SDK Standard Edition • Sun Java™ 2 SDK Standard Edition Documentation • Program Files
JONES AND BARTLETT COMPUTER SCIENCE
TE
Team-Fly®
AM FL Y
World Headquarters Jones and Bartlett Publishers 40 Tall Pine Drive Sudbury, MA 01776 978-443-5000 info@jbpub.com 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
Copyright © 2003 by Jones and Bartlett Publishers, Inc. Cover image © Peter J. Robinson/Photolibrary/PictureQuest Text photo credits follow the index, which constitutes a continuation of the copyright page. Unless otherwise acknowledged, all photographs are the property of Jones and Bartlett Publishers. Library of Congress Cataloging-in-Publication Data Dale, Nell B. Programming and problem solving with Java / Nell Dale, Chip Weems, Mark Headington. p. cm. Includes index. ISBN 0-7637-0490-3 1. Java (Computer program language) I. Weems, Chip. II. Headington, Mark R. III. Title. QA76.73.J38D346 2003 005.13’3--dc21 2002043476 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. Production Credits Chief Executive Officer: Clayton Jones Chief Operating Officer: Don W. Jones, Jr. Executive V.P. and Publisher: Robert W. Holland, Jr. V.P., Design and Production: Anne Spencer V.P., Manufacturing and Inventory Control: Therese Bräuer V.P., Sales and Marketing: William Kane Editor-in-Chief, College: J. Michael Stranz Production Manager: Amy Rose Senior Marketing Manager: Nathan Schultz Associate Production Editor: Karen C. Ferreira Associate Editor: Theresa DiDonato Production Assistant: Jenny McIsaac Cover Design: Kristin Ohlin Composition: Northeast Compositors Illustrations and Technical Art: Smolinski Studios Copyediting: Jill Hobbs Proofreading: Trillium Project Management Text Design: Anne Spencer Printing and Binding: Courier Kendallville Cover Printing: Lehigh Press This book was typeset in QuarkXPress 4.1 on a Macintosh G4. The font families used were Caecilia, Myria, and Letter Gothic. The first printing was printed on 45# Utopia GW Matte. Printed in the United States of America 07 06 05 04 03 10 9 8 7 6 5 4 3 2 1
This book is dedicated to you, and to all of our other students for whom it was begun and without whom it would never have been completed.
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.
J. W. von Goethe, Faust, Walter Kaufman trans., New York, Anchor/Doubleday: 1963.
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.
Contents
Preface xv
Chapter 1
Introduction to Object-Oriented Programming
2
4
1.1 1.2 1.3 1.4 1.5 1.6 1.7
Overview of Object-Oriented Programming
What Is Programming? 4 How Do We Write a Program? 5
How Is Java Code Converted into a Form That a Computer Can Use? How Does Interpreting Code Differ from Executing It? How Is Compilation Related to Interpretation and Execution? What Kinds of Instructions Can Be Written in a Programming Language?
Object-Oriented Programming Languages 18
10 14 14 15 20 22
What’s Inside the Computer? Problem-Solving Techniques
Ask Questions 23 Look for Things That Are Familiar 24 Solve by Analogy 25 Means-Ends Analysis 25 Divide and Conquer 26 The Building-Block Approach 27 Merging Solutions 27 Mental Blocks: The Fear of Starting 28 Object-Oriented Problem Solving 29 Case Study: Party Planning 30
Summary 33 Quick Check 34 Exam Preparation Exercises 36 Programming Warm-Up Exercises Programming Problems 38 Case Study Follow-Up 38
37
Chapter 2
Java Syntax and Semantics, Classes, and Objects
40
42
2.1
The Elements of Java Programs
Syntax and Semantics 42 Syntax Templates 42 Naming Program Elements: Identifiers Built-in Types in Java 47 Classes and Objects 50 Defining Terms: Declarations 54
46
v
vi
|
Contents
Field Declarations 54 Assignment and Expressions 59 Beyond Minimalism: Adding Comments to Code Output 64 Input 67 Interactive Input and Output 70
64
2.2 2.3
Application Construction
Blocks 73
70 75
Application Entry, Correction, and Execution
Entering Application Code 75 Compiling and Running an Application Finishing Up 77 77
2.4
Classes and Methods
User Classes 78 Methods 79 Case Study: Display a Name in Multiple Formats
78
83
2.5
Testing and Debugging
Summary 87 Quick Check 88 Exam Preparation Exercises 90 Programming Warm-Up Exercises Programming Problems 95 Case Study Follow-Up 97
86
94
Chapter 3
Arithmetic Expressions
98
100 103
3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8
Overview of Java Data Types Numeric Data Types
Integral Types 103 Floating-Point Types 105
Declarations for Numeric Types
Named Constant Declarations Variable Declarations 107 106
106
Simple Arithmetic Expressions
Arithmetic Operators 108 Increment and Decrement Operators Precedence Rules 114 Type Conversion and Type Casting 112
108
Compound Arithmetic Expressions
115
114
Additional Mathematical Methods Value-Returning Class Methods Additional String Operations
120 122 126
Contents
|
vii
The length Method 126 The indexOf Method 126 The substring Method 128 Converting Strings to Numeric Values Noninteractive Input/Output 131
130
3.9 3.10
Applications with Multiple Class Files
Case Study: Small Company Payroll 135
131 140
Testing and Debugging
Summary 141 Quick Check 141 Exam Preparation Exercises 143 Programming Warm-Up Exercises Programming Problems 150 Case Study Follow-Up 151
146
Chapter 4
Selection and Encapsulation
152
154 154
4.1 4.2
Flow of Control
Selection 154
Conditions and Logical Expressions
The boolean Data Type 155 Logical Expressions 155 Precedence of Operators 165 Relational Operators with Floating-Point Types
167
4.3
The if Statement
The if-else Form 168 Blocks (Compound Statements) The if Form 170 169
167
4.4 4.5 4.6 4.7
Nested if Statements
The Dangling else 176
173 177 179
Encapsulation Abstraction
Data and Control Abstraction 179 Case Study: Warning Notices 184
Testing and Debugging
Testing Strategies 190 The Test Plan 193 Tests Performed Automatically During Compilation and Execution 194
Summary 197 Quick Check 197 Exam Preparation Exercises 199 Programming Warm-Up Exercises
190
204
viii
|
Contents
Programming Problems 206 Case Study Follow-Up 209
Chapter 5
File Objects and Looping Statements
210
212
5.1
File Input and Output
Files 212 Using Files 213 An Example Application Using Files
219
5.2
Looping
The while Statement 221 Phases of Loop Execution 223 Loops Using the while Statement 223 Count-Controlled Loops 223 Event-Controlled Loops 225 Looping Subtasks 229 How to Design Loops 233 Designing the Flow of Control 233 Designing the Process Within the Loop 235 The Loop Exit 236 Nested Loops 236 General Pattern 237 Designing Nested Loops 240
220
5.3 5.4
Mutable and Immutable Objects
A Parameter-Passing Analogy 244 Case Study: Average Income By Gender 246
242
Testing and Debugging
Loop-Testing Strategy 252 Test Plans Involving Loops 252
Summary 255 Quick Check 257 Exam Preparation Exercises 258 Programming Warm-Up Exercises Programming Problems 264 Case Study Follow-Up 266
252
262
Chapter 6
Object-Oriented Software Design and Implementation 268
6.1 6.2 6.3 6.4
Software Design Strategies Objects and Classes Revisited Object-Oriented Design
Object-Oriented Problem Solving Software Engineering 276 275
270 271 274
The CRC Card Design Process
Identifying the Initial Classes Through Brainstorming 277
277
Contents
|
ix
Filtering 278 Determining Responsibilities Inheritance 285
280
6.5 6.6
Functional Decomposition
Writing Modules 287
285 289
Object-Oriented Implementation
Class Interface Design 289 Internal Data Representation 291 Responsibilities as Methods 292
6.7
Packages
Package Syntax 294 Packages with Multiple Compilation Units Package Example 297 296
294
6.8
Ethics and Responsibilities in the Computing Profession
Software Piracy 301 Privacy of Data 302 Use of Computer Resources 302 Case Study: Address Book 304
301
6.9
Testing and Debugging
Summary 315 Quick Check 316 Exam Preparation Exercises 317 Programming Warm-Up Exercises Programming Problems 320 Case Study Follow-Up 323
314
319
Chapter 7
Inheritance, Polymorphism, and Scope
324
326
7.1 7.2 7.3
Inheritance
An Analogy 326
Inheritance and the Object-Oriented Design Process How to Read a Class Hierarchy
Overriding 336 Hiding 336 Polymorphism 337
328 333
7.4 7.5 7.6
Derived Class Syntax Scope of Access
Internal Scope 340 External Scope 342
337 339
Implementing a Derived Class
Constructors in Derived Classes 347
346
x
|
Contents
Overloading and Method Signatures 347 Accessing Overridden and Hidden Methods and Fields A Concrete Example 349
349
7.7 7.8 7.9
Copy Constructors Output and Input of Objects
Case Study: Extending the Address Book 359
352 354 365
Testing and Debugging
Summary 366 Quick Check 367 Exam Preparation Exercises 368 Programming Warm-Up Exercises Programming Problem 372 Case Study Follow-Up 373
370
Chapter 8
Event-Driven Input and Output
AM FL Y
374
376
8.1
Frames
TE
Import Classes and Declare Fields 376 Instantiate Frame Objects and Specify Some of Their Properties 377 Add Output to the Content Pane 380 Make the Frame Visible on the Screen 380
8.2 8.3
Formatting Output
Using GridLayout for Tabular Output 382 Alignment of Text Within Jlabels 384
382
Event Handling
Creating a Button 385 Creating and Registering a Button Event Listener An Event-Handling Example 390 Event Loops 393 387
385
8.4 8.5 8.6 8.7 8.8 8.9
Entering Data Using Fields in a Frame Creating a Data Entry Field Using a Field Reading Data in an Event Handler
Case Study: Totaling Rainfall Amounts 402
394 396 397 398 409 420
Handling Multiple Button Events
Case Study: A Simple Calculator 412
Testing and Debugging
Summary 421 Quick Check 421 Exam Preparation Exercises 422
Team-Fly®
Contents
|
xi
Programming Warm-Up Exercises Programming Problems 426 Case Study Follow-Up 426
424
Chapter 9
Exceptions and Additional Control Structures
430
432
9.1
Exception-Handling Mechanism
The try-catch-finally Statement 432 Generating an Exception with throw 435 Exception Classes 437
9.2
Additional Control Statements
The switch Statement 438 The do Statement 442 The for Statement 445 Guidelines for Choosing a Looping Statement
438
448
9.3
Additional Java Operators
Assignment Operators and Assignment Expressions Increment and Decrement Operators 450 Bitwise Operators 451 The ?: Operator 456 Operator Precedence 456 Case Study: Monthly Rainfall Averages 459 448
448
9.4
Testing and Debugging
Summary 467 Quick Check 468 Exam Preparation Exercises 470 Programming Warm-Up Exercises Programming Problems 474 Case Study Follow-Up 477
466
472
Chapter 10
One-Dimensional Arrays
478
480 481 483
10.1 10.2 10.3
Atomic Data Types Composite Data Types One-Dimensional Arrays
Declaring an Array 486 Creating an Array 486 Declaring and Creating an Array with an Initializer List Accessing Individual Components 488 Out-of-Bounds Array Indexes 490 Aggregate Array Operations 491
488
10.4
Examples of Declaring and Processing Arrays
493
xii
|
Contents
Occupancy Rates 493 Sales Figures 494 Character Counts 495
10.5 10.6 10.7
Arrays of Objects
Arrays of Strings 497 Arrays of User-Defined Objects 500
497
Arrays and Methods Special Kinds of Array Processing
Partial (or Sub) Array Processing 501 Indexes with Semantic Content 501 Case Study: Grading True/False Tests 502
500 501
10.8
Testing and Debugging
Summary 513 Quick Check 513 Exam Preparation Exercises 514 Programming Warm-Up Exercises Programming Problems 518 Case Study Follow-Up 521
510
517
Chapter 11
Array-Based Lists
522
524 525
11.1 11.2
Lists List Class
Brainstorming the List Class 525 CRC Card 526 Refining the Responsibilities 526 Internal Data Representation 531 Responsibility Algorithms for Class List Test Plan 536
531
11.3 11.4
Sorting the List Items
Responsibility Algorithms for Class ListWithSort Class ListWithSort 541 539
539
Sorted List
Brainstorming the Sorted List 543 Responsibility Algorithms for Class SortedList Test Plan 548 545
543
11.5 11.6 11.7
The List Class Hierarchy and Abstract Classes Searching
Sequential Search 550 Binary Search 552
548 550
Generic Lists
Comparable Interface 559
559
Contents
|
xiii
Polymorphism 561 Case Study: Merging Address Books
562
11.8
Testing and Debugging
Summary 572 Quick Check 573 Exam Preparation Exercises 574 Programming Warm-Up Exercises Programming Problems 577 Case Study Follow-Up 578
571
575
Chapter 12
Multidimensional Arrays and Numeric Computation
580
582
12.1
Two-Dimensional Arrays
Array Declaration and Instantiation 582 Accessing Individual Components 583 Using Initializer Lists 584
12.2
Processing Two-Dimensional Arrays
Sum the Rows 587 Sum to Columns 588 Initialize the Array 589 Two-Dimensional Arrays and Methods
586
590
12.3 12.4 12.5
Multidimensional Arrays Vector Class Floating-Point Numbers
Representation of Floating-Point Numbers 592 Arithmetic with Floating-Point Numbers 595 Implementation of Floating-Point Numbers in the Computer 596
591 592 592
12.6 12.7
Decimal Format Type
Case Study: Matrix Manipulation 605
602 619
Testing and Debugging
Summary 621 Quick Check 621 Exam Preparation Exercises 623 Programming Warm-Up Exercises Programming Problems 630 Case Study Follow-Up 633
628
Chapter 13
Recursion
634
636
636
13.1
What Is Recursion?
Power Function Definition
xiv
|
Contents
Power Function Implementation
637
13.2
More Examples with Simple Variables
Calculating the Factorial Function 638 Converting Decimal Integers to Binary Numbers Towers of Hanoi 644 641
638
13.3 13.4 13.5
Recursive Algorithms with Structured Variables
Printing the Values in an Array Binary Search 651 648
648
Recursion or Iteration? Testing and Debugging
Summary 653 Quick Check 653 Exam Preparation Exercises 654 Programming Warm-Up Exercises
651 652
655
Chapter 14
Applets
658
660 661
14.1 14.2 14.3
What Is an Applet? How Do You Write an Applet?
Factorial 661 Calculator 664
How Do You Run an Applet?
Web Browsers 667 HTML 668 Factorial 669 Calculator 670 Case Study: Searching Experiments
667
671
14.4
Testing and Debugging
Summary 677 Quick Check 677 Exam Preparation Exercises 677 Programming Warm-Up Exercises Programming Problems 679 Case Study Follow-Up 680
676
678
Appendixes Glossary Answers Index
682 698 706 744
Preface
Programming and Problem Solving with Java™ represents a significant transition in the development of the Dale series, with much that is new. Here we briefly summarize the features of this new text. The most obvious new feature is the beautiful full-color design, which allows us to use colored code displays that follow conventions similar to the editors found in integrated development environments. The code coloring conventions also make syntax stand out from the text more effectively. For the first time, we are able to show realistic full-color screen images of program output. Color is used extensively to enhance the clarity and improve overall readability of illustrations, feature boxes, and other elements of the text. We’re very excited to add this new dimension to our pedagogical toolkit. This book has been developed from the ground up to be a Java text. It is not a “Java translation” of our previous texts. We have, however, retained our familiar easy-to-read style and clear approach to introducing new topics. Each chapter has the same overall organization as in our previous books, with a full problem-solving case study, testing and debugging hints, summary, and five types of exercises. Also, some topics, such as problem solving, are independent of the programming language and thus contain familiar discussions. An exciting new feature in each chapter is the division of the learning goals into knowledge goals and skill goals. Each chapter thus addresses specific concepts that students should understand as distinct from skills that they should develop. For example, in the chapter that covers inheritance, students are expected to understand the concept of a class hierarchy, and to be able to implement a derived class. In every regard, this new book is object-oriented in its presentation of the fundamental concepts of computing. From the very first chapter we use object-oriented terminology to de-
xv
xvi
|
Preface
scribe the software development process. Classes are covered extensively in Chapter 2, where we first encounter Java syntax. Over the course of the next several chapters, students learn to build separately compiled classes representing realistic objects and to add to their sophistication gradually. In Chapter 6, we present the CRC card technique for object-oriented design, and in Chapter 7 we formalize the earlier coverage of classes and introduce inheritance. Unlike our other Java text, Introduction to Java™ and Software Design, here we save the introduction of graphical user interface components for Chapter 8. These are used only sparingly in the remaining chapters, so that instructors who do not wish to focus on GUI and event programming do not have to do so. We use a modest subset of the Swing library components that is appropriate to a course at this level. 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 with prior familiarity of event-driven interfaces and expect to learn how to write programs containing them. In this book, we have thus strived to strike a balance between covering the more complex style of I/O with which students are familiar, and the more traditional console I/O that is simpler to use for early applications. The text uses real Java I/O classes rather than ones we supply. It would have made our job much easier to supply a streamlined set of I/O classes to simplify Java I/O. We have seen many books 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 using such libraries produces students who still do not know how to write real Java programs at the end of the course, leaving them to learn the Java I/O library on their own, without help or guidance. Instead, we have carefully chosen a subset of the console I/O and Swing packages that is within their grasp, and that covers all of the essential concepts necessary for them to explore additional features of the library on their own. All of the programs have been tested with Metrowerks CodeWarrior® or the Apple OSX version of the Sun SDK.The program code is included on the Student Resource Disk for Java, which accompanies your new book.
Chapter Coverage
Chapte..."
|
You need to upgrade your Flash Player , or try to enable javascript in order see this document properly.
|
|