WileyPLUS is a research-based online environment
for effective teaching and learning.
WileyPLUS builds students’ confidence because it takes the guesswork
out of studying by providing students with a clear roadmap:
• what to do
• how to do it
• if they did it right
It offers interactive resources along with a complete digital textbook that help
students learn more. With WileyPLUS, students take more initiative so you’ll have
greater impact on their achievement in the classroom and beyond.
For more information, visit www.wileyplus.com
HELP, RESOURCES, AND PERSONAL
SUPPORT YOU AND YOUR STUDENTS NEED!
www.wileyplus.com/resources
i
I
A t- DAY?S~C
1st CLASS
2-Minute Tutorials and all
of the resources you and your
students need to get started
Student support from an
experienced student user
Collaborate with your colleagues,
find a mentor, attend virtual and live
events, and view resources
www.WhereFacultyConnect.com
Pre-loaded, ready-to-use
assignments and presentations
created by subject matter experts
Technical Support 24/7
FAQs, online chat,
and phone support
www.wileyplus.com/support
Your WileyPLUS Account Manager,
providing personal training
and support
CAY HORSTMANN
San Jose State University
WILEY
John Wiley & Sons, Inc.
VICE PRESIDENT AND EXECUTIVE PUBLISHER Don Fowley
EXECUTIVE EDITOR
CONTENT MANAGER
SENIOR PRODUCTION EDITOR
EXECUTIVE MARKETING MANAGER
CREATIVE DIRECTOR
SENIOR DESIGNER
SENIOR PHOTO EDITOR
PRODUCT DESIGNER
CONTENT EDITOR
EDITORIAL PROGRAM ASSISTANT
MEDIA SPECIALIST
PRODUCTION SERVICES
COVER PHOTOS
Beth Lang Golub
Kevin Holm
John Curley
Christopher Ruel
Harry Nolan
Madelyn Lesure
Lisa Gee
Thomas Kulesa
Wendy Ashenberg
Elizabeth Mills
Lisa Sabatini
Cindy Johnson
© Robbie Taylor/ Alamy;
© FLPA/John Holmes/Age Fotostock;
© frans lemmens/ Alamy
This book was set in Stempel Garamond by Publishing Services, and printed and bound by R.R. Donnelley &
Sons Company. The cover was printed by R.R. Donnelley & Sons, J efferson City.
This book is printed on acid-free paper. °°
Copyright © 2013, 2010 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be
reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical,
photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976
United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood
Drive, Danvers, MA 01923, website www.copyright.com. Requests to the Publisher for permission should be
addressed to the Permissions Department, John Wiley & Sons, Inc., Ill River Street, Hoboken, NJ 07030-5774,
(201) 748-6011, fax (201) 748-6008, website www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to a
third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc¬
tions and a free of charge return shipping label are available at www.wiley.com/go/returnlahel. Outside of the
United States, please contact your local representative.
Library of Congress Cataloging-in-Publication Data:
Horstmann, Cay S., 1959-
Big Java : late objects / Cay Horstmann.
p. cm.
Includes index.
ISBN 978-1-118-08788-6 (pbk. : acid-free paper)
1. Java (Computer program language) I. Title.
QA76.73.J38H67 2012
005.2762— dc23
2011043315
ISBN 978-1-118-08788-6 (Main Book)
ISBN 978-1-118-12942-5 (Binder-Ready Version)
Printed in the United States of America
10987654321
PREFACE
This book is an introduction to Java and computer programming that focuses on the
essentials — and on effective learning. The book is designed to serve a wide range of
student interests and abilities and is suitable for a first course in programming for
computer scientists, engineers, and students in other disciplines. No prior program¬
ming experience is required, and only a modest amount of high school algebra is
needed. Here are the key features of this book:
Present fundamentals first.
The book takes a traditional route, first stressing control structures, methods, pro¬
cedural decomposition, and arrays. Objects are used when appropriate in the early
chapters. Students start designing and implementing their own classes in Chapter 8.
Guidance and worked examples help students succeed.
Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc¬
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “Problem Solving” sections stress the
importance of design and planning. “How To” guides help students with common
programming tasks. Additional Worked Examples are available online.
Practice makes perfect.
Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. This book contains
a substantial number of self-check questions at the end of each section. “Practice It”
pointers suggest exercises to try after each section. And additional practice opportu¬
nities, including code completion questions, guided lab exercises, and skill-oriented
multiple-choice questions are available online.
A visual approach motivates the reader and eases navigation.
Photographs present visual analogies that explain the
nature and behavior of computer concepts. Step-by-
step figures illustrate complex program operations.
Syntax boxes and example tables present a variety
of typical and special cases in a compact format. It
is easy to get the “lay of the land” by browsing the
visuals, before focusing on the textual material.
Focus on the essentials while being
technically accurate.
An encyclopedic coverage is not helpful for a begin¬
ning programmer, but neither is the opposite —
reducing the material to a list of simplistic bullet points. In this book, the essentials
are presented in digestible chunks, with separate notes that go deeper into good prac¬
tices or language features when the reader is ready for the additional information.
You will not find artificial over-simplifications that give an illusion of knowledge.
Visual features help the reader
with navigation.
vi Preface
A Tour of the Book
This book is intended for a two-semester introduction to programming that may also
include algorithms, data structures, and/or applications.
The first seven chapters follow a traditional approach to basic programming
concepts. Students learn about control structures, stepwise refinement, and arrays.
Objects are used only for input/output and string processing. Input/output is cov¬
ered in Chapter 7, but Sections 7.1 and 7.2 can be covered with Chapter 4; in that way,
students can practice writing loops that process text files. Chapter 4 also provides an
Fundamentals
Object-Oriented Design
I . Introduction
Preface vii
optional introduction to programming drawings that consist of lines, rectangles, and
ovals, with an emphasis on reinforcing loops.
After students have gained a solid foundation, they are ready to tackle the imple¬
mentation of classes in Chapter 8. Chapter 9 covers inheritance and interfaces. A
simple methodology for object-oriented design is presented in Chapter 12. Object-
oriented design may also be covered immediately after Chapter 9 by omitting the
GUI versions of the sample programs. By the end of these chapters, students will be
able to implement programs with multiple interacting classes.
Graphical user interfaces are presented in Chapters 10 and 11. The first of these
chapters enables students to write programs with buttons, text components, and sim¬
ple drawings. If you want to go deeper, you will find layout management and addi¬
tional user-interface components in the second chapter.
Chapters 13-18 cover algorithms and data structures at a level suitable for begin¬
ning students. Recursion, in Chapter 13, starts with simple examples and progresses
to meaningful applications that would be difficult to implement iteratively. Chapter
14 covers quadratic sorting algorithms as well as merge sort, with an informal intro¬
duction to big-Oh notation. In Chapter 15, the Java Collections Framework is pre¬
sented from the perspective of a library user, without revealing the implementations
of lists and maps. You can cover this chapter anytime after Chapter 8. In Chapters 16
and 1 7, students learn how to implement linear and tree-based data structures, and
how to analyze the efficiency of operations on these data structures. Finally, Chapter
18 covers programming with Java generics.
Chapters 19-24 feature applied topics: binary input/output, concurrent program¬
ming, networking, database programming, XML processing, and the development of
web applications. Chapters 20-24 are available in electronic form on the Web and in
WileyPLUS.
Any subset of these chapters can be incorporated into a custom print version of
this text; ask your Wiley sales representative for details.
Problem Solving Strategies
This book provides practical, step-by-step illustrations of techniques that can help
students devise and evaluate solutions to programming problems. Introduced where
they are most relevant, these strategies address barriers to success for many students.
Strategies included are:
• Algorithm Design (with pseudocode)
• First Do It By Hand (doing sample
calculations by hand)
• Flowcharts
• Test Cases
• Hand-Tracing
• Storyboards
• Reusable Methods
• Stepwise Refinement
• Adapting Algorithms
• Discovering Algorithms by
Manipulating Physical Objects
• Tracing Objects (identifying state and
behavior)
• Patterns for Object Data
• Thinking Recursively
• Estimating the Running Time of an
Algorithm
Optional Science and Business Exercises
End-of-chapter exercises include problems from scientific and business domains.
Designed to engage students, the exercises illustrate the value of programming in
applied fields.
VIII
Preface
Appendices
Many instructors find it highly beneficial to require a consistent style for all assign¬
ments. If the style guide in Appendix L conflicts with instructor sentiment or local
customs, however, it is available in electronic form so that it can be modified.
A. The Basic Latin and Latin-1 Subsets of Unicode
B. Java Operator Summary
C. Java Reserved Word Summary
D. The Java Library
E. Java Syntax Summary
F. HTML Summary
C. Tool Summary
H. Javadoc Summary
I. Number Systems
J. Bit and Shift Operations
K. UML Summary
L. Java Language Coding Guidelines
Web Resources
This book is complemented by a complete suite of online resources and a robust
WileyPLUS course. Go to www.wiley.com/conege/horstmann to visit the online compan¬
ion sites, which include
• Source code for all example programs in the book and in online examples.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Video Examples in which the author explains the steps he is taking and shows his
work as he solves a programming problem.
• Lab exercises that apply chapter concepts (with solutions for instructors only).
• Lecture presentation slides (in PowerPoint format).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only).
WileyPLUS
WileyPLUS is an online teaching and learning environment that integrates the digital
textbook with instructor and student resources. See pages xiii-xiv for details.
Walkthrough ix
A Walkthrough of the Learning Aids
The pedagogical elements in this book work together to focus on and reinforce key
concepts and fundamental principles of programming, with additional tips and detail
organized to support and deepen these fundamentals. In addition to traditional
features, such as chapter objectives and a wealth of exercises, each chapter contains
elements geared to today’s visual learner.
4.2 The for Loop 135
Throughout each chapter,
margin notes show where
new concepts are introduced
and provide an outline of key ideas.
4.2 The for Loop
The for loop is
used when a
value runs from a
starting point to an
ending point with a
constant increment
or decrement.
Additional online example code
provides complete programs for
students to run and modify.
Annotated syntax boxes
provide a quick, visual overview
of new language constructs.
A program usinc
common loop
algorithms.
It often happens that you want to execute a sequence of statements a given number
of times. You can use awhile loop that is controlled by a counter, as in the following
example:
int counter = 1; // Initialize the counter
while (counter <= 10) // Check the counter
{
System . out . pri ntl n(counter) ;
counter++; // Update the counter
}
Because this loop type is so common, there is a spe¬
cial form for it, called the for loop (see Syntax 4.2).
for (int counter = 1; counter <= 10; counter++)
{
System .out.println(counter);
}
Some people call this loop count-controlled. In con¬
trast, the while loop of the preceding section can be
called an event-controlled loop because it executes
until an event occurs; namely that the balance
reaches the target. Another commonly used term
for a count-controlled loop is definite. You know
from the outset that the loop body will be executed
a definite number of times; ten times in our exam¬
ple. In contrast, you do not know how many itera¬
tions it takes to accumulate a target balance. Such a
loop is called indefinite.
7u can visualize the for loop a
n orderly sequence of steps.
"Syntax 4.2 for Statement
Annotations explain required
components and point to more
information on common errors
or best practices associated
with the syntax.
Syntax for ( initialization ; condition ; update )
statements
These three
expressions should be related.
1^ See page 163.
This initialization The condition is
This update is
happens once checked before
executed after
before the loop starts. each iteration.
each iteration.
\ \
The variable i is sum = sum + i ;
This loop executes 6 times.
defined only in this for loop. }
A See page 1 64.
See page 161.
Like a variable in a computer
program, a parking space has
an identifier and a contents.
Analogies to everyday objects are
used to explain the nature and behavior
of concepts such as variables, data
types, loops, and more.
x Walkthrough
Memorable photos reinforce
analogies and help students
remember the concepts.
Problem Solving sections teach
techniques for generating ideas and
evaluating proposed solutions, often
using pencil and paper or other
artifacts. These sections emphasize
that most of the planning and problem
solving that makes students successful
happens away from the computer.
A recipe for a fruit pie may say to use any kind of fruit.
Here, “fruit" is an example of a parameter variable.
Apples and cherries are examples of arguments.
6.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 277
Now how does that help us with our problem, switching the first and the second
half of the array?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
Java programmers, we will say that we swap the coins in positions 0 and 4:
Next, we swap the coins in positions 1 and 5:
0##
f ••
Describing an Algorithm with Pseudocode
This is the first of many “How To” sections in this book that give you step-by-step proce¬
dures for carrying out important tasks in developing computer programs.
Before you are ready to write a program in Java, you need to develop an algorithm— a
method for arriving at a solution for a particular problem. Describe the algorithm in
pseudocode: a sequence of precise steps formulated in English.
For example, consider this problem: You have the choice of
buying two cars. One is more fuel efficient than the other, but
also more expensive. You know the price and fuel efficiency (in
miles per gallon, mpg) of both cars. You plan to keep the car for
ten years. Assume a price of $4 per gallon of gas and usage of
15,000 miles per year. You will pay cash for the car and not
worry about financing costs. Which car is the better deal?
How To guides give step-by-step
guidance for common programming
tasks, emphasizing planning and
testing. They answer the beginner’s
question, “Now what do I do?” and
integrate key concepts into a
problem-solving sequence.
Walkthrough xi
Parameter Passing • The method computes the expression si deLength * sideLength * si deLength, which
has the value 8. That value is stored in the variable volume. Q
f \
Self-check exercises at the
end of each section are designed
to make students think through
the new material — and can
spark discussion in lecture.
V _ J
The method returns. All of its variables are removed. The return value is trans¬
ferred to the caller, that is, the method calling the cubeVol ume method. The caller
puts the return value in the resul tl variable. Q
6. Write the for loop of the InvestmentTable. java program as a while loop.
7. How many numbers does this loop print?
for (int n = 10; n >= 0; n— )
{
System. out . pri ntl n(n) ;
}
8. Write a for loop that prints all even numbers between 10 and 20 (inclusive).
9. Write a for loop that computes the sum of the integers from 1 to n.
10. How would you modify the for loop of the InvestmentTable. java program to
print all balances until the investment has doubled?
f 'N
Optional science and business
exercises engage students with
realistic applications of Java.
V _ _ _ _ _ /
section_1 /Doublelnvestment.java
1 /**
2 This program computes the time required to double an investment.
3 */
4 public class Doubleinvestment
5 {
6 public static void main(String[] args)
7 {
8 final double RATE = 5;
9 final double INITIAL_BALANCE = 10000;
10 final double TARGET = 2 * INITIAL_BALANCE;
1 1
12 double balance = INITIAL_BALANCE ;
13 int year = 0;
14
15 // Count the years required for the investment to double
16
17 while (balance < TARGET)
18 {
19 year++;
20 double interest = balance * RATE / 100;
21 balance = balance + interest;
22 }
23
24 System, out. pri ntl n("The investment doubled after "
25 + year + " years.");
26 }
27 }
Science P6.32 Sounds can be represented by an array of “sample
values” that describe the intensity of the sound at a
point in time. The program ch06/sound/SoundEffect.
java reads a sound file (in WAV format), calls a
method process for processing the sample values, and
saves the sound file. Your task is to implement the
process method by introducing an echo. For each
t
C
r
■ Business P9.21 Implement a superclass Appointment and sub¬
classes Onetime, Daily, and Monthly. An appoint¬
ment has a description (for example, “see the
dentist”) and a date and time. Write a method
occurs0n(int year, int month, int day) that checks
whether the appointment occurs on that date.
For example, for a monthly appointment, you
must check whether the day of the month
matches. Then fill an array of Appoi ntment objects
with a mixture of appointments. Have the user enter a date and pri:
ments that occur on that date.
t out all appoint-
/ \
Program listings are carefully
designed for easy reading,
going well beyond simple
color coding. Methods are set
off by a subtle outline.
V _ )
xii Walkthrough
'\
Common Errors describe the kinds
of errors that students often make,
with an explanation of why the errors
occur, and what to do about them.
Common Error 6.4
Length and Size
Unfortunately, the Java syntax for
determining the number of elements
in an array, an array list, and a string
is not at all consistent. It is a com¬
mon error to confuse these. You just
Data Type
Number of Elements
Array
a. length
Array list
a.sizeO
have to remember the correct syntax
for every data type.
String
a.lengthO
Programming Tip 3.5
4-
Programming Tips explain
good programming practices,
and encourage students to be
more productive with tips and
techniques such as hand-tracing.
Hand-Tracing
A very useful technique for understanding whether a pro¬
gram works correctly is called hand-tracing. You simulate
the program’s activity on a sheet of paper. You can use this
method with pseudocode or Java code.
Get an index card, a cocktail napkin, or whatever sheet
of paper is within reach. Make a column for each variable.
Have the program code ready. Use a marker, such as a
paper clip, to mark the current statement. In your mind,
execute statements one at a time. Every time the value of a
variable changes, cross out the old value and write the new
value below the old one.
For example, let’s trace the tax program with the data
from the program run onpage 1 02. In lines 1 5 and 1 6, taxi and
tax2 are initialized to 0.
Hand-tracing helps you
understand whether a
program works correctly.
ain(String[] args)
double RATE2 = 0.2S;
double RATE1 SINGLE J.IMIT = 32000;
double RATE1_MARRIED_LIMIT = 64000;
In lines 22 and 25, income and marital Status a
initialized by input statements.
Special Topic 7.2
Special Topics present optional
topics and provide additional
explanation of others. New
features of Java 7 are also
covered in these notes.
Q A program that
demonstrates how to
use a file chooser.
File Dialog Boxes
In a program with a graphical user interface, you will want to use a file dialog box (such as the
one shown in the figure below) whenever the users of your program need to pick a file. The
IFil eChooser class implements a file dialog box for the Swing user-interface toolkit.
The 3 Fi 1 eChooser class has many options to fine-tune the display of the dialog box, but in its
most basic form it is quite simple: Construct a file chooser object; then call the showOpenDialog
or showSaveDialog method. Both methods show the same dialog box, but the button for select¬
ing a file is labeled “Open” or “Save”, depending on which method you call.
For better placement of the dialog box on the screen, you can specify the user-interface
component over which to pop up the dialog box. If you don’t care where the dialog box pops
up, you can simply pass null. The showOpenDialog and showSaveDialog methods return either
JFi 1 eChooser .APPR0VE_0PTI0N, if the user has chosen a file, or 3FileChooser.CANCEL_0PTI0N, if the
user canceled the selection. If a file was chosen, then you call the getSelectedFile method to
obtain a Fi 1 e object that describes the file. Here is a complete example:
IFileChooser chooser = new IFileChooserO ;
Scanner in = null;
if (chooser. showOpenDialog(null) = IFil eChooser ,APPR0VE_0PTI0N)
{
File selectedFile = chooser. getSelectedFileO I
in = new Scanner(selectedFile);
Call with
showOpenDial og
| allclatctc-nofumt.htra
il □ wmliw-tunmw
□ Java
: constant- valtits.liunl
D ovirvirw-utt.hu
□ Java*
Q package -Hit
□ Olfl
D help - docMml
0 unalKKl roinli
n ittooirt t
Q) Indtxliiinl
Q stvltshttt.ris
Random Fact 4.1 The First Bug
Random Facts provide historical and
social information on computing — for
interest and to fulfill the “historical and
social context” requirements of the
ACM/IEEE curriculum guidelines.
According to legend,
the first bug was
found in the Mark il,
chanical computer a
sity. It really was caused by a bug
moth was trapped in a relay switch.
Actually, from the note that the
operator left in the log book next to
the moth (see the figure), it appears as
if the term “bug” had already been in
active use at the time.
The pioneering computer scientist grams right. I can remember the exact
Maurice Wilkes wrote, “Somehow, at instant in time at which it dawned on
huge electrome- the Moore School and afterwards, one me that a great part of my future life
Harvard Univer- had always assumed there would be would be spent finding mistakes in
particular difficulty in getting pro- my own programs."
J
.T
Walkthrough xiii
WileyPLUS
WileyPLUS is an online environment that supports students and instructors. This
book’s WileyPLUS course can complement the printed text or replace it altogether.
For Students
Different learning styles, different levels of proficiency, different levels of prepara¬
tion-each student is unique. WileyPLUS empowers all students to take advantage
of their individual strengths.
Integrated, multi-media resources— including audio and visual exhibits and demon¬
stration problems — encourage active learning and provide multiple study paths to
fit each student’s learning preferences.
• Worked Examples apply the problem-solving steps in the book to another realis¬
tic example.
• Video Examples present the author explaining the steps he is taking and showing
his work as he solves a programming problem.
• Animations of key concepts allow students to replay dynamic explanations that
instructors usually provide on a whiteboard.
Self-assessments are linked to relevant portions of the text. Students can take control
of their own learning and practice until they master the material.
• Practice quizzes can reveal areas where students need to focus.
• “Learn by doing” lab exercises can be assigned for self-study or for use in the lab.
• “Code completion” questions enable students to practice programming skills by
filling in small code snippets and getting immediate feedback.
For Instructors
WileyPLUS includes all of the instructor resources found on the companion site,
and more.
WileyPLUS gives you tools for identifying those students who are falling behind,
allowing you to intervene accordingly, without having to wait for them to come to
office hours.
• Practice quizzes for pre-reading assessment, self-quizzing, or additional practice
can be used as-is or modified for your course needs.
• Multi-step laboratory exercises can be used in lab or assigned for extra student
practice.
WileyPLUS simplifies and automates student performance assessment, making
assignments, and scoring student work.
• An extensive set of multiple-choice questions for quizzing and testing have been
developed to focus on skills, not just terminology.
• “Code completion” questions can also be added to online quizzes.
• Solutions to all review and programming exercises are provided.
To order Big Java, Late Objects, with its WileyPLUS course for your students, use ISBN 978-1-11 8-28906-8.
xiv Walkthrough
With WileyPLUS ...
■tUrltonwB. Java ?«
PLUS
Students can read the book online
and take advantage of searching
and cross-linking.
Instructors can assign drill-and-practice
questions to check that students did
their reading and grasp basic concepts.
Teat Hank (Web) 7.107 What la the Err
WlMt it Uie error in Chit code fragment?
C Out of bounds error
C data not initialized
p A twa'dlmpntlonfll array it required
C A catt it required
n thla Array Code fragment?
Question Attempts: 0 of 1 used
lyatae.out .pcintlni M ghee mooch) i
21 Alia toa] a ccopaed *heo oo me itpd a provided a 1
22 How do >ou ceopae the uul of all poaove >010'
23 the an the vaJunof politico and eh »hcn oo math
24 Wba i» wroaf wth the IcOjv k»
boolean found • falaa;
for tint peeitien • 0: ! found tt petition <
r. length n: poaieion**)
Students can practice programming
by filling in small code snippets
and getting immediate feedback.
aalSMOon: Tracing a Loop
Int 1-1;
int s - 0;
while (1 <- 10)
{
* - * ♦ 1;
Local variables
J
1t-
>
That animation dcmomlrstn (ho proem* of land (racing a l«v When you trace a loop, jxmi keep track of
die current hnc of code and the current value* of the variable*. Whenever a variable'* vitae change*, vou
crow out the old value and »twc in the new value Click on the *\<tt* barton k> see the nest traewiy wen.
It H a good idea for vou to predict w hat action mil occur btfurr Inning the bun on Keep clicking the
"NcM holloa until tkic loop CVK*
©
Students can play and replay
dynamic explanations of
concepts and program flow.
ln*truc*ioM
View Problem
► Vlrw/Frllt f odr
Submit To Grmfobook
Fin l ill
Displayed below it the partial code required fer this problem. Complete the cede to make a fully functioning
program that will wive thi* problem by edemg Arecdv in the tent box below. When you ere finished, you may cbefc
'Next' and lebPet will compile end run your code and generate e
grade report. ^
ch04.flv
public das* Numbers
<
Compute* a sum of even integer*
©param a the lower bound (may be odd or even)
©par am a the lower bound (may be odd or even}
©return the turn of e.en mteger* between a and b (induixa).
rtb)
1 Drawing a Spiral
| Write a Dtoqram that draws a spiral, ike this:
public it evenSum{int a
LabRat
Students can watch and listen as the author
solves a problem step-by-step.
| gi«a4i.d'Q^.Hnr(»l, |L *Z. yi).
draws a one from (*1, x2) to (yl. y2).
SUMlel (al. yl) - (too. 1001 Tlwrfhai Iwv Mnv Mfynwrola steroid Inf Uni iwrls foivy Oiaw 40 sevuronO.
Acknowledgments xv
Acknowledgments
Many thanks to Beth Lang Golub, Don Fowley, Elizabeth Mills, Thomas Kulesa,
Wendy Ashenberg, Lisa Gee, Andre Legaspi, Kevin Holm, and John Curley at John
Wiley & Sons, and Vickie Piercey at Publishing Services for their help with this proj¬
ect. An especially deep acknowledgment and thanks goes to Cindy Johnson for her
hard work, sound judgment, and amazing attention to detail.
I am grateful to Jose Cordova, University of Louisiana, Monroe , Rick Giles, Aca¬
dia University, Amitava Karmaker, University of Wisconsin, Stout, Khaled Mansour,
Washtenaw Community College, Patricia McDermott- Wells, Florida International
University, Brent Seales, University of Kentucky, Donald Smith, Columbia College,
and David Woolbright, Columbus State University, for their excellent work on the
supplemental material. Thank you also to Jose-Arturo Mora-Soto, Jesica Rivero-
Espinosa, and Julio-Angel Cano-Romero of the University of Madrid for their con¬
tribution of business exercises.
Many thanks to the individuals who provided feedback, reviewed the manuscript,
made valuable suggestions, and brought errors and omissions to my attention. They
include:
Lynn Aaron, SUNY Rockland
Community College
Karen Arlien, Bismarck State College
Jay Asundi, University of Texas, Dallas
Eugene Backlin, DePaul University
William C. Barge, Trine University
Bruce J. Barton, Suffolk County
Community College
Sanjiv K. Bhatia, University of Missouri,
St. Louis
Anna Bieszczad, California State
University, Channel Islands
Jackie Bird, Northwestern University
Eric Bishop, Northland Pioneer College
Paul Bladek, Edmonds Community
College
Paul Logasa Bogen II, Texas A&M
University
Irene Bruno, George Mason University
Paolo Bucci, Ohio State University
Joe Burgin, College of Southern
Maryland
Robert P. Burton, Brigham Young
University
Leonello Calabresi, University of
Maryland University College
Martine Ceberio, University of Texas,
El Paso
Uday Chakraborty, University of
Missouri, St. Louis
Suchindran Chatterjee, Arizona State
University
Xuemin Chen, Texas Southern
University
Haiyan Cheng, Willamette University
Chakib Chraibi, Barry University
Ta-Tao Chuang, Gonzaga University
Vincent Cicirello, Richard Stockton
College
Mark Clement, Brigham Young
University
Gerald Cohen, St. Joseph’s College
Ralph Conrad, San Antonio College
Dave Cook, Stephen F. Austin State
University
Rebecca Crellin, Community College
of Allegheny County
Leslie Damon, Vermont Technical
College
Geoffrey D. Decker, Northern Illinois
University
Khaled Deeb, Barry University, School
of Adult and Continuing Education
Akshaye Dhawan, Ursinus College
Julius Dichter, University of Bridgeport
Mike Domaratzki, University of
Manitoba
xvi Acknowledgments
Philip Dorin, Loyola Marymount
University
Anthony J. Dos Reis, SUNY New Paltz
Elizabeth Drake, Santa Fe College
Tom Duffy, Norwalk Community
College
Michael Eckmann, Skidmore College
Sander Eller, California State
Polytechnic University, Pomona
Amita Engineer, Valencia Community
College
Dave Evans, Pasadena Community
College
James Factor, Alverno College
Chris Fietkiewicz, Case Western
Reserve University
Terrell Foty, Portland Community
College
Valerie Frear, Daytona State College
Ryan Gar lick, University of North Texas
Aaron Garrett, Jacksonville State
University
Stephen Gilbert, Orange Coast College
Peter van der Goes, Rose State College
Billie Goldstein, Temple University
Michael Gourley, University of Central
Oklahoma
Grigoriy Grinberg, Montgomery
College
Linwu Gu, Indiana University
Sylvain Guinepain, University of
Oklahoma, Norman
Bruce Haft, Glendale Community
College
Nancy Harris, James Madison
University
Allan M. Hart, Minnesota State
University, Mankato
Ric Heishman, George Mason
University
Guy Helmer, Iowa State University
Katherin Herbert, Montclair State
University
Rodney Hoffman, Occidental College
May Hou, Norfolk State University
John Houlihan, Loyola University
Andree Jacobson, University of New
Mexico
Eric Jiang, University of San Diego
Christopher M. Johnson, Guilford
College
Jonathan Kapleau, New Jersey Institute
of Technology
Amitava Karmaker, University of
Wisconsin, Stout
Rajkumar Kempaiah, College of Mount
Saint Vincent
Mugdha Khaladkar, New Jersey
Institute of Technology
Richard Kick, Newbury Park High
School
Julie King, Sullivan University,
Lexington
Samuel Kohn, Touro College
April Kontostathis, Ursinus College
Ron Krawitz, DeVry University
Nat Kumaresan, Georgia Perimeter
College
Debbie Lamprecht, Texas Tech
University
Jian Lin, Eastern Connecticut State
University
Hunter Lloyd, Montana State
University
Cheng Luo, Coppin State University
Kelvin Lwin, University of California,
Merced
Frank Malinowski, Dalton College
John S. Mallozzi, Iona College
Khaled Mansour, Washtenaw
Community College
Kenneth Martin, University of North
Florida
Deborah Mathews,/. Sargeant
Reynolds Community College
Louis Mazzucco, State University of
New York at Cobleskill and
Excelsior College
Drew McDermott, Yale University
Hugh McGuire, Grand Valley State
University
Michael L. Mick, Purdue University,
Calumet
Acknowledgments xvii
Jeanne Milostan, University of
California, Merced
Sandeep Mitra, SUNY Brockport
Michel Mitri, James Madison University
Kenrick Mock, University of Alaska
Anchorage
Namdar Mogharreban, Southern
Illinois University
Shamsi Moussavi, Masshay Community
College
Nannette Napier, Georgia Gwinnett
College
Tony Tuan Nguyen, De Anza College
Michael Ondrasek, Wright State
University
K. Palaniappan, University of Missouri
James Papademas, Oakton Community
College
Gary Parker, Connecticut College
Jody Paul, Metropolitan State College
of Denver
Mark Pendergast, Florida Gulf Coast
University
James T. Pepe, Bentley University
Jeff Pittges, Radford University
Tom Plunkett, Virginia Tech
Linda L. Preece, Southern Illinois
University
Vijay Ramachandran, Colgate
University
Craig Reinhart, California Lutheran
University
Jonathan Robinson, Touro College
Chaman Lai Sabharwal, Missouri
University of Science & Technology
Katherine Saleh, Illinois Central
College
Namita Sarawagi, Rhode Island College
Ben Schafer, University of Northern
Iowa
Walter Schilling, Milwaukee School of
Engineering
Jeffrey Paul Scott, Blackhawk Technical
College
Amon Seagull, NOVA Southeastern
University
Linda Seiter ,John Carroll University
Kevin Seppi, Brigham Young University
Ricky J. Sethi, UCLA, USC ISI, and
DeVry University
Ali Shaykhian, Florida Institute of
Technology
Lai Shimpi, Saint Augustine’s College
Victor Shtern, Boston University
Rahul Simha, George Washington
University
Jeff Six, University of Delaware
Donald W. Smith, Columbia College
Derek Snow, University of Southern
Alabama
Peter Spoerri, Fairfield University
David R. Stampf, Suffolk County
Community College
Peter Stanchev, Kettering University
Ryan Stansifer, Florida Institute of
Technology
Stu Steiner, Eastern Washington
University
Robert Strader, Stephen F. Austin
State University
David Stucki, Otterbein University
Ashok Subramanian, University of
Missouri, St Louis
Jeremy Suing, University of Nebraska,
Lincoln
Dave Sullivan, Boston University
Vaidy Sunderam, Emory University
Hong Sung, University of Central
Oklahoma
Monica Sweat, Georgia Tech University
Joseph Szurek, University of Pittsburgh,
Greensburg
Jack Tan, University of Wisconsin
Cynthia Tanner, West Virginia
University
Russell Tessier, University of
Massachusetts, Amherst
Krishnaprasad Thirunarayan, Wright
State University
Megan Thomas, California State
University, Stanislaus
Timothy Urness, Drake University
Eliana Valenzuela-Andrade, University
of Puerto Rico at Arecibo
XVIII
Acknowledgments
Tammy VanDeGrift, University of
Portland
Philip Ventura, Broward College
David R. Vineyard, Kettering
University
Qi Wang, Northwest Vista College
Jonathan Weissman, Finger Lakes
Community College
Reginald White, Black Hawk
Community College
Ying Xie, Kennesaw State University
Arthur Yanushka, Christian Brothers
University
Chen Ye, University of Illinois, Chicago
Wook-Sung Yoo, Fairfield University
Steve Zale, Middlesex County College
Bahram Zartoshty, California State
University, Northridge
Frank Zeng, Indiana Wesleyan
University
Hairong Zhao, Purdue University
Calumet
Stephen Zilora, Rochester Institute of
Technology
And a special thank you to our class testers:
Eugene Backlin and the students of DePaul University, Loop
Debra M. Duke and the students of J. Sargeant Reynolds Community College
Gerald Gordon and the students of DePaul University, Loop
Mike Gourley and the students of the University of Central Oklahoma
Mohammad Morovati and the students of the College of DuPage
Mutsumi Nakamura and the students of Arizona State University
George Novacky and the students of the University of Pittsburgh
Darrin Rothe and the students of the Milwaukee School of Engineering
Paige Rutner and the students of Georgia Southern University
Narasimha Shashidhar and the students of Sam Houston State University
Mark Sherriff and the students of the University of Virginia
Frank Zeng and the students of Indiana Wesleyan University
CONTENTS
PREFACE v
SPECIAL FEATURES xxvi
chapter 1 INTRODUCTION 1
1.1 Computer Programs 2
1.2 The Anatomy of a Computer 3
l.S The Java Programming Language 5
1.4 Becoming Familiar with Your Programming Environment 8
1.5 Analyzing Your First Program 12
1.6 Errors 15
1.7
Problem Solving: Algorithm Design
16
chapter 2 FUNDAMENTAL DATA TYPES
2.1
Variables 30
2.2
Arithmetic 41
2.3
Input and Output 48
2.4
Problem Solving: First Do It By Hand
57
2.5
Strings 59
CHAPTER 3 DECISIONS 81
5.1 The if Statement 82
5.2 Comparing Numbers and Strings 88
S.S Multiple Alternatives 96
3.4 Nested Branches 100
3.5 Problem Solving: Flowcharts 105
3.6 Problem Solving: Test Cases 108
3.7 Boolean Variables and Operators 111
3.8 Application: Input Validation 116
CHAPTER 4 LOOPS 1 39
4.1 The while Loop 140
4.2 Problem Solving: Hand-Tracing 147
4.3 The for Loop 150
4.4 The do Loop 1 56
4.5 Application: Processing Sentinel Values 158
xx Contents
4.6 Problem Solving: Storyboards 162
4.7 Common Loop Algorithms 165
4.8 Nested Loops 1 72
4.9 Application: Random Numbers and Simulations 176
chapter 5 METHODS 201
5.1 Methods as Black Boxes 202
5.2 Implementing Methods 204
5.3 Parameter Passing 207
5.4 Return Values 210
5.5 Methods Without Return Values 214
5.6 Problem Solving: Reusable Methods 215
5.7 Problem Solving: Stepwise Refinement 218
5.8 Variable Scope 225
5.9 Recursive Methods (Optional) 228
chapter 6 ARRAYS AND ARRAY LISTS 249
6.1 Arrays 250
6.2 The Enhanced for Loop 257
6.3 Common Array Algorithms 258
6.4 Using Arrays with Methods 268
6.5 Problem Solving: Adapting Algorithms 272
6.6 Problem Solving: Discovering Algorithms by Manipulating
Physical Objects 279
6.7 Two-Dimensional Arrays 282
6.8 Array Lists 289
chapter? INPUT/OUTPUT AND EXCEPTION HANDLING 31 7
7. 1 Reading and Writing Text Files 318
7.2 Text Input and Output 323
7.3 Command Line Arguments 330
7.4 Exception Handling 337
7.5 Application: Handling Input Errors 347
chapters OBJECTS AND CLASSES 361
8.1 Object-Oriented Programming 362
8.2 Implementing a Simple Class 364
8.3 Specifying the Public Interface of a Class 367
8.4 Designing the Data Representation 371
Contents xxi
8.5 Implementing Instance Methods 372
8.6 Constructors 375
8.7 Testing a Class 380
8.8 Problem Solving: Tracing Objects 386
8.9 Problem Solving: Patterns for Object Data 388
8.10 Object References 395
8.11 Static Variables and Methods 400
chapter 9 INHERITANCE AND INTERFACES 415
9.1 Inheritance Hierarchies 416
9.2 Implementing Subclasses 420
9.3 Overriding Methods 424
9.4 Polymorphism 430
9.5 Object: The Cosmic Superclass 441
9.6 Interface Types 448
chapter 10 GRAPHICAL USER INTERFACES 465
10.1 Frame Windows 466
10.2 Events and Event Handling 470
10.3 Processing Text Input 481
10.4 Creating Drawings 487
chapter n ADVANCED USER INTERFACES 507
11.1 Layout Management 508
1 1 .2 Choices 510
11.3 Menus 521
1 1 .4 Exploring the Swing Documentation 528
11.5 Using Timer Events for Animations 533
1 1 .6 Mouse Events 536
chapter 12 OBJECT-ORIENTED DESIGN 549
12.1 Classes and Their Responsibilities 550
12.2 Relationships Between Classes 554
12.3 Application: Printing an Invoice 562
12.4 Packages 574
chapter 13 RECURSION 585
13.1 Triangle Numbers Revisited 586
13.2 Problem Solving: Thinking Recursively 590
13.3 Recursive Helper Methods 594
13.4 The Efficiency of Recursion 596
13.5 Permutations 601
13.6 Mutual Recursion 606
13.7 Backtracking 612
chapter 14 SORTING AND SEARCHING 627
14.1 Selection Sort 628
14.2 Profiling the Selection Sort Algorithm 631
1 4.3 Analyzing the Performance of the Selection Sort Algorithm
14.4 Merge Sort 639
14.5 Analyzing the Merge Sort Algorithm 642
14.6 Searching 646
1 4.7 Problem Solving: Estimating the Running Time of an Algorithm
14.8 Sorting and Searching in the Java Library 656
chapter 1 5 THEJAVA COLLECTIONS FRAMEWORK 669
15.1 An Overview of the Collections Framework 670
15.2 Linked Lists 672
1 5.3 Sets 679
15.4 Maps 684
15.5 Stacks, Queues, and Priority Queues 690
15.6 Stack and Queue Applications 693
chapter 16 BASIC DATA STRUCTURES 71 5
16.1 Implementing Linked Lists 714
16.2 Implementing Array Lists 728
16.3 Implementing Stacks and Queues 733
16.4 Implementing a Hash Table 739
chapter 17 TREE STRUCTURES 759
17.1 Basic Tree Concepts 760
17.2 Binary Trees 764
17.3 Binary Search Trees 769
Contents xxiii
I
I
17.4 Tree Traversal 778
17.5 Red-Black Trees 784
17.6 Heaps 791
17.7 The Heapsort Algorithm 802
chapter 1 8 GENERIC CLASSES 817
18.1 Generic Classes and Type Parameters 818
18.2 Implementing Generic Types 819
18.3 Generic Methods 823
18.4 Constraining Type Parameters 825
18.5 Type Erasure 829
chapter 19 STREAMS AND BINARY INPUT/OUTPUT 839
19.1 Readers, Writers, and Streams 840
19.2 Binary Input and Output 841
19.3 Random Access 845
19.4 Object Streams 851
CHAPTER 20
MULTITHREADING
(WEB ONLY) ©
20.1 Running Threads
20.2 Terminating Threads
20.3 Race Conditions
20.4 Synchronizing Object Access
20.5 Avoiding Deadlocks
20.6 Application: Algorithm Animation
CHAPTER 21
INTERNET NETWORKING
(WEB ONLY) ©
21.1 The Internet Protocol
21 .2 Application Level Protocols
21.3 A Client Program
21.4 A Server Program
21.5 URL Connections
CHAPTER 22
RELATIONAL DATABASES
(WEB ONLY) ©
22.1 Organizing Database Information
22.2 Queries
22.3 Installing a Database
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
xxiv Contents
22.4 Database Programming in Java
22.5 Application: Entering an Invoice
CHAPTER 23
XML
(WEB ONLY) ©
23.1 XML Tags and Documents
23.2 Parsing XML Documents
23.3 Creating XML Documents
23.4 Validating XML Documents
CHAPTER 24
WEB APPLICATIONS
(WEB ONLY) ©
i
24.1 The Architecture of a Web Application
24.2 The Architecture of aJSL Application
24.3 JavaBeans Components
24.4 Navigation Between Pages
24.5 JSL Components
24.6 A Three-Tier Application
APPENDICES
APPENDIX A
APPENDIX B
APPENDIX C
APPENDIX D
APPENDIX E
APPENDIX F
APPENDIX C
APPENDIX H
APPENDIX I
APPENDIXJ
APPENDIX K
APPENDIX L
THE BASIC LATIN AND LATIN-1 SUBSETS OF UNICODE
JAVA OPERATOR SUMMARY 865
JAVA RESERVED WORD SUMMARY 867
THE JAVA LIBRARY 869
JAVA SYNTAX SUMMARY 913
HTML SUMMARY 925
TOOL SUMMARY 931
JAVADOC SUMMARY 933
NUMBER SYSTEMS 935
BIT AND SHIFT OPERATIONS 941
UML SUMMARY 943
JAVA LANGUAGE CODING GUIDELINES 947
861
GLOSSARY 955
INDEX 969
CREDITS 1011
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
Contents xxv
ALPHABETICAL LIST OF SYNTAX BOXES
Arrays 251
Array Lists 290
Assignment 34
Cast 44
Catching Exceptions 341
Comparisons 89
Constant Declaration 35
Constructor with Superclass Initializer 430
Constructors 376
Declaring a Generic Class 820
Declaring a Generic Method 824
for Statement 152
if Statement 84
Input Statement 49
Instance Methods 373
Instance Variable Declaration 365
Interface Types 449
Java Program 1 3
Static Method Declaration 205
Subclass Declaration 422
The Enhanced for Loop 258
The finally Clause 344
The i nstanceof Operator 445
The throws Clause 343
Throwing an Exception 338
Two-Dimensional Array Declaration 283
while Statement 141
Variable Declaration 31
xxvi Special Features
- 1
l£& HowTos
and
*j I f
- 1
chapter!
^ Common
Errors
. _ ii _
_ A
+
Worked Examples >
i
Introduction
Omitting Semicolons
14
Describing an Algorithm
Misspelling Words
16
with Pseudocode
20
Compiling and Running
a Program
©
Writing an Algorithm for
Tiling a Floor
©
Dividing Household Expenses
©
2
Fundamental
Using Undeclared or
Using Integer Division
©
Data Types
Uninitialized Variables
37
Carrying out Computations
54
Overflow
38
Computing the Cost
Roundoff Errors
38
of Stamps
©
Unintended Integer Division
46
Computing Travel Time
©
Unbalanced Parentheses
46
Computing Distances on Earth ©
3
Decisions
A Semicolon After the
if Condition
Implementing an
86 if Statement
Exact Comparison of
Floating-Point Numbers
Using == to Compare Strings
The Dangling else Problem
Combining Multiple
Relational Operators
Confusing && and |
Conditions
Extracting the Middle
91 Computing the Plural of
92 an English Word
1 04 The Genetic Code
113
114
93
o
o
©
4 Loops
Don’t Think “Are We
There Yet?"
Infinite Loops
Off-by-One Errors
Evaluating a Cell Phone Plan ©
144 Writing a Loop 169
'45 Credit Card Processing ©
145 Manipulating the Pixels
in an Image ©
Drawing a Spiral ©
5 Methods Trying to Modify Arguments 209 Implementing a Method 212
Missing Return Value 212 Generating Random
Passwords ©
Calculating a Course Grade ©
Debugging ©
Thinking Recursively 231
Fully Justified Text ©
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
Special Features xxvii
Backup Copies 11 The ENIAC and the Dawn
ofComputing 5
Choose Descriptive Variable
Names 38
Do Not Use Magic Numbers 39
Spaces in Expressions 47
Use the API Documentation 53
Numeric Types in Java 39
Big Numbers 40
Combining Assignment
and Arithmetic 47
Instance Methods and
Static Methods 64
Using Dialog Boxes for Input
and Output 65
The Pentium
Floating-Point Bug 48
International Alphabets
and Unicode 66
Brace Layout
86
The Conditional Operator
87
The Denver Airport
Always Use Braces
86
Lexicographic Ordering
Luggage Handling System
95
Tabs
87
of Strings
92
Artificial Intelligence
119
Avoid Duplication in Branches 88
The switch Statement
99
Eland-Tracing
103
Enumeration Types
105
Make a Schedule and Make
Logging
110
Time for Unexpected
Short-Circuit Evaluation
Problems
109
of Boolean Operators
114
De Morgan’s Law
115
Use for Loops for Their
The Loop-and-a-Elalf Problem
The First Bug
146
Intended Purpose Only
1 55
and the break Statement
160
Software Piracy
182
Choose Loop Bounds That
Redirection of Input
Match Your Task
1 55
and Output
161
Count Iterations
1 56
Drawing Graphical Shapes
179
Method Comments
207
The Explosive Growth of
Do Not Modify Parameter
Personal Computers
232
Variables
209
Keep Methods Short
223
Tracing Methods
223
Stubs
224
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
xxviii Special Features
CHAPTER
6 Arrays and Array Lists
^ Common
i v Errors
_ _
Bounds Errors
255
Uninitialized Arrays
255
Underestimating the Size
of a Data Set
267
Length and Size
299
fM HowT°s
and
Worked Examples
Working with Arrays 275
Rolling the Dice ©
Removing Duplicates from
an Array ©
A World Population Table ©
Came of Life ©
7
Input/Output and Backslashes in File Names
Exception Handling Constructing a Scanner with
a Stri ng
321 Computing a Document’s
Readability
32 1 Processing Text Files
Analyzing Baby Names
Detecting Accounting Fraud
o
333
©
©
8 Objects and Classes
Forgetting to Initialize
Object References
in a Constructor 378
Trying to Call a Constructor 379
Declaring a Constructor
as void 379
Implementing a Class 382
Implementing a
Bank Account Class ©
Paying Off a Loan ©
Modeling a Robot Escaping
from a Maze ©
9 Inheritance and
Replicating Instance Variables
Developing an
Interfaces
from the Superclass
423
Inheritance Flierarchy
436
Confusing Super- and
Implementing an
Subclasses
424
Employee Hierarchy for
Accidental Overloading
428
Payroll Processing
©
Forgetting to Use super
Building a Discussion Board
©
When Invoking a
Superclass Method
429
Drawing Geometric Shapes
©
Don’t Use Type Tests
446
Forgetting to Declare Implement-
ing Methods as Public
453
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
Special Features xxix
Use Arrays for Sequences
Sorting with the Java Library 267 An Early Internet Worm
of Related Items
256 Binary Search
267
Reading Exception Reports
274 Methods with a Variable
Number of Parameters
272
Two-Dimensional Arrays
with
Variable Row Lengths
288
Multidimensional Arrays
The Diamond Syntax in
289
Java 7
299
Throw Early, Catch Late
345
Reading Web Pages
321
Encryption Algorithms
336
Do Not Squelch Exceptions
345
File Dialog Boxes
321
The Ariane Rocket Incident
347
Do Not Use catch and fi nal 1 y
Reading and Writing
in the Same try Statement
346
Binary Data
322
Regular Expressions
Automatic Resource
330
Management in Java 7
346
All Data Variables Should
The javadoc Utility
370
Electronic Voting Machines
394
Be Private; Most Methods
Overloading
380
Open Source and
Should Be Public
374
Calling One Constructor
Free Software
402
from Another
399
Use a Single Class for Variation
in Values, Inheritance for
Variation in Behavior 420
Calling the Superclass
Constructor 429
Dynamic Method Lookup and
the Implicit Parameter 433
Abstract Classes 434
Final Methods and Classes 435
Protected Access 436
Inheritance and the
toString Method 446
Inheritance and the
equals Method 447
Constants in Interfaces 453
Function Objects 454
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
xxx Special Features
CHAPTER
10 Graphical User
Interfaces
Common
i.A \ Errors
Modifying Parameter Types
in the Implementing
Method 478
Forgetting to Attach
a Listener 478
Forgetting to Repaint 496
By Default, Components Fiave
Zero Width and Height 497
# HowTos
and
Worked Examples
Drawing Graphical Shapes
Coding a Bar Chart Creator
Solving Crossword Puzzles
497
©
o
1 1 Advanced User
Interfaces
Laying Out a User Interface
Programming a Working
Calculator
Adding Mouse and
Keyboard Support to the
Bar Chart Creator
Designing a Baby
Naming Program
518
©
o
o
12 Object-Oriented Design
IB
Recursion
Infinite Recursion
Using CRC Cards and
UML Diagrams in
Program Design
558
Simulating an Automatic
Teller Machine
©
Finding Files
©
Towers of Hanoi
©
14 Sorting and Searching The compareTo Method Can Enhancing the Insertion Sort
Return Any Integer, Algorithm ©
Not Just -1 , 0, and 1 658
15 The Java Collections
Framework
Choosing a Collection 686
Word Frequency ©
Simulating a Queue of
Waiting Customers ©
Building aTable of Contents ©
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
Special Features xxxi
Don’t Use a Frame Adding the mai n Method to the
as a Listener 478 Frame Class 470
Local Inner Classes 479
Anonymous Inner Classes 480
Use a GUI Builder 520 Keyboard Events 539
Event Adapters 540
Make Parallel Arrays into Attributes and Methods in
Arrays of Objects 561 UML Diagrams 559
Consistency 562 Multiplicities 560
Aggregation, Association,
and Composition 560
The Limits of Computation 604
Oh, Omega, and Theta
636
The First Programmer
650
Insertion Sort
637
The Quicksort Algorithm
644
The Parameterized
Comparable Interface
658
The Comparator Interface
659
Use Interface References to
Hash Functions
688
Standardization
678
Manipulate Data Structures 683
Reverse Polish Notation
701
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
xxxii Special Features
' - 1
r'%. Common
Errors
H x-
<$& HowTos
',xBr and
Worked Examples
16 Basic Data Structures
Implementing a
Doubly-Linked List ©
17 Tree Structures
Building a Huffman Tree ©
Implementing a
Red-Black Tree ©
1 8 Generic Classes
Cenericity and Inheritance 827
The Array Store Exception 827
Using Generic Types in a
Static Context 832
Making a Generic Binary
Search Tree Class ©
19 Streams and Binary
Input/Output
Negative byte Values 845
Choosing a File Format 854
20 Multithreading
(WEB ONLY) ©
Calling awai t Without
Calling signalAll ©
Calling signalAll Without
Locking the Object ©
21 Internet Networking
(WEB ONLY) ©
Designing Client/Server
Programs ©
22 Relational Databases
(WEB ONLY) ©
Joining Tables Without
Specifying a Link Condition ©
Constructing Queries from
Arbitrary Strings ©
Programming a Bank
Database ©
23 XML
(WEB ONLY) ©
XML Elements Describe
Objects, Not Classes ©
Designing an XML
Document Format ©
Writing an XML Document ©
Writing a DTD ©
24 Web Applications
(WEB ONLY) ©
Designing a Managed Bean ©
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
Special Features xxxiii
Static Classes 728
Open Addressing 747
Wildcard Types 828
Reflection 832
Thread Pools ©
Object Locks and
Synchronized Methods ©
The Java Memory Model ©
Use High-Level Libraries ©
Use the Runnable Interface ©
Check for Thread Interruptions
in the run Method
of a Thread ©
Embedded Systems ©
Stick with the Standard
©
Primary Keys and Indexes
Avoid Unnecessary Data
Transactions
Replication
©
Object-Relational Mapping
Don’t Replicate Columns
in a Table
©
Don’t Hardwire Database
Connection Parameters
into Your Program
©
Let the Database Do the Work
©
© Databases and Privacy
©
©
Prefer XML Elements over
Attributes
Avoid Children with Mixed
Elements and Text
Schema Languages
® Other XML Technologies
©
© Word Processing and
q Typesetting Systems
Grammars, Parsers, and
Compilers
o
o
Session State and Cookies ©
AJAX ©
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
CHAPTER
1
INTRODUCTION
CHAPTER COALS
To learn about computers
and programming
To compile and run your first Java program
To recognize compile-time and run-time errors
To describe an algorithm with pseudocode
CHAPTER CONTENTS
1.1 COMPUTER PROGRAMS 2
1.2 THE ANATOMY OF A COMPUTER 3
Random Fact 1.1: The ENIAC and the Dawn of
Computing 5
1.3 THE JAVA PROGRAMMING
LANGUAGE 5
1 .4 BECOMING FAMILIAR WITH YOUR
PROGRAMMING ENVIRONMENT 8
Programming Tip 1.1: Backup Copies 1 1
Video Example 1.1: Compiling and Running
a Program ©
1.5 ANALYZING YOUR FIRST
PROGRAM 1 2
Syntax 1.1: Java Program 1 3
Common Error 1 .1 : Omitting Semicolons 14
1.6 ERRORS 15
Common Error 1 .2: Misspelling Words 16
1.7 PROBLEMSOLVING:
ALGORITHM DESIGN 16
HowTo 1.1: Describing an Algorithm with
Pseudocode 20
Worked Example 1.1: Writing an Algorithm for
Tiling a Floor ©
Video Example 1.2: Dividing Household
Expenses ©
Just as you gather tools, study a project, and make a plan for
tackling it, in this chapter you will gather up the basics you
need to start learning to program. After a brief introduction
to computer hardware, software, and programming in
general, you will learn how to write and run your first
Java program. You will also learn how to diagnose and
fix programming errors, and how to use pseudocode to
describe an algorithm — a step-by-step description of how
to solve a problem — as you plan your computer programs.
1.1 Computer Programs
Computers execute
very basic
instructions in
rapid succession.
A computer program
is a sequence
of instructions
and decisions.
Programming is the
act of designing and
implementing
computer programs.
You have probably used a computer for work or fun. Many people use computers
for everyday tasks such as electronic banking or writing a term paper. Computers are
good for such tasks. They can handle repetitive chores, such as totaling up numbers
or placing words on a page, without getting bored or exhausted.
The flexibility of a computer is quite an amazing phenomenon. The same machine
can balance your checkbook, lay out your term paper, and play a game. In contrast,
other machines carry out a much narrower range of tasks; a car drives and a toaster
toasts. Computers can carry out a wide range of tasks because they execute different
programs, each of which directs the computer to work on a specific task.
The computer itself is a machine that stores data (numbers, words, pictures), inter¬
acts with devices (the monitor, the sound system, the printer), and executes programs.
A computer program tells a computer, in minute detail, the sequence of steps that are
needed to fulfill a task. The physical computer and peripheral devices are collectively
called the hardware. The programs the computer executes are called the software.
Today’s computer programs are so sophisticated that it is hard to believe that they
are composed of extremely primitive instructions. A typical instruction may be one
of the following:
• Put a red dot at a given screen position.
• Add up two numbers.
• If this value is negative, continue the program at a certain instruction.
The computer user has the illusion of smooth interaction because a program contains
a huge number of such instructions, and because the computer can execute them at
great speed.
The act of designing and implementing computer programs is called program¬
ming. In this book, you will learn how to program a computer —that is, how to direct
the computer to execute tasks.
To write a computer game with motion and sound effects or a word processor
that supports fancy fonts and pictures is a complex task that requires a team of many
highly-skilled programmers. Your first programming efforts will be more mundane.
The concepts and skills you learn in this book form an important foundation, and
you should not be disappointed if your first programs do not rival the sophisticated
software that is familiar to you. Actually, you will find that there is an immense thrill
even in simple programming tasks. It is an amazing experience to see the computer
precisely and quickly carry out a task that would take you hours of drudgery, to
2
1.2 The Anatomy of a Computer 3
make small changes in a program that lead to immediate improvements, and to see the
computer become an extension of your mental powers.
1 . What is required to play music on a computer?
2. Why is a CD player less flexible than a computer?
3. What does a computer user need to know about programming in order to play a
video game?
1 .2 The Anatomy of a Computer
The central
processing unit (CPU)
performs program
control and
data processing.
Storage devices
include memory and
secondary storage.
To understand the programming process, you need to have a rudimentary under¬
standing of the building blocks that make up a computer. We will look at a personal
computer. Larger computers have faster, larger, or more powerful components, but
they have fundamentally the same design.
At the heart of the computer lies the central processing unit (CPU) (see Figure
1). The inside wiring of the CPU is enormously complicated. For example, the Intel
Core processor (a popular CPU for personal computers at the time of this writing) is
composed of several hundred million structural elements, called transistors.
The CPU performs program control and data processing. That is, the CPU locates
and executes the program instructions; it carries out arithmetic operations such as
addition, subtraction, multiplication, and division; it fetches data from external mem¬
ory or devices and places processed data into storage.
There are two kinds of storage. Primary storage is made from memory chips:
electronic circuits that can store data, provided they are supplied with electric power.
Secondary storage, usually a hard disk (see Figure 2), provides slower and less
expensive storage that persists without electricity. A hard disk consists of rotating
platters, which are coated with a magnetic material, and read/ write heads, which can
detect and change the magnetic flux on the platters.
The computer stores both data and programs. They are located in secondary stor¬
age and loaded into memory when the program starts. The program then updates the
data in memory and writes the modified data back to secondary storage.
Figure 1 Central Processing Unit
Figure 2 A Hard Disk
4 Chapter 1 Introduction
a
Monitor
00
Speakers
Internet
Figure 3 Schematic Design of a Personal Computer
To interact with a human user, a computer requires peripheral devices. The com¬
puter transmits information (called output) to the user through a display screen,
speakers, and printers. The user can enter information (called input) for the computer
by using a keyboard or a pointing device such as a mouse.
Some computers are self-contained units, whereas others are interconnected
through networks. Through the network cabling, the computer can read data and
programs from central storage locations or send data to other computers. To the user
of a networked computer, it may not even be obvious which data reside on the com¬
puter itself and which are transmitted through the network.
Figure 3 gives a schematic overview of the architecture of a personal computer.
Program instructions and data (such as text, numbers, audio, or video) are stored on
the hard disk, on a compact disk (or DVD), or elsewhere on the network. When a
program is started, it is brought into memory, where the CPU can read it. The CPU
reads the program one instruction at a time. As directed by these instructions, the
CPU reads data, modifies it, and writes it back to memory or the hard disk. Some pro¬
gram instructions will cause the CPU to place dots on the display screen or printer or
to vibrate the speaker. As these actions happen many times over and at great speed,
the human user will perceive images and sound. Some program instructions read user
input from the keyboard or mouse. The program analyzes the nature of these inputs
and then executes the next appropriate instruction.
4. Where is a program stored when it is not currently running?
5. Which part of the computer carries out arithmetic operations, such as addition
and multiplication?
Now you can try these exercises at the end of the chapter: R1.2, R1.3.
1 .3 The Java Programming Language 5
Random Fact 1.1 The ENIAC and the Dawn of Computing
The ENIAC (electronic
numerical integrator
and computer) was
the first usable electronic computer. It
was designed by J. Presper Eckert and
John Mauchly at the University of Penn¬
sylvania and was completed in 1 946 —
two years before transistors were
invented. The computer was housed in
a large room and consisted of many
cabinets containing about 18,000 vac¬
uum tubes (see Figure 4). Vacuum
tubes burned out at the rate of several
tubes per day. An attendant with a
shopping cart full of tubes constantly
made the rounds and replaced defec¬
tive ones. The computer was pro¬
grammed by connecting wires on pan¬
els. Each wiring configuration would
set up the computer for a particular
problem. To have the computer work
on a different problem, the wires had to
be replugged.
Work on the ENIAC was supported
by the U.S. Navy, which was interested
in computations of ballistic tables that
would give the trajectory of a projec¬
tile, depending on the wind resistance,
initial velocity, and atmospheric con¬
ditions. To compute the trajectories,
one must find the numerical solu¬
tions of certain differential equations;
hence the name “numerical integra¬
tor". Before machines like the ENIAC
were developed, humans did this kind
of work, and until the 1 950s the word
“computer” referred to these people.
The ENIAC was later used for peace¬
ful purposes, such as the tabulation of
U.S. Census data.
Figure 4 The ENIAC
1.3 The Java Programming Language
In order to write a computer program, you need
to provide a sequence of instructions that the CPU
can execute. A computer program consists of a large
number of simple CPU instructions, and it is tedious
and error-prone to specify them one by one. For that
reason, high-level programming languages have
been created. In a high-level language, you specify
the actions that your program should carry out. A
compiler translates the high-level instructions into
the more detailed instructions required by the CPU.
Many different programming languages have been
designed for different purposes.
In 1991, a group led by James Gosling and Patrick
Naughton at Sun Microsystems designed a program¬
ming language, code-named “Green”, for use in
James Gosling
6 Chapter 1 Introduction
Java was originally
designed for
programming
consumer devices,
but it was first
successfully used
to write Internet
applets.
Java was designed to
be safe and portable,
benefiting both
Internet users
and students.
consumer devices, such as intelligent television “set-top” boxes. The language was
designed to be simple, secure, and usable for many different processor types. No cus¬
tomer was ever found for this technology.
Gosling recounts that in 1994 the team realized, “We could write a really cool
browser. It was one of the few things in the client/server mainstream that needed
some of the weird things we’d done: architecture neutral, real-time, reliable, secure.”
Java was introduced to an enthusiastic crowd at the SunWorld exhibition in 1995,
together with a browser that ran applets— Java code that can be located anywhere on
the Internet. Figure 5 shows a typical example of an applet.
Since then, Java has grown at a phenomenal rate. Programmers have embraced the
language because it is easier to use than its closest rival, C++. In addition, Java has a
rich library that makes it possible to write portable programs that can bypass pro¬
prietary operating systems — a feature that was eagerly sought by those who wanted
to be independent of those proprietary systems and was bitterly fought by their ven¬
dors. A “micro edition” and an “enterprise edition” of the Java library allow Java
programmers to target hardware ranging from smart cards and cell phones to the
largest Internet servers.
Because Java was designed for the Internet, it has two attributes that make it very
suitable for beginners: safety and portability.
The safety features of the Java language make it possible to run Java programs in
a browser without fear that they might attack your computer. As an added benefit,
these features also help you to learn the language faster. When you make an error that
results in unsafe behavior, you receive an accurate error report.
The other benefit of Java is portability. The same Java program will run, without
change, on Windows, UNIX, Linux, or Macintosh. In order to achieve portability,
the Java compiler does not translate Java programs directly into CPU instructions.
Instead, compiled Java programs contain instructions for the Java virtual machine,
Figure 5 An Applet for Visualizing Molecules Running in
a Browser Window (http://jmol.sourceforge.net/)
1 .3 The Java Programming Language 7
Java programs are
distributed as
instructions for a
virtual machine,
making them
platform-
independent.
Java has a very large
library. Focus on
learning those parts
of the library that
you need for your
programming
projects.
a program that simulates a real CPU. Portability is another benefit for the beginning
student. You do not have to learn how to write programs for different platforms.
At this time, Java is firmly established as one of the most important languages for
general-purpose programming as well as for computer science instruction. However,
although Java is a good language for beginners, it is not perfect, for three reasons.
Because Java was not specifically designed for students, no thought was given
to making it really simple to write basic programs. A certain amount of technical
machinery is necessary in Java to write even the simplest programs. This is not a prob¬
lem for professional programmers, but it can be a nuisance for beginning students. As
you learn how to program in Java, there will be times when you will be asked to be
satisfied with a preliminary explanation and wait for more complete detail in a later
chapter.
Java has been extended many times during its life — see Table 1. In this book, we
assume that you have Java version 5 or later.
Finally, you cannot hope to learn all of Java in one course. The Java language itself
is relatively simple, but Java contains a vast set of library packages that are required
to write useful programs. There are packages for graphics, user-interface design,
cryptography, networking, sound, database storage, and many other purposes. Even
expert Java programmers cannot hope to know the contents of all of the packages —
they just use those that they need for particular projects.
Using this book, you should expect to learn a good deal about the Java language
and about the most important packages. Keep in mind that the central goal of this
book is not to make you memorize Java minutiae, but to teach you how to think
about programming.
Table 1 Java Versions
Version
Year
Important New Features
1.0
1996
1.1
1997
Inner classes
1.2
1998
Swing, Collections framework
1.3
2000
Performance enhancements
1.4
2002
Assertions, XML support
5
2004
Generic classes, enhanced for loop, auto-boxing, enumerations, annotations
6
2006
Library improvements
7
2011
Small language changes and library improvements
6. What are the two most important benefits of the Java language?
7. How long does it take to learn the entire Java library?
Practice It Now you can try this exercise at the end of the chapter: R1 .5.
8 Chapter 1 Introduction
1.4 Becoming Familiar with Your
Programming Environment
Set aside some time
to become familiar
with the
programming
environment that
you will use for your
class work.
An editor is a
program for entering
and modifying text,
such as a
Java program.
Many students find that the tools they need as programmers are very different from
the software with which they are familiar. You should spend some time making your¬
self familiar with your programming environment. Because computer systems vary
widely, this book can only give an outline of the steps you need to follow. It is a good
idea to participate in a hands-on lab, or to ask a knowledgeable friend to give you a
tour.
Step 1 Start the Java development environment.
Computer systems differ greatly in this regard. On many computers there is an inte¬
grated development environment in which you can write and test your programs.
On other computers you first launch an editor, a program that functions like a word
processor, in which you can enter your Java instructions; you then open a console
window and type commands to execute your program. You need to find out how to
get started with your environment.
Step 2 Write a simple program.
The traditional choice for the very first program in a new programming language is
a program that displays a simple greeting: “Hello, World!”. Let us follow that tradi¬
tion. Here is the “Hello, World!” program in Java:
public class HelloPrinter
{
public static void main(String[] args)
{
System. out. println ("Hello, World! ") ;
}
}
We will examine this program in the next section.
No matter which programming environment you use, you begin your activity by
typing the program statements into an editor window.
Create a new file and call it HelloPrinter. java, using the steps that are appropriate
for your environment. (If your environment requires that you supply a project name
in addition to the file name, use the name hello for the project.) Enter the program
instructions exactly as they are given above. Alternatively, locate the electronic copy
in this book’s companion code and paste it into your editor.
m [Terminal
1- □ X 1
1 file £dil View Iwrniridl Help
a
/JavaForEveryone$ cd ch01/hello/
/JavaForEveryone/ch01/hello$ javac HelloPrinter. java
/JavaForEvervone/ch01/hello$ java HelloPrinter
Bello, Wo rlcTQ
/JavaForEveryone/ch01/hello$ |
Figure 6 Running the HelloPrinter Program in a Console Window
1.4 Becoming Familiar with Your Programming Environment 9
Figure 7
Running the
HelloPrinter
Program in an
Integrated
Development
Environment
fr- [java - hello/src/HelloPrinter.java - Eclipse Platform _ !□ |X |
File Edit Refactor Source Navigate Search Project Prolog Bun Window Help
J © : © * o - q,- <# « J & <£■ 4>~ b
•? [j sn - i - ^
3tJJava
Java is case sensitive.
You must be careful
about distinguishing
between upper- and
lowercase letters.
The Java compiler
translates source
code into class files
that contain
instructions for the
Java virtual machine
As you write this program, pay careful attention to the various symbols, and keep
in mind that Java is case sensitive. You must enter upper- and lowercase letters exactly
as they appear in the program listing. You cannot type MAIN or Pri ntLn. If you are not
careful, you will run into problems — see Common Error 1 .2 on page 16.
Step 3 Run the program.
The process for running a program depends greatly on your programming environ¬
ment. You may have to click a button or enter some commands. When you run the
test program, the message
Hello, World!
will appear somewhere on the screen (see Figures 6 and 7).
In order to run your program, the Java compiler translates your source code (that
is, the statements that you wrote) into class files. (A class file contains instructions for
the Java virtual machine.) After the compiler has translated your program into virtual
machine instructions, the virtual machine executes them. Figure 8 summarizes the
process of creating and running a Java program. In some programming environments,
Editor
Source File
Compiler
Class files
Virtual
y
y
Machine
/ i
§ \
Figure 8 From Source Code to Running Program
Running
Program
10 Chapter 1 Introduction
Compilation Process
i in
the compiler and virtual machine are essentially invisible to the programmer— they
are automatically executed whenever you ask to run a Java program. In other envi¬
ronments, you need to launch the compiler and virtual machine explicitly.
Step 4 Organize your work.
As a programmer, you write programs, try them out, and improve them. You store
your programs in files. Files are stored in folders or directories. A folder can contain
files as well as other folders, which themselves can contain more files and folders (see
Figure 9). This hierarchy can be quite large, and you need not be concerned with all
of its branches. However, you should create folders for organizing your work. It is
a good idea to make a separate folder for your programming class. Inside that folder,
make a separate folder for each program.
Some programming environments place your programs into a default location if
you don’t specify a folder yourself. In that case, you need to find out where those files
are located.
Be sure that you understand where your files are located in the folder hierarchy.
This information is essential when you submit files for grading, and for making
backup copies (see Programming Tip 1.1).
chOl
T & section_4
_ HelloPrinter.java
T (lj section_5
_ PrintTester.java
T & section_6
_ Errorl.java
_ Error2.java
_ Error3.java
ftch02
T how_to_l
[_ VendingMachine.java
T & sectionl
_ Volumel.java
T L* section_2
_ Price.java
T & section_3
Volume2.java
T & section_4
_ Tiles.java
T & section_5
Ql Initials.java
Figure 9 A Folder Hierarchy
1.4 Becoming Familiar with Your Programming Environment 11
Practice It
8. Where is the HeYloPrinter . java file stored on your computer?
9. What do you do to protect yourself from data loss when you work on program¬
ming projects?
Now you can try this exercise at the end of the chapter: R1.6.
Programming Tip 1 .1
4
Backup Copies
You will spend many hours creating and improving Java pro¬
grams. It is easy to delete a file by accident, and occasionally files
are lost because of a computer malfunction. Retyping the contents
of lost files is frustrating and time-consuming. It is therefore cru¬
cially important that you learn how to safeguard files and get in
the habit of doing so before disaster strikes. Backing up files on a
memory stick is an easy and convenient storage method for many
people. Another increasingly popular form of backup is Internet
file storage. Here are a few pointers to keep in mind:
• Back up often. Backing up a file takes only a few seconds, and you will hate yourself if you
have to spend many hours recreating work that you could have saved easily. I recommend
that you back up your work once every thirty minutes.
• Rotate backups. Use more than one directory for backups, and
rotate them. That is, first back up onto the first directory. Then
back up onto the second directory. Then use the third, and then
go back to the first. That way you always have three recent
backups. If your recent changes made matters worse, you can
then go back to the older version.
• Pay attention to the backup direction. Backing up involves copying files from one place to
another. It is important that you do this right— that is, copy from your work location to
the backup location. If you do it the wrong way, you will overwrite a newer file with an
older version.
• Check your backups once in a while. Double-check that your backups are where you think
they are. There is nothing more frustrating than to find out that the backups are not there
when you need them.
• Relax, then restore. When you lose a file and need to restore it from a backup, you are
likely to be in an unhappy, nervous state. Take a deep breath and think through the
recovery process before you start. It is not uncommon for an agitated computer user to
wipe out the last backup when trying to restore a damaged file.
Develop a strategy
for keeping backup
copies of your
work before
disaster strikes.
VIDEO EXAMPLE 1 .1
Compiling and Running a Program
fWILEYO
rPLUS
This Video Example shows how to compile and run a simple Java
program.
12 Chapter 1 Introduction
1.5 Analyzing Your First Program
In this section, we will analyze the first Java program in detail. Here again is the
source code:
section_5/HelloPrinter.java
1 public class HelloPrinter
2 {
public static void main(String[] args)
4 {
System. out. println("Hello, World! );
6 }
7 }
Classes are the
fundamental
building blocks of
Java programs.
Every Java
application contains
a class with a main
method. When the
application starts,
the instructions in
the main method
are executed.
Each class contains
declarations of
methods. Each
method contains
a sequence
of instructions.
The line
public class HelloPrinter
indicates the declaration of a class called HelloPrinter.
Every Java program consists of one or more classes. Classes are the fundamental
building blocks of Java programs. You will have to wait until Chapter 8 for a full
explanation of classes.
The word public denotes that the class is usable by the “public”. You will later
encounter private features.
In Java, every source file can contain at most one public class, and the name of the
public class must match the name of the file containing the class. For example, the
class HelloPri nter must be contained in a file named HelloPri nter . java.
The construction
public static void main(String[] args)
{
}
declares a method called main. A method contains a collection of programming
instructions that describe how to carry out a particular task. Every Java application
must have a main method. Most Java programs contain other methods besides main,
and you will see in Chapter 5 how to write other methods.
The term static is explained in more detail in Chapter 8, and the meaning of
String [] args is covered in Chapter 7. At this time, simply consider
public class ClassName
{
public static void main(String[] args)
{
}
}
as a part of the “plumbing” that is required to create a Java program. Our first pro¬
gram has all instructions inside the mai n method of the class.
The mai n method contains one or more instructions called statements. Each state¬
ment ends in a semicolon ( ; ). When a program runs, the statements in the mai n method
are executed one by one.
1.5 Analyzing Your First Program IB
Syntax 1. Java Program
Every Java program
contains a mai n method
with this header.
The statements inside the
mai n method are executed
when the program runs.
Every program contains at least one class.
Choose a class name that describes
the program action.
public
{
class HelloPrinter
public static void main(String[] args)
{
System. out . print! n("Hello, World ! ") ;
’ /
Each statement
ends in a semicolon.
See page 14.
Be sure to match the
opening and closing braces.
Replace this
statement when you
write your own
programs.
A method is called
by specifying the
method and
its arguments.
A string is a sequence
of characters
enclosed in
quotation marks.
In our example program, the mai n method has a single statement:
System. out. println ("Hello, World! ") ;
This statement prints a line of text, namely “Hello, World! ”. In this statement, we call
a method which, for reasons that we will not explain here, is specified by the rather
long name System. out. println.
We do not have to implement this method — the programmers who wrote the Java
library already did that for us. We simply want the method to perform its intended
task, namely to print a value.
Whenever you call a method in Java, you need to specify
1 . The method you want to use (in this case, System. out. println).
2. Any values the method needs to carry out its task (in this case, "Hello, World! ").
The technical term for such a value is an argument. Arguments are enclosed in
parentheses. Multiple arguments are separated by commas.
A sequence of characters enclosed in quotation marks
"Hello, World!"
is call ed a string. You must enclose the contents of the string inside quotation marks
so that the compiler knows you literally mean "Hello, World!". There is a reason for
this requirement. Suppose you need to print the word main. By enclosing it in quota¬
tion marks, "main", the compiler knows you mean the sequence of characters main,
not the method named mai n. The rule is simply that you must enclose all text strings
in quotation marks, so that the compiler considers them plain text and does not try to
interpret them as program instructions.
You can also print numerical values. For example, the statement
System. out. println (3 + 4);
evaluates the expression 3+4 and displays the number 7.
14 Chapter 1 Introduction
ONLINE EXAMPLE
O A program to
demonstrate print
commands.
The System. out. print! n method prints a string or a number and then starts a new
line. For example, the sequence of statements
System. out. println("Hello") ;
System.out. print! n ("World! ") ;
prints two lines of text:
Hello
World !
There is a second method, System, out. print, that you can use to print an item without
starting a new line. For example, the output of the two statements
System . out . pri nt ("00") ;
System. out. println(S + 4);
is the single line
007
10. How do you modify the HelloPri nter program to greet you instead?
1 1 . How would you modify the Hell oPri nter program to print the word “Hello”
vertically?
1 2. Would the program continue to work if you replaced line 5 with this statement?
System. out. println(Hello) ;
1 3. What does the following set of statements print?
System. out. print("My lucky number is");
System. out. println(S + 4 + 5);
1 4. What do the following statements print?
System. out. println("Hello") ;
System . out . pri ntl n ("") ;
System. out. println("World") ;
Practice It Now you can try these exercises at the end of the chapter: R1.7, R1.8, PI. 5, PI. 7.
Omitting Semicolons
In Java every statement must end in a semicolon. Forgetting to type a semicolon is a common
error. It confuses the compiler, because the compiler uses the semicolon to find where one
statement ends and the next one starts. The compiler does not use line breaks or closing braces
to recognize the end of statements. For example, the compiler considers
System. out. pri ntl n ("Hello")
System. out . pri ntl n ("Wo rid! ") ;
a single statement, as if you had written
System. out . pri ntl n(" Hello") System. out . pri ntl n ("World ! ") ;
Then it doesn’t understand that statement, because it does not expect the word System follow¬
ing the closing parenthesis after "Hello".
The remedy is simple. Scan every statement for a terminating semicolon, just as you would
check that every English sentence ends in a period.
1.6 Errors 15
1 .6 Errors
A compile-time error
is a violation of
the programming
language rules that
is detected by
the compiler.
A run-time error
causes a program to
take an action that
the programmer did
not intend.
ONLINE EXAMPLE
O Three programs to
illustrate errors.
Experiment a little with the HelloPrinter program.
What happens if you make a typing error such as
System. ou . pri ntln ("Hello, World ! ") ;
System. out . pri ntln ("Hello, Word ! ") ;
In the first case, the compiler will complain. It will
say that it has no clue what you mean by ou. The
exact wording of the error message is dependent
on your development environment, but it might
be something like “Cannot find symbol ou”.
This is a compile-time error. Something is wrong Programmers spend a fair amount
according to the rules of the language and the com of time fixing compile-time and run-
piler finds it. For this reason, compile-time errors time errors.
are often called syntax errors. When the compiler
finds one or more errors, it refuses to translate the program into Java virtual machine
instructions, and as a consequence you have no program that you can run. You must
fix the error and compile again. In fact, the compiler is quite picky, and it is common
to go through several rounds of fixing compile-time errors before compilation suc¬
ceeds for the first time.
If the compiler finds an error, it will not simply stop and give up. It will try to
report as many errors as it can find, so you can fix them all at once.
Sometimes, an error throws the compiler off track. Suppose, for example, you
forget the quotation marks around a string: System, out. pri ntln (Hello, World!). The
compiler will not complain about the missing quotation marks. Instead, it will report
“Cannot find symbol Hello”. Unfortunately, the compiler is not very smart and it
does not realize that you meant to use a string. It is up to you to realize that you need
to enclose strings in quotation marks.
The error in the second line above is of a different kind. The program will compile
and run, but its output will be wrong. It will print
Hello, Word!
This is a run-time error. The program is syntactically correct and does something,
but it doesn’t do what it is supposed to do. Because run-time errors are caused by
logical flaws in the program, they are often called logic errors.
This particular run-time error did not include an error message. It simply pro¬
duced the wrong output. Some kinds of run-time errors are so severe that they gen¬
erate an exception: an error message from the Java virtual machine. For example, if
your program includes the statement
System. out. pri nt1n(l / 0);
you will get a run-time error message “Division by zero”.
During program development, errors are unavoidable. Once a program is longer
than a few lines, it would require superhuman concentration to enter it correctly
without slipping up once. You will find yourself omitting semicolons or quotation
marks more often than you would like, but the compiler will track down these prob¬
lems for you.
Run-time errors are more troublesome. The compiler will not find them — in fact,
the compiler will cheerfully translate any program as long as its syntax is correct—
16 Chapter 1 Introduction
but the resulting program will do something wrong. It is the responsibility of the
program author to test the program and find any run-time errors.
15. Suppose you omit the "" characters around Hello, World! from the Hell oPrlnter.
java program. Is this a compile-time error or a run-time error?
16. Suppose you change pri ntln to pri ntli ne in the HelloPri nter . java program. Is this
a compile-time error or a run-time error?
1 7. Suppose you change mai n to hello in the Hell oPri nter . java program. Is this a
compile-time error or a run-time error?
1 8. When you used your computer, you may have experienced a program that
“crashed” (quit spontaneously) or “hung” (failed to respond to your input). Is
that behavior a compile-time error or a run-time error?
1 9. Why can’t you test a program for run-time errors when it has compiler errors?
Practice It Now you can try these exercises at the end of the chapter: R1.9, R1.10, Rl.l 1.
Common Error 1 .2
f t.
Misspelling Words
If you accidentally misspell a word, then strange things may happen, and it may not always be
completely obvious from the error messages what went wrong. Here is a good example of how
simple spelling errors can cause trouble:
public class HelloPrinter
{
public static void Mai n(String[] args)
{
System. out . pri ntln ("Hello, World! ") ;
}
}
This class declares a method called Mai n. The compiler will not consider this to be the same as
the mai n method, because Mai n starts with an uppercase letter and the Java language is case sen¬
sitive. Upper- and lowercase letters are considered to be completely different from each other,
and to the compiler Main is no better match for main than rain. The compiler will cheerfully
compile your Mai n method, but when the Java virtual machine reads the compiled file, it will
complain about the missing main method and refuse to run the program. Of course, the mes¬
sage “missing main method” should give you a clue where to look for the error.
If you get an error message that seems to indicate that the compiler or virtual machine is on
the wrong track, it is a good idea to check for spelling and capitalization. If you misspell the
name of a symbol (for example, ou instead of out), the compiler will produce a message such as
“cannot find symbol ou”. That error message is usually a good clue that you made a spelling
error.
1 .7 Problem Solving: Algorithm Design
You will soon learn how to program calculations and decision making in Java. But
before we look at the mechanics of implementing computations in the next chapter,
let’s consider how you can describe the steps that are necessary for finding the solu¬
tion for a problem.
1.7 Problem Solving: Algorithm Design 17
You may have run across advertisements that encourage you to pay for a comput¬
erized service that matches you up with a love partner. Think how this might work.
You fill out a form and send it in. Others do the same. The data are processed by a
computer program. Is it reasonable to assume that
the computer can perform the task of finding the best
match for you? Suppose your younger brother, not
the computer, had all the forms on his desk. What
instructions could you give him? You can’t say, “Find
the best-looking person who likes inline skating and
browsing the Internet”. There is no objective stan¬
dard for good looks, and your brother’s opinion (or
that of a computer program analyzing the digitized
photo) will likely be different from yours. If you
can’t give written instructions for someone to solve
the problem, there is no way the computer can magi¬
cally find the right solution. The computer can only
do what you tell it to do. It just does it faster, without
getting bored or exhausted.
For that reason, a computerized match-making service cannot guarantee to find
the optimal match for you. Instead, you may be presented with a set of potential part¬
ners who share common interests with you. That is a task that a computer program
can solve.
Now consider the following investment problem:
You put $10,000 into a bank account that earns 5 percent interest per year. How many
years does it take for the account balance to be double the original?
Could you solve this problem by hand? Sure, you could. You figure out the balance
as follows:
Finding the perfect partner
is not a problem that a
computer can solve.
year
interest
balance
0
10000
1
10000.00 x 0.05 * 500.00
10000.00 + 500.00 = 10500.00
2
10500.00 x 0.05 * 525.00
10500.00 + 525.00 = 11025.00
3
1 1025.00 x 0.05 * 551.25
11025.00 + 551.25 = 11576.25
4
11576.25x 0.05 = 578.81
11576.25 + 578.81 = 12155.06 \
_
You keep going until the balance is at least $20,000. Then the last number in the year
column is the answer.
Of course, carrying out this computation is intensely boring to you or your
younger brother. But computers are very good at carrying out repetitive calcula¬
tions quickly and flawlessly. What is important to the computer is a description of the
steps for finding the solution. Each step must be clear and unambiguous, requiring no
guesswork. Here is such a description:
Start with a year value of 0, a column for the interest, and a balance of M 0,000.
year
interest
balance /
0
10000
18 Chapter 1 Introduction
Repeat the following steps while the balance is less than *20,000
Add 1 to the year value.
Compute the interest as balance x 0.05 (i.e., 5 percent interest).
Add the interest to the balance.
year
interest
balance /
0
10000
1
500.00
10500.00
14
942.82
19799.52
<R)
989.96
20789.28
Pseudocode is an
informal description
of a sequence of
steps for solving
a problem.
Report the final year value as the answer.
Of course, these steps are not yet in a language that a computer can understand, but
you will soon learn how to formulate them in Java. This informal description is called
pseudocode.
There are no strict requirements for pseudocode because it is read by human read¬
ers, not a computer program. Here are the kinds of pseudocode statements that we
will use in this book:
• Use statements such as the following to describe how a value is set or changed:
total cost = purchase price + operating cost
Multiply the balance value by 1 .05.
Remove the first and last character from the word.
• You can describe decisions and repetitions as follows:
If total cost 1 < total cost 2
While the balance is less than *20,000
For each picture in the sequence
Use indentation to indicate which statements should be selected or repeated:
For each car
operating cost = 1 0 x annual fuel cost
total cost = purchase price + operating cost
Here, the indentation indicates that both statements should be executed for
each car.
• Indicate results with statements such as:
Choose carl.
Report the final year value as the answer.
The exact wording is not important. What is important is that pseudocode describes
a sequence of steps that is
• Unambiguous
• Executable
• Terminating
1.7 Problem Solving: Algorithm Design 19
An algorithm for
solving a problem is
a sequence of steps
that is unambiguous
executable, and
terminating.
Understand
the problem
Develop and
describe an
algorithm
Test the
algorithm with
simple inputs
Translate
the algorithm
into Java
Compile and test
your program
The step sequence is unambiguous when there are
precise instructions for what to do at each step and
where to go next. There is no room for guesswork
or personal opinion. A step is executable when it
can be carried out in practice. Had we said to use
the actual interest rate that will be charged in years
to come, and not a fixed rate of 5 percent per year,
that step would not have been executable, because
there is no way for anyone to know what that
interest rate will be. A sequence of steps is termi¬
nating if it will eventually come to an end. In our
example, it requires a bit of thought to see that the
sequence will not go on forever: With every step, An algorithm is a recipe for
the balance goes up by at least $500, so eventually finding a solution.
it must reach $20,000.
A sequence of steps that is unambiguous, executable, and terminating is called an
algorithm. We have found an algorithm to solve our investment problem, and thus
we can find the solution by programming a computer. The existence of an algorithm
is an essential prerequisite for programming a task. You need to first discover and
describe an algorithm for the task that you want to solve before you start program¬
ming (see Figure 10).
Figure 10 The Software Development Process
20. Suppose the interest rate was 20 percent. How long would it take for the invest¬
ment to double?
2 1 . Suppose your cell phone carrier charges you $29.95 for up to 300 minutes of
calls, and $0.45 for each additional minute, plus 12.5 percent taxes and fees. Give
an algorithm to compute the monthly charge from a given number of minutes.
22. Consider the following pseudocode for finding the most attractive photo from a
sequence of photos:
Pick the first photo and call it "the best so far".
For each photo in the sequence
If it is wore attractive than the "best so far"
discard "the best so far".
Call this photo "the best so far".
The photo called "the best so far" is the wost attractive photo in the sequence.
Is this an algorithm that will find the most attractive photo?
20 Chapter 1
Introduction
23. Suppose each photo in Self Check 22 had a price tag. Give an algorithm for find¬
ing the most expensive photo.
24. Suppose you have a random sequence of black and white marbles and want to
rearrange it so that the black and white marbles are grouped together. Consider
this algorithm:
Repeat until sorted
locate the first black marble that is preceded by a white marble, and switch them.
What does the algorithm do with the sequence 0#0##? Spell out the steps
until the algorithm stops.
25. Suppose you have a random sequence of colored marbles. Consider this pseudo¬
code:
Repeat until sorted
locate the first marble that is preceded by a marble of a different color, and switch them.
Why is this not an algorithm?
Practice It Now you can try these exercises at the end of the chapter: R1.15, R1.17, PI. 4.
HOW TO 1 . 1
Describing an Algorithm with Pseudocode
This is the first of many “How To” sections in this book that give you step-by-step proce¬
dures for carrying out important tasks in developing computer programs.
Before you are ready to write a program in Java, you need to develop an algorithm— a
method for arriving at a solution for a particular problem. Describe the algorithm in pseudo¬
code: a sequence of precise steps formulated in English.
For example, consider this problem: You have the choice of
buying two cars. One is more fuel efficient than the other, but
also more expensive. You know the price and fuel efficiency (in
miles per gallon, mpg) of both cars. You plan to keep the car
for ten years. Assume a price of $4 per gallon of gas and usage
of 15,000 miles per year. You will pay cash for the car and not
worry about financing costs. Which car is the better deal?
Step 1 Determine the inputs and outputs.
In our sample problem, we have these inputs:
• purchase price 1 and fuel efficiency 1 , the price and fuel efficiency (in mpg) of the first car
• purchase priced and fuel efficiency^, the price and fuel efficiency of the second car
We simply want to know which car is the better buy. That is the desired output.
Step 2 Break down the problem into smaller tasks.
For each car, we need to know the total cost of driving it. Let’s do this computation separately
for each car. Once we have the total cost for each car, we can decide which car is the better deal.
The total cost for each car is purchase price * operating cost.
We assume a constant usage and gas price for ten years, so the operating cost depends on the
cost of driving the car for one year.
The operating cost is 1 0 x annual fuel cost.
The annual fuel cost is price per gallon x annual fuel consumed.
1.7 Problem Solving: Algorithm Design 21
The annual fuel consumed is annual miles driven / fuel efficiency. For example, if you drive the car
for 15,000 miles and the fuel efficiency is 15 miles/gallon, the car consumes 1,000 gallons.
Step 3 Describe each subtask in pseudocode.
In your description, arrange the steps so that any intermediate values are computed before
they are needed in other computations. For example, list the step
total cost * purchase price + operating cost
after you have computed operating cost.
Flere is the algorithm for deciding which car to buy:
For each car, compute the total cost as follows:
annual fuel consumed * annual miles driven / fuel efficiency
annual fuel cost = price per gallon x annual fuel consumed
operating cost = 1 0 x annual fuel cost
total cost * purchase price * operating cost
If total costl < total costZ
Choose carl.
Else
Choose carZ.
Step 4 Test your pseudocode by working a problem.
We will use these sample values:
Car 1: $25,000, 50 miles/gallon
Car 2: $20,000, 30 miles/gallon
Here is the calculation for the cost of the first car:
annual fuel consumed * annual miles driven / fuel efficiency = 15000 / 50 = 300
annual fuel cost * price per gallon x annual fuel consumed = 4x300=1200
operating cost = 1 0 x annual fuel cost = 1 0 x 1200 = 1 2000
total cost = purchase price + operating cost = Z5000 + 12000 = 37000
Similarly, the total cost for the second car is $40,000. Therefore, the output of the algorithm is
to choose car 1.
WORKED EXAMPLE 1 .1
Writing an Algorithm for Tiling a Floor
This Worked Example shows how to develop an algorithm for laying
tile in an alternating pattern of colors.
VIDEO EXAMPLE 1 .2
Dividing Household Expenses
fWILEYb
'PLUS
This Video Example shows how to develop an algorithm for
dividing household expenses among roommates.
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
22 Chapter 1 Introduction
CHAPTER SUMMARY
Define “computer program” and programming.
• Computers execute very basic instructions in rapid succession.
• A computer program is a sequence of instructions and decisions.
• Programming is the act of designing and implementing computer programs.
Describe the components of a computer.
• The central processing unit (CPU) performs program control and data
processing.
• Storage devices include memory and secondary storage.
Describe the process of translating high-level languages to machine code.
• Java was originally designed for programming consumer devices, but it was first
successfully used to write Internet applets.
• Java was designed to be safe and portable, benefiting both Internet users and
students.
• Java programs are distributed as instructions for a virtual machine, making them
platform-independent.
• Java has a very large library. Focus on learning those parts of the library that you
need for your programming projects.
Become familiar with your Java programming environment.
• Set aside some time to become familiar with the programming environment that
you will use for your class work.
• An editor is a program for entering and modifying text, such as a Java program.
• Java is case sensitive. You must be careful about distinguishing between upper-
and lowercase letters.
• The Java compiler translates source code into class files that contain instructions
for the Java virtual machine.
• Develop a strategy for keeping backup copies of your
work before disaster strikes.
Describe the building blocks of a simple program.
• Classes are the fundamental building blocks of Java programs.
• Every Java application contains a class with a mai n method. When the application
starts, the instructions in the mai n method are executed.
• Each class contains declarations of methods. Each method contains a sequence of
instructions.
• A method is called by specifying the method and its arguments.
• A string is a sequence of characters enclosed in quotation marks.
Review Exercises 23
Classify program errors as compile-time and run-time errors.
• A compile-time error is a violation of the programming language rules that is
detected by the compiler.
• A run-time error causes a program to take an action that the programmer did not
intend.
Write pseudocode for simple algorithms.
• Pseudocode is an informal description of a sequence of steps
for solving a problem.
• An algorithm for solving a problem is a sequence of steps that
is unambiguous, executable, and terminating.
STANDARD LIBRARY ITEMS INTRODUCED IN THIS CHAPTER
java.io.PrintStream java. Tang. System
print out
println
REVIEW EXERCISES
■ R 1 . 1 Explain the difference between using a computer program and programming a
computer.
■ R1 .2 Which parts of a computer can store program code? Which can store user data?
■ R1 .3 Which parts of a computer serve to give information to the user? Which parts take
user input?
■ ■ ■ R1 .4 A toaster is a single-function device, but a computer can be programmed to carry out
different tasks. Is your cell phone a single-function device, or is it a programmable
computer? (Your answer will depend on your cell phone model.)
■ R 1 . 5 Explain two benefits of using Java over machine code.
■ ■ R1 .6 On your own computer or on a lab computer, find the exact location (folder or
directory name) of
a. The sample file HelloPri nter. java, which you wrote with the editor
b. The Java program launcher java.exe or java
c. The library file rt . j ar that contains the run-time library
■ ■ R1 .7 What does this program print?
public class Test
{
public static void main(String[] args)
{
System. out. println("39 + 3");
System. out. println(39 + 3);
}
}
24 Chapter 1 Introduction
■ ■ R1.8
■ ■ R1.9
■ ■ R1.10
■ Rl.ll
■ ■ R1.12
■ ■■ R1.13
■ ■■ R1.14
■ ■ R1 .1 5
■ ■ R1.16
■ R1.1 7
■ ■■ R1.18
What does this program print? Pay close attention to spaces.
public class Test
{
public static void main(String[] args)
{
System. out. print("Hello") ;
System. out. println("World") ;
}
}
What is the compile-time error in this program?
public class Test
{
public static void main(String[] args)
{
System. out . println ("Hello" , "World! ") ;
}
}
Write three versions of the HelloPrinter . java program that have different compile¬
time errors. Write a version that has a run-time error.
How do you discover syntax errors? How do you discover logic errors?
Write an algorithm to settle the following question: A bank account starts out with
$10,000. Interest is compounded monthly at 6 percent per year (0.5 percent per
month). Every month, $500 is withdrawn to meet college expenses. After how many
years is the account depleted?
Consider the question in Exercise R1.12. Suppose the numbers ($10,000, 6 percent,
$500) were user selectable. Are there values for which the algorithm you developed
would not terminate? If so, change the algorithm to make sure it always terminates.
In order to estimate the cost of painting a house, a painter needs to know the surface
area of the exterior. Develop an algorithm for computing that value. Your inputs are
the width, length, and height of the house, the number of windows and doors, and
their dimensions. (Assume the windows and doors have a uniform size.)
You want to decide whether you should drive your car to work or take the train.
You know the one-way distance from your home to your place of work, and the
fuel efficiency of your car (in miles per gallon). You also know the one-way price of
a train ticket. You assume the cost of gas at $4 per gallon, and car maintenance at 5
cents per mile. Write an algorithm to decide which commute is cheaper.
You want to find out which fraction of your car’s use is for commuting to work,
and which is for personal use. You know the one-way distance from your home to
work. For a particular period, you recorded the beginning and ending mileage on the
odometer and the number of work days. Write an algorithm to settle this question.
In How To 1 .1, you made assumptions about the price of gas and annual usage to
compare cars. Ideally, you would like to know which car is the better deal without
making these assumptions. Why can’t a computer program solve that problem?
The value of n can be computed according to the following formula:
Programming Exercises 25
Write an algorithm to compute n. Because the formula is an infinite series and an
algorithm must stop after a finite number of steps, you should stop when you have
the result determined to six significant digits.
■ ■ R 1 . 1 9 Suppose you put your younger brother in charge of backing up your work. Write a
set of detailed instructions for carrying out his task. Explain how often he should do
it, and what files he needs to copy from which folder to which location. Explain how
he should verify that the backup was carried out correctly.
■ Business R1 .20 Imagine that you and a number of friends go to a luxury restaurant, and when you
ask for the bill you want to split the amount and the tip (15 percent) between all.
Write pseudocode for calculating the amount of money that everyone has to pay.
Your program should print the amount of the bill, the tip, the total cost, and the
amount each person has to pay. It should also print how much of what each person
pays is for the bill and for the tip.
PROGRAMMING EXERCISES
■ P 1 . 1 Write a program that prints a greeting of your choice, perhaps in a language other
than English.
■ ■ PI. 2 Write a program that prints the sum of the first ten positive integers, 1 + 2+ ... + 10.
■ ■ PI .3 Write a program that prints the product of the first ten positive integers, 1 x 2 x . . . x
10. (Use * to indicate multiplication in Java.)
■ ■ PI .4 Write a program that prints the balance of an account after the first, second, and
third year. The account has an initial balance of $1,000 and earns 5 percent interest
per year.
■ PI .5 Write a program that displays your name inside a box on the screen, like this:
Dave
Do your best to approximate lines with characters such as | - h
PI .6 Write a program that prints your name in large letters, such as
■ ■ PI .7 Write a program that prints a face similar to (but different from) the following:
/////
+""""„+
+ - +
■ ■ PI .8 Write a program that prints an imitation of a Piet Mondrian painting. (Search the
Internet if you are not familiar with his paintings.) Use character sequences such as
@@@ or : : : to indicate different colors, and use - and | to form lines.
26 Chapter 1 Introduction
■ ■ PI .9 Write a program that prints a house that looks exactly like the following:
+
+ +
+ +
+ - +
I I
I I I I
+-+-+-+
Write a program that prints an animal speaking a greeting, similar to (but different
from) the following:
A_A -
( ‘ ’ ) / Hello V
( - ) < Junior |
III \ Coder!/
(_|_) -
Write a program that prints three items, such as the names of your three best friends
or favorite movies, on three separate lines.
Write a program that prints a poem of your choice. If you don’t have a favorite
poem, search the Internet for “Emily Dickinson” or “e e cummings”.
Write a program that prints the United States flag, using * and = characters.
Type in and run the following program:
import javax. swing. JOptionPane;
■ PI. 11
■ PI. 12
■ ■ PI. IB
■ ■ PI. 14
public class DialogViewer
{
public static void main(String[] args)
{
JOptionPane. showMessageDialog(null , "Hello, World!");
}
}
Then modify the program to show the message “Hello, your name\” .
■ ■ PI. 15 Type in and run the following program:
import javax. swing. JOptionPane;
public class DialogViewer
{
public static void main(String[] args)
{
String name = JOptionPane. showInputDialog("What is your name?");
System . out . pri ntl n (name) ;
}
}
Then modify the program to print “Hello, name\” , displaying the name that the user
typed in.
■ ■ ■ PI .1 6 Modify the program from Exercise PI. 15 so that the dialog continues with the mes¬
sage “My name is Hal! What would you like me to do?” Discard the user’s input and
display a message such as
I'm sorry, Dave. I'm afraid I can't do that.
Replace Dave with the name that was provided by the user.
Answers to Self-Check Questions 27
■ ■ PI. 17 Type in and run the following program:
import java. net. URL;
import javax. swing. Imagelcon;
import javax. swing. JOptionPane;
public class Test
{
public static void main(String[] args) throws Exception
{
URL imageLocation = new URL (
"http : //horstmann . com/j ava4everyone/duke . gi f") ;
JOptionPane. showMessageDialog(null , "Hello", "Title",
JOptionPane. PLAIN_MESSAGE, new Imagelcon (imageLocati on) ) ;
}
}
Then modify it to show a different greeting and image.
■ Business PI .18 Write a program that prints a two-column list of your friends’ birthdays. In the
first column, print the names of your best friends; in the second column, print their
birthdays.
■ Business PI .1 9 In the United States there is no federal sales tax, so every state may impose its own
sales taxes. Look on the Internet for the sales tax charged in five U.S. states, then
write a program that prints the tax rate for five states of your choice.
Sales Tax Rates
Alaska: 0%
Hawaii : 4%
■ Business PI .20 To speak more than one language is a valuable skill in the labor market today. One of
the basic skills is learning to greet people. Write a program that prints a two-column
list with the greeting phrases shown in the following table; in the first column, print
the phrase in English, in the second column, print the phrase in a language of your
choice. If you don’t speak any language other than English, use an online translator
or ask a friend.
List of Phrases to Translate
Good morning.
It is a pleasure to meet you.
Please call me tomorrow.
Have a nice day!
ANSWERS TO SELF-CHECK QUESTIONS
1 . A program that reads the data on the CD and
sends output to the speakers and the screen.
2. A CD player can do one thing — play music
CDs. It cannot execute programs.
3. Nothing.
4. In secondary storage, typically a hard disk,
5. The central processing unit.
28 Chapter 1 Introduction
6. Safety and portability.
7. No one person can learn the entire library —it
is too large.
8. The answer varies among systems. A typical
answer might be /home/dave/csl/hello/Hello-
Pri nter. java or c:\Users\Dave\Workspace\heno\
HelloPrinter. java
9. You back up your files and folders.
T 0. Change World to your name (here, Dave):
System. out. pnntln("Hello, Dave!") ;
11. System. out. println("H") ;
System. out. println("e") ;
System. out. println("l") ;
System. out. println("l") ;
System. out. println("o") ;
12. No. The compiler would look for an
item whose name is Hel 1 o. You need to
enclose Hello in quotation marks:
System . out . pri ntl n("Hel 1 o") ;
13. The printout is My lucky number isl2. It would
be a good idea to add a space after the i s.
14. Hello
a blank line
World
1 5. This is a compile-time error. The compiler will
complain that it does not know the meanings
of the words Hello and World.
1 6. This is a compile-time error. The compiler
will complain that System. out does not have a
method called pri ntl i ne.
1 7. This is a run-time error. It is perfectly legal to
give the name hell o to a method, so the com¬
piler won’t complain. But when the program
is run, the virtual machine will look for a mai n
method and won’t find one.
18. It is a run-time error. After all, the program
had been compiled in order for you to run it.
1 9. When a program has compiler errors, no class
file is produced, and there is nothing to run.
20. 4 years:
0 10,000
1 12,000
2 14,400
3 17,280
4 20,736
21. Is the number of minutes at most 300?
a. If so, the answer is $29.95 x 1.125 = $33.70.
b. If not,
1 . Compute the difference: (number of
minutes) - 300.
2. Multiply that difference by 0.45.
3. Add $29.95.
4 . Multiply the total by 1 . 1 25 . That is the
answer.
22. No. The step If it is more attractive than the "best
so far" is not executable because there is no
objective way of deciding which of two photos
is more attractive.
23. Pick the first photo and call it "the most expensive so far" .
For each photo in the sequence
If it is more expensive than "the most expensive so far"
discard "the most expensive so far”.
Call this photo "the most expensive so far".
The photo called "the most expensive so far" is the most
expensive photo in the sequence.
24. The first black marble that is preceded by a
white one is marked in blue:
09099
Switching the two yields
•0099
The next black marble to be switched is
90099
yielding
90909
The next steps are
99009
99090
99900
Now the sequence is sorted.
25. The sequence doesn’t terminate. Consider the
input O0O#O. The first two marbles keep
getting switched.
CHAPTER
2
FUNDAMENTAL
DATA TYPES
CHAPTER COALS
To declare and initialize variables
and constants
To understand the properties and limitations of integers and floating-point numbers
To appreciate the importance of comments and good code layout
To write arithmetic expressions and assignment statements
To create programs that read and process inputs, and display the results
To learn how to use the Java Stri ng type
CHAPTER CONTENTS
2.1 VARIABLES 30
Syntax 2.1: Variable Declaration 31
Syntax 2.2: Assignment 34
Syntax 2.3: Constant Declaration 35
Common Error 2.1 : Using Undeclared or
Uninitialized Variables 37
Programming Tip 2.1 : Choose Descriptive
Variable Names 38
Common Error 2.2: Overflow 38
Common Error 2.3: Roundoff Errors 38
Programming Tip 2.2: Do Not Use
Magic Numbers 39
Special Topic 2.1 : Numeric Types in Java 39
Special Topic 2.2: Big Numbers 40
2.2 ARITHMETIC 41
Syntax 2.4: Cast 44
Common Error 2.4: Unintended
Integer Division 46
Common Error 2.5: Unbalanced Parentheses 46
Programming Tip 2.3: Spaces in Expressions 47
Special Topic 2.3: Combining Assignment
and Arithmetic 47
Video Example 2.1 : Using Integer Division ©
Random Fact 2.1 : The Pentium
Floating-Point Bug 48
2.3 INPUT AND OUTPUT 48
Syntax 2.5: Input Statement 49
Programming Tip 2.4: Use the API
Documentation 53
How To 2.1: Carrying out Computations 54
Worked Example 2.1 : Computing the Cost
of Stamps ©
2.4 PROBLEM SOLVING: FIRST
DO IT BY HAND 57
Worked Example 2.2: Computing Travel Time ©
2.5 STRINGS 59
Special Topic 2.4: Instance Methods and
Static Methods 64
Special Topic 2.5: Using Dialog Boxes for
Input and Output 65
Video Example 2.2: Computing Distances
on Earth ©
Random Fact 2.2: International Alphabets
and Unicode 66
I?r-
§|p5= %
Numbers and character strings (such as the ones on this
display board) are importantdata types in anyjava program.
In this chapter, you will learn how to work with numbers
and text, and how to write simple programs that perform
useful tasks with them.
2.1 Variables
When your program carries out computations, you will want to store values so that
you can use them later. In a Java program, you use variables to store values. In this
section, you will learn how to declare and
To illustrate the use of variables, we
will develop a program that solves the
following problem. Soft drinks are sold
in cans and bottles. A store offers a six-
pack of 12-ounce cans for the same price
as a two-liter bottle. Which should you
buy? (Twelve fluid ounces equal approx¬
imately 0.355 liters.)
In our program, we will declare vari¬
ables for the number of cans per pack
and for the volume of each can. Then we
will compute the volume of a six-pack in
liters and print out the answer.
use variables.
m
What contains more soda? A six-pack of
1 2-ounce cans or a two-liter bottle ?
2.1.1 Variable Declarations
The following statement declares a variable named cansPerPack:
int cansPerPack = 6;
. ... . A variable is a storage location in a computer program. Each variable has a name and
A variable is a . .. . b r r
storage location holds a value.
with a name. A variable is similar to a parking space in a parking garage. The parking space has
an identifier (such as “J 053”), and it can hold a vehicle. A variable has a name (such as
cansPerPack), and it can hold a value (such as 6).
Like a variable in a computer
program , a parking space has
an identifier and a contents.
BO
2.1 Variables 31
Syntax 2.1
Variable Declaration
Syntax typeName variableName = value ;
or
typeName variableName ;
See page 33 for rules and
examples of valid names.
Types introduced in
this chapter are
the number types
i nt and double
int cansPerPack = 6;
(page 31)
and the String type
(page 79).
Use a descriptive
\ variable name.
tI- See page 3%.
A variable declaration ends
with a semicolon.
Supplying an initial value is optional,
but it is usually a good idea,
rf, See page 31.
When declaring a
variable, you
usually specify an
initial value.
When declaring a
variable, you also
specify the type of
its values.
When declaring a variable, you usually want to initialize it. That is, you specify the
value that should be stored in the variable. Consider again this variable declaration:
int cansPerPack = 6;
The variable cansPerPack is initialized with the value 6.
Like a parking space that is restricted to a certain type of vehicle (such as a compact
car, motorcycle, or electric vehicle), a variable in Java stores data of a specific type.
Java supports quite a few data types: numbers, text strings, files, dates, and many oth¬
ers. You must specify the type whenever you declare a variable (see Syntax 2.1).
The cansPerPack variable is an integer, a whole number without a fractional part. In
Java, this type is called int. (See the next section for more information about number
types in Java.)
Note that the type comes before the variable name:
int cansPerPack = 6;
After you have declared and initialized a variable, you can use it. For example,
int cansPerPack = 6;
System . out . pri ntl n (cansPerPack) ;
int cansPerCrate = 4 * cansPerPack;
Table 1 shows several examples of variable
declarations.
Each parking space is suitable for a particular type of vehicle ,
just as each variable holds a value of a particular type.
32 Chapter 2 Fundamental Data Types
<S>
0
Use the int type
for numbers that
cannot have a
fractional part.
Table 1 Variable Declarations in Java
Variable Name
Comment
int cans = 6;
Declares an integer variable and initializes it with 6.
int total = cans + bottles;
The initial value need not be a fixed value. (Of course, cans and
bottl es must have been previously declared.)
bottles = 1;
Error: The type is missing. This statement is not a declaration but an
assignment of a new value to an existing variable — see Section 2.1.4.
i nt volume = "2" ;
Error: You cannot initialize a number with a string.
int cansPerPack;
Declares an integer variable without initializing it. This can be a
cause for errors — see Common Error 2.1 on page 37.
int dollars, cents;
Declares two integer variables in a single statement. In this book, we
will declare each variable in a separate statement.
2.1 .2 Number Types
In Java, there are several different types of numbers. You use the int type to denote a
whole number without a fractional part. For example, there must be an integer num¬
ber of cans in any pack of cans — you cannot have a fraction of a can.
When a fractional part is required (such as in the number 0.335), we use floating¬
point numbers. The most commonly used type for floating-point numbers in Java is
called doubl e. (If you want to know the reason, read Special Topic 2.1 on page 39 .) Here
is the declaration of a floating-point variable:
double canVolume = 0.335;
Table 2 Number Literals in Java
Number
Type
Comment
6
int
An integer has no fractional part.
-6
int
Integers can be negative.
0
int
Zero is an integer.
0.5
double
A number with a fractional part has type doubl e.
1.0
double
An integer with a fractional part .0 has type doubl e.
1E6
double
A number in exponential notation: 1 x 106 or 1000000.
Numbers in exponential notation always have type doubl e.
2.96E-2
double
Negative exponent: 2.96 x 10-2 = 2.96 / 100 = 0.0296
100,000
Error: Do not use a comma as a decimal separator.
^ 3 1/2
Error: Do not use fractions; use decimal notation: 3.5
2.1 Variables 33
Use the double
type for floating¬
point numbers.
When a value such as 6 or 0 . 3 3 5 occurs in a J ava program, it is called a number literal.
If a number literal has a decimal point, it is a floating-point number; otherwise, it is an
integer. Table 2 shows how to write integer and floating-point literals in Java.
2.1 .3 Variable Names
When you declare a variable, you should pick a name that explains its purpose. For
example, it is better to use a descriptive name, such as canVol ume, than a terse name,
such as cv.
In Java, there are a few simple rules for variable names:
1 . Variable names must start with a letter or the underscore (_) character, and the
remaining characters must be letters, numbers, or underscores. (Technically,
the $ symbol is allowed as well, but you should not use it— it is intended for
names that are automatically generated by tools.)
2 . You cannot use other symbols such as ? or %. Spaces are not permitted inside
names either. You can use uppercase letters to denote word boundaries, as in
cansPerPack. This naming convention is called camel
case because the uppercase letters in the middle of the
name look like the humps of a camel.)
3 . Variable names are case sensitive, that is, canVol ume and
canvol ume are different names.
4. You cannot use reserved words such as doubl e or cl ass
as names; these words are reserved exclusively for their
By convention,
variable names
should start with a
lowercase letter.
special Java meanings. (See Appendix C for a listing of all reserved words in
Java.)
It is a convention among Java programmers that variable names should start with a
lowercase letter (such as canVol ume) and class names should start with an uppercase
letter (such as HelloPri nter). That way, it is easy to tell them apart.
Table 3 shows examples of legal and illegal variable names in Java.
Table B Variable Names in Java
Variable Name
Comment
canVolumel
Variable names consist of letters, numbers, and the underscore character.
X
In mathematics, you use short variable names such as x or y. This is legal in Java, but not
very common, because it can make programs harder to understand (see Programming Tip
2.1 on page 38).
yjy CanVol ume
Caution: Variable names are case sensitive. This variable name is different from canVol ume,
and it violates the convention that variable names should start with a lowercase letter.
6pack
Error: Variable names cannot start with a number.
can volume
Error: Variable names cannot contain spaces.
double
Error: You cannot use a reserved word as a variable name.
^ ltr/fl .oz
Error: You cannot use symbols such as / or.
34 Chapter 2 Fundamental Data Types
An assignment
statement stores a
new value in a
variable, replacing
the previously
stored value.
Variable Initialization
and Assignment
1 1'
The assignment
operator = does not
denote mathematical
equality.
Syntax 2.2
2.1.4 The Assignment Statement
You use the assignment statement to place a new value into a variable. Here is an
example:
cansPerPack = 8;
The left-hand side of an assignment statement consists of a variable. The right-hand
side is an expression that has a value. That value is stored in the variable, overwriting
its previous contents.
There is an important difference between a variable declaration and an assignment
statement:
Variable declaration
int cansPerPack = 6;
cansPerPack = 8; Assignment statement
The first statement is the declaration of cansPerPack. It is an instruction to create a
new variable of type i nt, to give it the name cansPerPack, and to initialize it with 6. The
second statement is an assignment statement: an instruction to replace the contents of
the existing variable cansPerPack with another value.
The = sign doesn’t mean that the left-hand side is equal to the right-hand side. The
expression on the right is evaluated, and its value is placed into the variable on the left.
Do not confuse this assignment operation with the = used in algebra to denote
equality. The assignment operator is an instruction to do something — namely, place a
value into a variable. The mathematical equality states that two values are equal.
For example, in Java, it is perfectly legal to write
total Volume = total Volume + 2;
It means to look up the value stored in the variable total Volume, add 2 to it, and place
the result back into total Volume. (See Figure 1.) The net effect of executing this state¬
ment is to increment totalVolume by 2. For example, if totalVolume was 2.13 before
execution of the statement, it is set to 4.13 afterwards. Of course, in mathematics it
would make no sense to write that t=x + 2.No value can equal itself plus 2.
Assignment
Syntax variableName = value ;
This is an initialization
of a new variable,
NOT an assignment.
The name of a previously
defined variable
double total = 0;
This is an assignment.
total = bottles * B0TTLE_V0LUME;
V _ _ , _ J
Y
The expression that replaces the previous value
total = total + cans * CANLVOLUME;
The same name
can occur on both sides.
See Figure 1.
2.1 Variables 35
Figure 1 Executing the Assignment totalVolume = total Vol ume + 2
2.1 .5 Constants
„ „ , When a variable is defined with the reserved word fi nal, its value can never change,
the value of a Constants are commonly written using capital letters to distinguish them visually
variable that is from regular variables:
defined as final .
final double B0TTLE_V0LUME = 2;
It is good programming style to use named constants in your program to explain the
meanings of numeric values. For example, compare the statements
double totalVolume = bottles * 2;
and
double totalVolume = bottles * B0TTLE_V0LUME;
A programmer reading the first statement may not understand the significance of the
number 2. The second statement, with a named constant, makes the computation
much clearer.
Syntax 2 Constant Declaration
Syntax final typeName variableName = expression ;
The fi nal reserved word
^ final double CAN VOLUME = 0.355; // Liters in a 12
ounce can
indicates that this value - —
cannot be modified.
This comment explains how
Use uppercase letters for constants.
the value for the constant
was determined.
2.1 .6 Comments
As your programs get more complex, you should add comments, explanations for
human readers of your code. For example, here is a comment that explains the value
used in a variable initialization:
final double CANLVOLUME = 0.355; // Liters in a 12-ounce can
This comment explains the significance of the value 0.355 to a human reader. The
compiler does not process comments at all. It ignores everything from a // delimiter
to the end of the line.
36 Chapter 2 Fundamental Data Types
Use comments to add
explanations for
humans who read
your code. The
compiler ignores
comments.
/*
There are approximately 0.335 liters in a 12-ounce can because one ounce
equals 0.02957353 liter; see The International Systems of Units (SI) - Conversion
Factors for General Use (NIST Special Publication 1038).
V
Finally, start a comment that explains the purpose of a program with the /** delimiter
instead of /*. Tools that analyze source files rely on that convention. For example,
/**
This program computes the volume (in liters) of a six-pack of soda cans.
V
The following program shows the use of variables, constants, and the assignment
statement. The program displays the volume of a six-pack of cans and the total vol¬
ume of the six-pack and a two-liter bottle. We use constants for the can and bottle
volumes. The total Volume variable is initialized with the volume of the cans. Using an
assignment statement, we add the bottle volume. As you can see from the program
output, the six-pack of cans contains over two liters of soda.
section_l/Volumel .java
1 A*
2 This program computes the volume (in liters) of a six-pack of soda
3 cans and the total volume of a six-pack and a two-liter bottle.
4 */
5 public class Volumel
6 {
public static void main(String[] args)
8 {
9 int cansPerPack = 6;
10 final double CAN_V0LUME = 0.355; // Liters in a 12-ounce can
11 double totalVolume = cansPerPack * CAN_V0LUME;
12
13 System. out. print( 'A six-pack of 12-ounce cans contains );
14 System. out. print(total Volume) ;
15 System. out. println( ' liters.');
16
17 final double B0TTLE_V0LUME = 2; // Two-liter bottle
18
19 totalVolume = totalVolume + B0TTLE_V0LUME;
20
21 System. out. print ( 'A six-pack and a two-liter bottle contain );
22 System. out. print(total Volume) ;
23 System. out. println( ' liters.’);
24 }
25 }
Program Run
A six-pack of 12-ounce cans contains 2.13 liters.
A six-pack and a two-liter bottle contain 4.13 liters.
It is a good practice to provide comments. This helps programmers who read your
code understand your intent. In addition, you will find comments helpful when you
review your own programs.
You use the // delimiter for short comments. If you have a longer comment,
enclose it between /* and */ delimiters. The compiler ignores these delimiters and
everything in between. For example,
2.1 Variables 37
Just as a television commentator explains the news,
you use comments in your program to explain its behavior.
1 . Declare a variable suitable for holding the number of bottles in a case.
2. What is wrong with the following variable declaration?
int ounces per liter = 28.35
3. Declare and initialize two variables, uni tPri ce and quanti ty, to contain the unit
price of a single bottle and the number of bottles purchased. Use reasonable
initial values.
4. Use the variables declared in Self Check 3 to display the total purchase price.
5. Some drinks are sold in four-packs instead of six-packs. How would you change
the Vol umel. java program to compute the total volume?
6. What is wrong with this comment?
double canVolume = 0.355; /* Liters in a 12-ounce can //
7. Suppose the type of the cansPerPack variable in Vol umel. java was changed from int
to double. What would be the effect on the program?
8. Why can’t the variable total Volume in the Vol umel. java program be declared as
final ?
9. How would you explain assignment using the parking space analogy?
Practice It Now you can try these exercises at the end of the chapter: R2.1, R2.2, P2.1.
Common Error 2.1
Using Undeclared or Uninitialized Variables
You must declare a variable before you use it for the first time. For example, the following
sequence of statements would not be legal:
double canVolume = 12 * literPerOunce; // ERROR: literPerOunce is not yet declared
double literPerOunce = 0.0296;
In your program, the statements are compiled in order. When the compiler reaches the first
statement, it does not know that literPerOunce will be declared in the next line, and it reports
an error. The remedy is to reorder the declarations so that each variable is declared before it is
used.
38 Chapter 2 Fundamental Data Types
A related error is to leave a variable uninitialized:
int bottles;
int bottleVolume = bottles * 2; // ERROR: bottles is not yet initialized
The Java compiler will complain that you are using a variable that has not yet been given a
value. The remedy is to assign a value to the variable before it is used.
Choose Descriptive Variable Names
We could have saved ourselves a lot of typing by using shorter variable names, as in
double cv = 0.355;
Compare this declaration with the one that we actually used, though. Which one is easier to
read? There is no comparison. Just reading canVolume is a lot less trouble than reading cv and
then figuring out it must mean “can volume”.
In practical programming, this is particularly important when programs are written by
more than one person. It may be obvious to you that cv stands for can volume and not cur¬
rent velocity, but will it be obvious to the person who needs to update your code years later?
For that matter, will you remember yourself what cv means when you look at the code three
months from now?
Overflow
Because numbers are represented in the computer with a limited number of digits, they cannot
represent arbitrary numbers.
The i nt type has a limited range: It can represent numbers up to a little more than two bil¬
lion. For many applications, this is not a problem, but you cannot use an i rt to represent the
world population.
If a computation yields a value that is outside the i nt range, the result overflows. No error is
displayed. Instead, the result is truncated, yielding a useless value. For example,
int fiftyMillion = 50000000;
System. out. println(100 * fiftyMillion); // Expected: 5000000000
displays 705032704.
In situations such as this, you can switch to double values. However, read Common Error
2.3 for more information about a related issue: roundoff errors.
Roundoff Errors
Roundoff errors are a fact of life when calculating with floating-point numbers. You probably
have encountered that phenomenon yourself with manual calculations. If you calculate 1/ 3 to
two decimal places, you get 0.33. Multiplying again by 3, you obtain 0.99, not 1.00.
In the processor hardware, numbers are represented in the binary number system, using
only digits 0 and 1. As with decimal numbers, you can get roundoff errors when binary digits
are lost. They just may crop up at different places than you might expect.
2.1 Variables 39
Here is an example:
double price = 4.35;
double quantity = 100;
double total = price * quantity; // Should be 100 * 4.35 = 435
System. out. println(total) ; // Prints 434.99999999999999
In the binary system, there is no exact representation for 4.35, just as there is no exact repre¬
sentation for l/ 3 in the decimal system. The representation used by the computer is just a
little less than 4.35, so 100 times that value is just a little less than 435.
You can deal with roundoff errors by rounding to the nearest integer (see Section 2.2.5) or
by displaying a fixed number of digits after the decimal separator (see Section 2.3.2).
Do Not Use Magic Numbers
A magic number is a numeric constant that appears in your code without explanation. For
example,
totalVolume = bottles * 2;
Why 2? Are bottles twice as voluminous as cans? No, the reason is that every bottle contains 2
liters. Use a named constant to make the code self-documenting:
final double B0TTLE_V0LUME = 2;
totalVolume = bottles * B0TTLE_V0LUME ;
There is another reason for using named constants. Suppose cir¬
cumstances change, and the bottle volume is now 1.5 liters. If
you used a named constant, you make a single change, and you
are done. Otherwise, you have to look at every value of 2 in your
program and ponder whether it meant a bottle volume, or some¬
thing else. In a program that is more than a few pages long, that
is incredibly tedious and error-prone.
Even the most reasonable cosmic constant is going to change
one day. You think there are seven days per week? Your cus¬
tomers on Mars are going to be pretty unhappy about your silly
prejudice. Make a constant
We prefer programs that
are easy to understand
over those that appear
to work by magic.
final int DAYS_PER_WEEK = 7;
Numeric Types in Java
In addition to the i nt and doubl e types, Java has several other numeric types.
Java has two floating-point types. The float type uses half the storage of the double type
that we use in this book, but it can only store about 7 decimal digits. (In the computer, num¬
bers are represented in the binary number system, using digits 0 and 1 .) Many years ago, when
computers had far less memory than they have today, f 1 oat was the standard type for floating¬
point computations, and programmers would indulge in the luxury of “double precision”
only when they needed the additional digits. Today, the f 1 oat type is rarely used.
By the way, these numbers are called “floating-point” because of their internal representa¬
tion in the computer. Consider numbers 29600, 2.96, and 0.0296. They can be represented in
a very similar way: namely, as a sequence of the significant digits— 296 — and an indication of
the position of the decimal point. When the values are multiplied or divided by 10, only the
40 Chapter 2 Fundamental Data Types
position of the decimal point changes; it “floats”. Computers use base 2, not base 10, but the
principle is the same.
In addition to the int type, Java has integer types byte, short, and long. Their ranges are
shown in Table 4. (Their strange-looking limits are related to powers of 2, another conse¬
quence of the fact that computers use binary numbers.)
Table 4 Java Number Types
Type
Description
Size
int
The integer type, with range
-2,147,483,648 (Integer. MIN_VALUE) . . . 2,147,483,647
(Integer ,MAX_VALUE, about 2.14 billion)
4 bytes
byte
The type describing a single byte consisting of 8 bits,
with range -128 ... 127
1 byte
short
The short integer type, with range -32,768 . . . 32,767
2 bytes
long
The long integer type, with about 19 decimal digits
8 bytes
double
The double-precision floating-point type,
with about 15 decimal digits and a range of about ±1030S
8 bytes
float
The single-precision floating-point type,
with about 7 decimal digits and a range of about ±1038
4 bytes
char
The character type, representing code units in the
Unicode encoding scheme (see Random Fact 2.2)
2 bytes
Big Numbers
If you want to compute with really large numbers, you can use big number objects. Big num¬
ber objects are objects of the Biglnteger and BigDecimal classes in the java. math package. Unlike
the number types such as int or double, big number objects have essentially no limits on their
size and precision. However, computations with big number objects are much slower than
those that involve number types. Perhaps more importantly, you can’t use the familiar arith¬
metic operators such as (+ - *) with them. Instead, you have to use methods called add, sub¬
tract, and multiply. Here is an example of how to create a Biglnteger object and how to call the
multiply method:
Biglnteger oneHundred = new Biglnteger("100") ;
Biglnteger fiftyMillion = new Biglnteger("50000000") ;
System. out. println(oneHundred.multiply(fiftyMillion)) ; // Prints 5000000000
The BigDecimal type carries out floating-point computations without roundoff errors. For
example,
BigDecimal price = new BigDecimal ("4.35") ;
BigDecimal quantity = new BigDecimal ("100") ;
BigDecimal total = pri ce. multi pi y(quanti ty) ;
System. out. println(total) ; // Prints 435.00
2.2 Arithmetic 41
2.2 Arithmetic
In the following sections, you will learn how to carry out arithmetic calculations
in Java.
2.2.1 Arithmetic Operators
Java supports the same four basic arithmetic operations as a calculator — addition,
subtraction, multiplication, and division— but it uses different symbols for multipli¬
cation and division.
You must write a * b to denote multiplication. Unlike in mathematics, you cannot
write a b, a • b, or a x b. Similarly, division is always indicated with a /, never a + or a
fraction bar.
u + b
For example, — — — becomes (a + b) / 2.
The combination of variables, literals, operators, and/or method calls is called an
expression. For example, (a + b) / 2 is an expression.
Parentheses are used just as in algebra: to indicate in which order the parts of the
expression should be computed. For example, in the expression (a + b) / 2, the sum
a + b is computed first, and then the sum is divided by 2. In contrast, in the expression
a + b / 2
Mixing integers and
floating-point values
in an arithmetic
expression yields a
floating-point value.
only b is divided by 2, and then the sum of a and b / 2 is formed. As in regular algebraic
notation, multiplication and division have a higher precedence than addition and sub¬
traction. For example, in the expression a + b / 2, the / is carried out first, even though
the + operation occurs further to the left.
If you mix integer and floating-point values in an arithmetic expression, the result
is a floating-point value. For example, 7 + 4 . 0 is the floating-point value 11.0.
2.2.2 Increment and Decrement
_ „ , , Changing a variable by adding or subtracting 1 is so common that there is a special
The ++ operator adds ° b . 1 ° & r
l to a variable; the -- shorthand for it. The ++ operator increments a variable — see Figure 2:
operator subtracts 1.
counter++; // Adds 1 to the variable counter
Similarly, the -- operator decrements a variable:
counter — ; // Subtracts 1 from counter
Figure 2 Incrementing a Variable
42 Chapter 2 Fundamental Data Types
If both arguments
of / are integers,
the remainder
is discarded.
The % operator
computes the
remainder of an
integer division.
2.2.3 Integer Division and Remainder
Division works as you would expect, as long as at least
one of the numbers involved is a floating-point number.
That is,
7.0 / 4.0
7 / 4.0
7.0 / 4
all yield 1.75. However, if both numbers are integers,
then the result of the division is always an integer, with
the remainder discarded. That is,
7 / 4
evaluates to 1 because 7 divided by 4 is 1 with a remain¬
der of 3 (which is discarded). This can be a source of
subtle programming errors — see Common Error 2.4.
If you are interested in the remainder only, use the % operator:
7 % 4
is 3, the remainder of the integer division of 7 by 4. The % symbol has no analog in alge¬
bra. It was chosen because it looks similar to /, and the remainder operation is related
to division. The operator is called modulus. (Some people call it modulo or mod.) It
has no relationship with the percent operation that you find on some calculators.
Here is a typical use for the integer / and % operations. Suppose you have an amount
of pennies in a piggybank:
int pennies = 1729;
You want to determine the value in dollars and cents. You obtain the dollars through
an integer division by 100:
int dollars = pennies / 100; // Sets dollars to 17
The integer division discards the remainder. To obtain the remainder, use the % operator:
int cents = pennies % 100; // Sets cents to 29
See Table 5 for additional examples.
Integer division and the %
operator yield the dollar and
cent values of a piggybank
full of pennies.
Table 5 Integer Division and Remainder
Expression
(where n = 1 729)
Value
Comment
n % 10
9
n % 10 is always the last digit of n .
n / 10
172
This is always n without the last digit.
n % 100
29
The last two digits of n.
n / 10.0
172.9
Because 10.0 is a floating-point number, the fractional part is not discarded.
-n % 10
-9
Because the first argument is negative, the remainder is also negative.
n % 2
1
n % 2 is 0 if n is even, 1 or -1 if n is odd.
2.2 Arithmetic 43
The java library
declares many
mathematical
functions, such as
Math.sqrt (square
root) and Math . pow
(raising to a power).
2.2.4 Powers and Roots
In Java, there are no symbols for powers and roots. To compute them, you must call
methods. To take the square root of a number, you use the Math.sqrt method. For
example, Vx is written as Math.sqrt (x). To compute*”, you write Math. pow(x, n).
In algebra, you use fractions, exponents, and roots to arrange expressions in a
compact two-dimensional form. In Java, you have to write all expressions in a linear
arrangement. For example, the mathematical expression
b x
becomes
b * Math.pow(l + r / 100, n)
Figure 3 shows how to analyze such an expression. Table 6 shows additional mathe¬
matical methods.
\n
1 + — ]
100
Figure 3
Analyzing an Expression
b * Math.pow(l + r / 100, n)
r
100
1 +-
100
( r \n
1 H -
100
b x
( „ \n
1 + -
v 1 00 j
Table 6 Mathematical Methods
Method
Returns
Math . sqrt(x)
Square root of x (a 0)
Math.powfx, y)
xy (x > 0, or x = 0 and y > 0, or x < 0 and y is an integer)
Math . si n(x)
Sine of x (x in radians)
Math . cos(x)
Cosine of x
Math.tan(x)
Tangent of x
Math.toRadians(x)
Convert x degrees to radians (i.e., returns x • jr/180)
Math.toDegrees(x)
Convert x radians to degrees (i.e., returns x • 1 80/jt)
Math.exp(x)
Math . log(x)
Natural log (ln(x), x > 0)
44
Chapter 2 Fundamental Data Types
You use a cast
(typeName) to
convert a value to a
different type.
Syntax 2.4
Table 6 Mathematical Methods
Method
Returns
Math . loglO(x)
Decimal log (log10 (x), x > 0)
Math . round(x)
Closest integer to x (as a 1 ong)
Math.abs(x)
Absolute value |x|
Math. max (x, y)
The larger of x and y
Math.min(x, y)
The smaller of x and y
2.2.5 Converting Floating-Point Numbers to Integers
Occasionally, you have a value of type doubl e that you need to convert to the type i nt.
It is an error to assign a floating-point value to an integer:
double balance = total + tax;
int dollars = balance; // Error: Cannot assign double to int
The compiler disallows this assignment because it is potentially dangerous:
• The fractional part is lost.
• The magnitude may be too large. (The largest integer is about 2 billion, but a
floating-point number can be much larger.)
You must use the cast operator (i nt) to convert a convert floating-point value to an
integer. Write the cast operator before the expression that you want to convert:
double balance = total + tax;
int dollars = (int) balance;
The cast (i nt) converts the floating-point value bal ance to an integer by discarding the
fractional part. For example, if balance is 13.75, then dollars is set to 13.
When applying the cast operator to an arithmetic expression, you need to place the
expression inside parentheses:
int dollars = (int) (total + tax);
Cast
Syntax ( typeName ) expression
This is the type of the expression after casting.
\
\
(int) (balance * 100)
Use parentheses here if
These parentheses are a the cast is applied to an expression
part of the cast operator.
with arithmetic operators.
2.2 Arithmetic 45
ONLINE EXAMPLE
A program
demonstrating casts,
rounding, and the
% operator.
Discarding the fractional part is not always appropriate. If you want to round a
floating-point number to the nearest whole number, use the Math . round method. This
method returns a long integer, because large floating-point numbers cannot be stored
in an i nt.
long rounded = Math . round(balance) ;
If balance is 13.75, then rounded is set to 14.
If you know that the result can be stored in an i nt and does not require a 1 ong, you
can use a cast:
int rounded = (i nt) Math.round(balance);
Table 7 Arithmetic Expressions
Mathematical
Expression
Java
Expression
Comments
x + y
2
(x + y) / 2
The parentheses are required;
y
x + y / 2 computes x + —
xy
T
x * y / 2
Parentheses are not required; operators with
the same precedence are evaluated left to right.
l looj
Math.pow(l + r / 100, n)
Use Math . pow(x, n) to compute x”.
y/a2 + b2
Math . sqrt(a * a + b * b)
a * a is simpler than Math . pow(a, 2).
l + J + k
3
(i + j + k) / 3.0
If i,j, and k are integers, using a denominator
of 3.0 forces floating-point division.
71
Math . PI
Math . PI is a constant declared in the Math class.
1 0. A bank account earns interest once per year. In Java, how do you compute the
interest earned in the first year? Assume variables percent and bal ance of type
doubl e have already been declared.
1 1 . In Java, how do you compute the side length of a square whose area is stored in
the variable area?
12. The volume of a sphere is given by
If the radius is given by a variable radius of type double, write a Java expression
for the volume.
1 3. What is the value of 1729 / 10 and 1729 % 10?
14. If n is a positive number, what is (n / 10) % 10?
Practice It
Now you can try these exercises at the end of the chapter: R2.3, R2.5, P2.4, P2.25.
46 Chapter 2 Fundamental Data Types
Common Error 2.4
- - f.
Common Error 2.5
■ f.
Unintended Integer Division
It is unfortunate that Java uses the same symbol, namely /, for both integer and floating-point
division. These are really quite different operations. It is a common error to use integer divi¬
sion by accident. Consider this segment that computes the average of three integers.
int scorel = 10;
int score2 = 4;
int score3 = 9;
double average = (scorel + score2 + score3) / 3; // Error
System. out. println("Average score: " + average); // Prints 7.0, not 7.666666666666667
What could be wrong with that? Of course, the average of scorel, score2, and score3 is
scorelr score2 + score3
3
Here, however, the / does not mean division in the mathematical sense. It denotes integer divi¬
sion because both scorel + score2 + score3 and 3 are integers. Because the scores add up to 23,
the average is computed to be 7, the result of the integer division of 23 by 3. That integer 7 is
then moved into the floating-point variable average. The remedy is to make the numerator or
denominator into a floating-point number:
double total = scorel + score2 + score3;
double average = total / 3;
or
double average = (scorel + score2 + score3) / 3.0;
Unbalanced Parentheses
Consider the expression
((a + b) * t / 2 * (1 - t)
What is wrong with it? Count the parentheses. There are three ( and two ). The parenthe¬
ses are unbalanced. This kind of typing error is very common with complicated expressions.
Now consider this expression.
(a + b) * t) / (2 * (1 - t)
This expression has three ( and three ), but it still is not correct. In the middle of the
expression,
(a + b) * t) / (2 * (1 - t)
t
there is only one ( but two ), which is an error. In the middle of an expression, the count of (
must be greater than or equal to the count of ), and at the end of the expression the two counts
must be the same.
Here is a simple trick to make the counting easier without using
pencil and paper. It is difficult for the brain to keep two counts
simultaneously. Keep only one count when scanning the expres¬
sion. Start with 1 at the first opening parenthesis, add 1 whenever
you see an opening parenthesis, and subtract one whenever you
see a closing parenthesis. Say the numbers aloud as you scan the
2.2 Arithmetic 47
expression. If the count ever drops below zero, or is not zero at the end, the parentheses are
unbalanced. For example, when scanning the previous expression, you would mutter
(a + b) * t) / (2 * (1 - t)
1 0-1
and you would find the error.
Spaces in Expressions
It is easier to read
xl = (-b + Math . sqrt(b * b - 4 * a 4 c)) / (2 * a) ;
than
xl=(-b+Math.sqrt(b*b-4*a*c))/(2*a) ;
Simply put spaces around all operators +-*/%=. However, don’t put a space after a unary
minus: a - used to negate a single quantity, such as -b. That way, it can be easily distinguished
from a binary minus, as in a - b.
It is customary not to put a space after a method name. That is, write Math . sqrt(x) and not
Math.sqrt (x).
Combining Assignment and Arithmetic
In Java, you can combine arithmetic and assignment. For example, the instruction
total += cans;
is a shortcut for
total = total + cans;
Similarly,
total *= 2;
is another way of writing
total = total * 2 ;
Many programmers find this a convenient shortcut. If you like it, go ahead and use it in your
own code. For simplicity, we won’t use it in this book, though.
VIDEO EXAMPLE 2.1
Using Integer Division
/wmo
rPLUS
A punch recipe calls for a given amount of orange soda. In this
Video Example, you will see how to compute the required number
of 12-ounce cans, using integer division.
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
48 Chapter 2 Fundamental Data Types
Random Fact 2.1 The Pentium Floating-Point Bug
t y In 1994, Intel Corporation released what
^ • Sr was then its most powerful processor, the
Pentium. Unlike previous generations of its processors, it
had a very fast floating-point unit. Intel's goal was to com¬
pete aggressively with the makers of higher-end processors
for engineering workstations. The Pentium was a huge suc¬
cess immediately.
In the summer of 1 994, Dr. Thomas Nicely of Lynchburg
College in Virginia ran an extensive set of computations
to analyze the sums of reciprocals of certain sequences of
prime numbers. The results were not always what his the¬
ory predicted, even after he took into account the inevitable
roundoff errors. Then Dr. Nicely noted that the same pro¬
gram did produce the correct results when running on the
slower 486 processor that preceded the Pentium in Intel’s
lineup. This should not have happened. The optimal round¬
off behavior of floating-point calculations has been stan¬
dardized by the Institute for Electrical and Electronic Engi¬
neers (IEEE) and Intel claimed to adhere to the IEEE standard
in both the 486 and the Pentium processors. Upon further
checking, Dr. Nicely discovered that indeed there was a very
small set of numbers for which the product of two num¬
bers was computed differently on the two processors. For
example,
4,1 95,835 - ((4,1 95,835/3,1 45,727) x 3,1 45,727)
is mathematically equal to 0, and it did compute as 0 on a
486 processor. On his Pentium processor the result was
256.
As it turned out, Intel had independently discovered
the bug in its testing and had started to produce chips that
fixed it. The bug was caused by an error in a table that was
used to speed up the floating-point multiplication algorithm
of the processor. Intel determined that the problem was
exceedingly rare. They claimed that under normal use, a
typical consumer would only notice the problem once every
27,000 years. Unfortunately for Intel, Dr. Nicely had not
been a normal user.
Now Intel had a real problem on its hands. It figured that
the cost of replacing all Pentium processors that it had sold
so far would cost a great deal of money. Intel already had
more orders for the chip than it could produce, and it would
be particularly galling to have to give out the scarce chips
as free replacements instead of selling them. Intel’s man¬
agement decided to punt on the issue and initially offered
to replace the processors only for those customers who
could prove that their work required absolute precision in
mathematical calculations. Naturally, that did not go over
well with the hundreds of thousands of customers who had
paid retail prices of $700 and more for a Pentium chip and
did not want to live with the nagging feeling that perhaps,
one day, their income tax program would produce a faulty
return.
Ultimately, Intel caved in to public demand and replaced
all defective chips, at a cost of about 475 million dollars.
Pentium FDIV error
1.333840000
1.333820000
1.333680000
3145727+
8?
' * 9 <? ? :
4195835+
This graph shows a set of numbers for which the original
Pentium processor obtained the wrong quotient.
2.3 Input and Output
In the following sections, you will see how to read user input and how to control the
appearance of the output that your programs produce.
2.3.1 Reading Input
You can make your programs more flexible if you ask the program user for inputs
rather than using fixed values. Consider, for example, a program that processes prices
2.3 Input and Output 49
A supermarket
scanner reads bar
codes. The Java
Scanner reads
numbers and text.
Java classes are
grouped into
packages. Use the
import statement
to use classes
from packages.
and quantities of soda containers. Prices and quantities are likely to fluctuate. The
program user should provide them as inputs.
When a program asks for user input, it should first print a message that tells the
user which input is expected. Such a message is called a prompt.
System. out. print("PJease enter the number of bottles: "); // Display prompt
Use the print method, not println, to display the prompt. You want the input to
appear after the colon, not on the following line. Also remember to leave a space after
the colon.
Because output is sent to System. out, you might think that you use System. in for
input. Unfortunately, it isn’t quite that simple. When Java was first designed, not
much attention was given to reading keyboard input. It was assumed that all pro¬
grammers would produce graphical user interfaces with text fields and menus.
System . i n was given a minimal set of features and must be combined with other classes
to be useful.
To read keyboard input, you use a class called Scanner. You obtain a Scanner object
by using the following statement:
Scanner in = new Scanner(System. in) ;
You will learn more about objects and classes in Chapter 8. For now, simply include
this statement whenever you want to read keyboard input.
When using the Scanner class, you need to carry out another step: import the class
from its package. A package is a collection of classes with a related purpose. All
classes in the Java library are contained in packages. The System class belongs to the
package j ava .Jang. The Scanner class belongs to the package j ava .util.
Only the classes in the java.lang package are automatically available in your pro¬
grams. To use the Scanner class from the java, util package, place the following decla¬
ration at the top of your program file:
import java. util .Scanner;
Once you have a scanner, you use its nextlnt method to read an integer value:
System. out. print("Please enter the number of bottles: ");
int bottles = in.nextlnt();
Syntax 2 Input Statement
Include this line so you can
use the Scanner class.
import java. util .Scanner;
Create a Scanner object
to read keyboard input.
Scanner in = new Scanner(System. i n) ; p„n't use println here.
Pisolav a prompt in the console window. -
— System. out. printf Please enter the number of bottles: );
int bottles = in.nextlnt();
mine a variable to hold the input value.
The program waits for user input,
then places the input into the variable.
50 Chapter 2 Fundamental Data Types
Use the Scanner class
to read keyboard
input in a
console window.
When the nextlnt method is called, the program waits until the user types a number
and presses the Enter key. After the user supplies the input, the number is placed into
the bottl es variable, and the program continues.
To read a floating-point number, use the nextDouble method instead:
System. out. print("Enter price: ") ;
double price = in . nextDouble() ;
2.3.2 Formatted Output
Use the printf
method to specify
how values should
be formatted.
When you print the result of a computation, you often want to control its appear¬
ance. For example, when you print an amount in dollars and cents, you usually want
it to be rounded to two significant digits. That is, you want the output to look like
Price per liter: 1.22
instead of
Price per liter: 1.215962441314554
The following command displays the price with two digits after the decimal point:
System. out. printf("%.2f", price) ;
You can also specify a field width :
System.out . printf ("%10.2f" , pri ce) ;
The price is printed using ten characters: six spaces followed by the four characters
1.22.
1.22
The construct %10 . 2f is called a format specifier: it describes how a value should be for¬
matted. The letter f at the end of the format specifier indicates that we are displaying a
floating-point number. Use d for an integer and s for a string; see Table 8 for examples.
Table 8 Format Specifier Examples
Format String
Sample Output
Comments
"%d"
24
Use d with an integer.
"%5d"
24
Spaces are added so that the field width is 5.
"Quanti ty : %5d "
Quantity: 24
Characters inside a format string but outside
format specifier appear in the output.
"%f"
1.21997
Use f with a floating-point number.
1.22
Prints two digits after the decimal point.
"%7.2f"
1.22
Spaces are added so that the field width is 7.
"%s"
Hel lo
Use s with a string.
"%d %.2f"
24 1.22
You can format multiple values at once.
2.3 Input and Output 51
You use the pri ntf method to line
up your output in neat columns.
A format string contains format specifiers and literal characters. Any characters that
are not format specifiers are printed verbatim. For example, the command
System. out. printf("Price per liter:%10.2f", price);
prints
Price per liter: 1.22
You can print multiple values with a single call to the pri ntf method. Here is a typical
example:
System. out. printf("Quantity: %d Total: %10.2f", quantity, total);
Quantity: 24 Total
r
The pri ntf method does not
width 10 start a new line here.
_ .
x
17.29
No field width was specified,
so no padding added
Two digits after
the decimal point
The pri ntf method, like the print method, does not start a new line after the output.
If you want the next output to be on a separate line, you can call System.out.println().
Alternatively, Section 2.5.4 shows you how to add a newline character to the format
string.
Our next example program will prompt for the price of a six-pack and the volume
of each can, then print out the price per ounce. The program puts to work what you
just learned about reading input and formatting output.
section_3/Volume2.java
1 import java. util .Scanner;
2
3 /**
4 This program prints the price per ounce for a six-pack of cans.
5 V
6 public class Volume2
7 {
8 public static void main(String[] args)
9 {
52 Chapter 2 Fundamental Data Types
10 // Read price per pack
1 1
12 Scanner in = new Scanner(System.in) ;
13
14 System. out. print("Please enter the price for a six-pack: ");
15 double packPrice = in.nextDouble();
16
17 // Read can volume
18
19 System. out. print("Please enter the volume for each can (in ounces): ");
20 double canVolume = in.nextDouble();
21
22 // Compute pack volume
23
24 final double CANS_PER_PACK = 6;
25 double packVolume = canVolume * CANS_PER_PACK;
26
27 // Compute and print price per ounce
28
29 double pricePerOunce = packPrice / packVolume;
30
31 System. out. printf( Price per ounce: %8.2f", pricePerOunce);
32 System. out. printlnC);
33 }
34 }
Program Run
Please enter the price for a six-pack: 2.95
Please enter the volume for each can (in ounces): 12
Price per ounce: 0.04
1 5. Write statements to prompt for and read the user’s age using a Scanner variable
named i n.
1 6. What is wrong with the following statement sequence ?
System. out. print("Please enter the unit price: ");
double unitPrice = in.nextDoubleO ;
int quantity = in.nextlntO ;
1 7. What is problematic about the following statement sequence?
System. out. print("Please enter the unit price: ") ;
double unitPrice = in.nextlntO;
1 8. What is problematic about the following statement sequence ?
System. out. print("Please enter the number of cans");
int cans = in.nextlntO;
1 9. What is the output of the following statement sequence ?
int volume = 10;
System. out. printf ("The volume is %5d", volume);
20. Using the pri ntf method, print the values of the integer variables bottl es and cans
so that the output looks like this:
Bottles: 8
Cans: 24
The numbers to the right should line up. (You may assume that the numbers
have at most 8 digits.)
2.3 Input and Output 53
Practice It Now you can try these exercises at the end of the chapter: R2.10, P2.6, P2.7.
Use the API Documentation
The classes and methods of the Java library are listed in the API doc¬
umentation. The API is the “application programming interface”.
A programmer who uses the Java classes to put together a computer
program (or application) is an application programmer. That’s you.
In contrast, the programmers who designed and implemented the
library classes (such as Scanner) are system programmers.
You can find the API documentation at http://download.oracle.eom/javase/7/docs/api. The
API documentation describes all classes in the Java library— there are thousands of them. For¬
tunately, only a few are of interest to the beginning programmer. To learn more about a class,
click on its name in the left hand column. You can then find out the package to which the class
belongs, and which methods it supports (see Figure 4). Click on the link of a method to get a
detailed description.
Appendix D contains an abbreviated version of the API documentation.
The API (Application
Programming Inter¬
face) documentation
lists the classes and
methods of the
Java library.
*> Scanner (Java Platform SE 7 ) - Mozilla Firefox
Fichier Edition Affichage Historique Marque-pages Outils Aide
♦ &
0 http://download.orade.eom/javase/7/docs/api/
javax.net
javax.net.ssl
javax.print
javax.print.attribute
javax.print.attribute.i
javax.printevent
javax.rmi
javax.rmi.CORBA
javax.rmi. ssl
javax.script
iavaiLSen iritv m il
E
0
RunTimeOperations 0
RuntimeOperationsE
RuntimePermission
SAAJ Meta Factory
SAAJResult
SafeVarargs
SampleModel
Sasl
SasJClient
SasIClientFactory
Sasl Exception
SasIServer
SasIServerFactory
Savepoint
SAX Exception
SAXNotRecognizedE
SAXNotSupportedEx
SAXParse Exception .
SAXParser
SAXParserFactory
SAXResult
SAX Source
SAXT ransformerFact«
jScanneii
ScatteringByte Cham
^trharh ilnrlPvart i
Overview Package Class Use Tree Deprecated Index Help
Prev Class Next Class Frames No Frames
Summary: Nested | Field | Constr | Method Detal: Field | Constr | Method
Java'* Platform
Standard Ed. 7
java. util
Class Scanner
java lang. Object
java.util.Scanner
All Implemented Interfaces:
Closeable, AutoCloseable, lterator<String>
public final class Scanner
extends Object
implements Iterator<String>f Closeable
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanne r breaks its input into tokens using a delimiter pattern, which by default matches
whitespace. The resulting tokens may then be converted into values of different types using
the various next methods.
For example, this code allows a user to read a number from System .in:
Scanner sc = new Scanner(System.in) ;
int i = sc.nextlnt( ) ;
As another example, this code allows long types to be assigned from entries in a file
myNumbers:
E
M.
Figure 4 The API Documentation of the Standard Java Library
54 Chapter 2 Fundamental Data Types
HOW TO 2.1
Step 1
Carrying out Computations
Many programming problems require arithmetic computations. This How To shows you
how to turn a problem statement into pseudocode and, ultimately, a Java program.
For example, suppose you are asked to write a program that simulates a vending machine.
A customer selects an item for purchase and inserts a bill into the vending machine. The vend¬
ing machine dispenses the purchased item and gives change. We will assume that all item prices
are multiples of 25 cents, and the machine gives all change in dollar coins and quarters.
Your task is to compute how many coins of each type to return.
Understand the problem: What are the inputs? What are the desired outputs?
In this problem, there are two inputs:
• The denomination of the bill that the customer inserts
• The price of the purchased item
There are two desired outputs:
• The number of dollar coins that the machine returns
• The number of quarters that the machine returns
Step 2 Work out examples by hand.
This is a very important step. If you can’t compute a couple of solutions by hand, it’s unlikely
that you’ll be able to write a program that automates the computation.
Let’s assume that a customer purchased an item that cost $2.25 and inserted a $5 bill. The
customer is due $2.75, or two dollar coins and three quarters, in change.
That is easy for you to see, but how can a Java program come to the same conclusion? The
key is to work in pennies, not dollars. The change due the customer is 275 pennies. Dividing
by 100 yields 2, the number of dollars. Dividing the remainder (75) by 25 yields 3, the number
of quarters.
Step 3 Write pseudocode for computing the answers.
In the previous step, you worked out a specific instance of the problem. You now need to
come up with a method that works in general.
Given an arbitrary item price and payment, how can you compute the coins due? First,
compute the change due in pennies:
change due = 1 00 x bill value - item price in pennies
To get the dollars, divide by 100 and discard the remainder:
dollar coins * change due / 1 00 (without remainder)
The remaining change due can be computed in two ways. If you are familiar with the modulus
operator, you can simply compute
change due * change due ^ 1 00
Alternatively, subtract the penny value of the dollar coins from the change due:
change due * change due - 1 00 x dollar coins
To get the quarters due, divide by 25:
quarters * change due / 15
2.3 Input and Output 55
Step 4
Step 5
Step 6
Step 7
Declare the variables and constants that you need, and specify their types.
Here, we have five variables:
• billValue
• itemPrice
• changeDue
• dollarCoins
• quarters
Should we introduce constants to explain 100 and 25 as PENNIES_PER_DOLLAR and PENNIES_PER_
QUARTER? Doing so will make it easier to convert the program to international markets, so we
will take this step.
It is very important that changeDue and PENNIES_PER_DOLLAR are of type int because the com¬
putation of dol 1 arCoi ns uses integer division. Similarly, the other variables are integers.
Turn the pseudocode into Java statements.
If you did a thorough job with the pseudocode, this step should be easy. Of course, you have
to know how to express mathematical operations (such as powers or integer division) in Java.
changeDue = PENNIES_PER_DOLLAR * bill Value - itemPrice;
dollarCoins = changeDue / PENNIES_PER_DOLLAR;
changeDue = changeDue % PENNIES_PER_DOLLAR;
quarters = changeDue / PENNIES_PER_QUARTER;
Provide input and output.
Before starting the computation, we prompt the user for the bill value and item price:
System. out. print("Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): ") ;
billValue = in.nextlntO;
System. out. print("Enter item price in pennies: ") ;
itemPrice = in.nextlntO;
When the computation is finished, we display the result. For extra credit, we use the printf
method to make sure that the output lines up neatly.
System. out. printf("Dollar coins: %6d", dollarCoins);
System. out. pri ntf ("Quarters : %6d", quarters);
Provide a class with a mai n method.
Your computation needs to be placed into a class. Find an appropriate name for the class that
describes the purpose of the computation. In our example, we will choose the name Vending-
Machine.
Inside the class, supply a mai n method.
A vending machine takes bills
and gives change in coins.
56 Chapter 2 Fundamental Data Types
In the mai r method, you need to declare constants and variables (Step 4), carry out compu¬
tations (Step 5), and provide input and output (Step 6). Clearly, you will want to first get the
input, then do the computations, and finally show the output. Declare the constants at the
beginning of the method, and declare each variable just before it is needed.
Here is the complete program, how_to_l/VendingMachi ne . java:
import java. util .Scanner;
/**
This program simulates a vending machine that gives change.
*/
public class Vendi ngMachine
{
public static void main(String[] args)
{
Scanner in = new Scanner(System. in) ;
final int PENNIES_PER_DOLLAR = 100;
final int PENNIES_PER_QUARTER =25;
System. out. print("Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): ") ;
int billValue = in . nextlntO ;
System. out. print("Enter item price in pennies: ");
int itemPrice = in. nextlntO;
// Compute change due
int changeDue = PENNIES_PER_DOLLAR * billValue - itemPrice;
int dollarCoins = changeDue / PENNIES_PER_DOLLAR;
changeDue = changeDue % PENNIES_PER_DOLLAR;
int quarters = changeDue / PENNIES_PER_QUARTER;
// Print change due
System. out. printf ("Dollar coins: %6d", dollarCoins);
System. out. printlnO ;
System. out. printf("Quarters: %6d", quarters);
System. out. printlnO ;
}
}
Program Run
Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): 5
Enter item price in pennies: 225
Dollar coins: 2
Quarters: 3
WORKED EXAMPLE 2.1
Computing the Cost of Stamps
This Worked Example uses arithmetic functions to simulate a stamp vending machine.
© Available online in WileyPLUS and at www.wiley.com/college/horstmann.
2.4 Problem Solving: First Do It By Hand 57
2.4 Problem Solving: First Do It By Hand
A very important step for developing an algorithm is to first carry out the computa¬
tions by hand. If you can’t compute a solution yourself, it’s unlikely that you’ll be
able to write a program that automates the computation.
To illustrate the use of hand calculations, consider the following problem.
A row of black and white tiles needs to be placed along a wall. For aesthetic rea¬
sons, the architect has specified that the first and last tile shall be black.
Your task is to compute the number of tiles needed and the gap at each end, given
the space available and the width of each tile.
Total width
Pick concrete values
for a typical situation
to use in a hand
calculation.
To make the problem more concrete, let’s assume the following dimensions:
• Total width: 100 inches
• Tile width: 5 inches
The obvious solution would be to fill the space with 20 tiles, but that would not
work— the last tile would be white.
Instead, look at the problem this way: The first tile must always be black, and then
we add some number of white/black pairs:
ONLINE EXAMPLE
A program that
implements this
algorithm.
The first tile takes up 5 inches, leaving 95 inches to be covered by pairs. Each pair is
10 inches wide. Therefore the number of pairs is 95 / 10 = 9.5. However, we need to
discard the fractional part since we can’t have fractions of tile pairs.
Therefore, we will use 9 tile pairs or 18 tiles, plus the initial black tile. Altogether,
we require 19 tiles.
The tiles span 19 x 5 = 95 inches, leaving a total gap of 100 -19x5 = 5 inches.
The gap should be evenly distributed at both ends. At each end, the gap is
(100- 19 x 5) /2 = 2.5 inches.
This computation gives us enough information to devise an algorithm with arbi¬
trary values for the total width and tile width.
number of pairs = integer part of (total width - tile width) / (lx tile width)
number of tiles = 1 *lx number of pairs
gap at each end = (total width - number of tiles x tile width) / 1
As you can see, doing a hand calculation gives enough insight into the problem that it
becomes easy to develop an algorithm.
58 Chapter 2 Fundamental Data Types
2 1 . Translate the pseudocode for computing the number of tiles and the gap width
into Java.
22. Suppose the architect specifies a pattern with black, gray, and white tiles, like
this:
r
i
Again, the first and last tile should be black. How do you need to modify the
algorithm?
23. A robot needs to tile a floor with alternating black and white tiles. Develop
an algorithm that yields the color (0 for black, 1 for white), given the row and
column number. Start with specific values for the row and column, and then
generalize.
12 3 4
1
2
3
4
24. For a particular car, repair and maintenance costs in year 1 are estimated at $100;
in year 10, at $1,500. Assuming that the repair cost increases by the same amount
every year, develop pseudocode to compute the repair cost in year 3 and then
generalize to year w.
25. The shape of a bottle is approximated by two cylinders of radius rj and r2 and
heights h-^ and A2, joined by a cone section of height hi,.
Using the formulas for the volume of a cylinder, V = nr2h, and a cone section,
(rf + rft + rijh
V = 7C- - —
3
develop pseudocode to compute the volume of the bottle. Using an actual bottle
with known volume as a sample, make a hand calculation of your pseudocode.
Practice It Now you can try these exercises at the end of the chapter: R2.15, R2.17, R2.18.
WORKED EXAMPLE 2.2
Computing Travel Time
In this Worked Example, we develop a hand calculation to compute
the time that a robot requires to retrieve an item from rocky terrain.
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
2.5 Strings 59
2.5 Strings
Strings are sequences
of characters.
Many programs process text, not numbers. Text
consists of characters: letters, numbers, punc¬
tuation, spaces, and so on. A string is a sequence
of characters. For example, the string "Harry" is a
sequence of five characters.
The length method
yields the number
of characters in
a string.
2.5.1 The String Type
You can declare variables that hold strings.
String name = "Harry";
We distinguish between string variables (such as the variable name declared above) and
string literals (character sequences enclosed in quotes, such as "Harry"). A string vari¬
able is simply a variable that can hold a string, just as an integer variable can hold an
integer. A string literal denotes a particular string, just as a number literal (such as 2)
denotes a particular number.
The number of characters in a string is called the length of the string. For exam¬
ple, the length of "Harry" is 5. You can compute the length of a string with the length
method.
int n = name.lengthO;
A string of length 0 is called the empty string. It contains no characters and is written
2.5.2 Concatenation
Use the + operator to
concatenate strings;
that is, to put them
together to yield a
longer string.
Given two strings, such as "Harry" and "Morgan", you can concatenate them to one
long string. The result consists of all characters in the first string, followed by all
characters in the second string. In Java, you use the + operator to concatenate two
strings.
For example,
String fName = "Harry";
String IName = "Morgan";
String name = fName + IName;
results in the string
"HarryMorgan"
What if you’d like the first and last name separated by a space? No problem:
String name = fName + " " + IName;
This statement concatenates three strings: fName, the string literal " ", and IName. The
result is
"Harry Morgan"
When the expression to the left or the right of a + operator is a string, the other one
is automatically forced to become a string as well, and both strings are concatenated.
60 Chapter 2 Fundamental Data Types
Whenever one of
the arguments of the
+ operator is a string,
the other argument is
converted to
a string.
For example, consider this code:
String jobTitfe = "Agent";
int employeeld = 7;
String bond = jobTitle + employeeld;
Because jobTitle is a string, employeeld is converted from the integer 7 to the string "7".
Then the two strings "Agent" and "7" are concatenated to form the string "Agent7".
This concatenation is very useful for reducing the number of System. out. print
instructions. For example, you can combine
System. out. print("The total is ");
System . out . pri ntl n (total ) ;
to the single call
System. out. println("The total is " + total);
The concatenation "The total is " + total computes a single string that consists of the
string "The total i s ", followed by the string equivalent of the number total .
Use the next method
of the Scanner class
to read a string
containing a
single word.
2.5.3 String Input
You can read a string from the console:
System. out. print("Please enter your name: ");
String name = in.nextO;
When a string is read with the next method, only one word is read. For example, sup¬
pose the user types
Harry Morgan
as the response to the prompt. This input consists of two words. The call in.nextO
yields the string "Harry". You can use another call to in.nextO to read the second word.
2.5.4 Escape Sequences
To include a quotation mark in a literal string, precede it with a backslash (\), like this:
"He said \' Hello\""
The backslash is not included in the string. It indicates that the quotation mark that
follows should be a part of the string and not mark the end of the string. The sequence
\" is called an escape sequence.
To include a backslash in a string, use the escape sequence \\, like this:
"C : \\T emp\\Sec ret . txt"
Another common escape sequence is \n, which denotes a newline character. Print¬
ing a newline character causes the start of a new line on the display. For example, the
statement
System. out . print ("*\n**\n***\n") ;
prints the characters
*
***
on three separate lines.
2.5 Strings 61
You often want to add a newline character to the end of the format string when
you use System . out . pri ntf:
System. out. printf ("Price: %10.2f\n", price);
String positions are
counted starting
with 0.
2.5.5 Strings and Characters
Strings are sequences of Unicode characters (see Random
Fact 2.2). In Java, a character is a value of the type char.
Characters have numeric values. You can find the values
of the characters that are used in Western European lan¬
guages in Appendix A. For example, if you look up the
value for the character ' H ' , you can see that is actually
encoded as the number 72.
Character literals are delimited by single quotes, and you should not confuse them
with strings.
• ' H 1 is a character, a value of type char.
• "H" is a string containing a single character, a value of type Stri ng.
The charAt method returns a char value from a string. The first string position is
labeled 0, the second one 1, and so on.
Harry
0 12 3 4
The position number of the last character (4 for the string "Harry") is always one less
than the length of the string.
For example, the statement
String name = "Harry";
char start = name.charAt(O) ;
char last = name.charAt(4) ;
sets start to the value ' H ’ and last to the value ' y ' .
WORD
A string is a sequence of
characters.
2.5.6 Substrings
Use the substring
method to extract a
part of a string.
Once you have a string, you can extract substrings by using the substring method.
The method call
str.substring(start, pastEnd)
returns a string that is made up of the characters in the string str, starting at posi¬
tion start, and containing all characters up to, but not including, the position pastEnd.
Here is an example:
String greeting = "Hello, World!";
String sub = greeting. substrings, 5); // sub is "Hello"
The substring operation makes a string that consists of the first five characters taken
from the string greeting.
Hello, World!
0123456789 10 11 12
62 Chapter 2 Fundamental Data Types
Let’s figure out how to extract the substring "World". Count characters starting at 0,
not 1. You find that W has position number 7. The first character that you don’t want,
! , is the character at position 12. Therefore, the appropriate substring command is
String sub2 = greeting. substring^, 12);
5
_ A _
f S
Hello, World!
0 1 2 3 4 5 6 + 7 8 9 10 11+12
It is curious that you must specify the position of the first character that you do want
and then the first character that you don’t want. There is one advantage to this setup.
You can easily compute the length of the substring: It is pastEnd - start. For example,
the string "World" has length 12-7 = 5.
If you omit the end position when calling the substri ng method, then all characters
from the starting position to the end of the string are copied. For example,
String tail = greeting. substring(7); // Copies all characters from position 7 on
sets tail to the string "World!".
Following is a simple program that puts these concepts to work. The program asks
for your name and that of your significant other. It then prints out your initials.
The operation first.substring(0, 1) makes a
string consisting of one character, taken from the
start of fi rst. The program does the same for the
second. Then it concatenates the resulting one-
character strings with the string literal to get
a string of length 3, the initials string. (See
Figure 5.)
Figure 5 Building the initials String
Initials are formed from the first
letter of each name.
section_5/lnitials.java
1 import java. util .Scanner;
2
3 /**
4 This program prints a pair of initials.
5 */
6 public class Initials
7 {
8 public static void main(String[] args)
9 {
10 Scanner in = new Scanner(System.in) ;
2.5 Strings 63
12 // Get the names of the couple
13
14 System. out. print("Enter your first name: );
15 String first = in.nextO;
16 System. out. print("Enter your significant other's first name: ");
17 String second = in.nextO;
18
19 // Compute and display the inscription
20
21 String initials = first. substring(0, 1)
22 + + second. substring(0, 1);
23 System. out. println (initials) ;
24 }
25 }
Program Run
Enter your first name: Rodolfo
Enter your significant other's first name: Sally
R&S
Table 9 String Operations
Statement
Result
Comment
string str = "la";
str = str + "va" ;
str is set to "lava"
When applied to strings,
+ denotes concatenation.
System. out . pri ntln("Please"
+ " enter your name: ") ;
Prints
Please enter your name:
Use concatenation to break up strings
that don’t fit into one line.
team = 49 + "ers"
team is set to "49ers"
Because "ers" is a string, 49 is converted
to a string.
String first = in.nextO;
String last = in.nextO;
(User input: Harry Morgan)
fi rst contains "Harry"
last contains "Morgan"
The next method places the next word
into the string variable.
String greeting = "H & S";
int n = greeting. length() ;
n is set to 5
Each space counts as one character.
String str = "Sally";
char ch = str.charAt(l) ;
ch is set to 'a'
This is a char value, not a Stri ng. Note
that the initial position is 0.
String str = "Sally";
String str2 = str.substring(l, 4);
str2 is set to "all"
Extracts the substring starting at
position 1 and ending before position 4.
String str = "Sally";
String str2 = str.substring(l) ;
str2 is set to "ally"
If you omit the end position, all
characters from the position until the
end of the string are included.
String str = "Sally";
String str2 = str.substring(l, 2);
str2 is set to "a"
Extracts a Stri ng of length
1; contrast with str.charAt(l).
String last = str.substring(
str.lengthO - 1);
1 ast is set to the string
containing the last
character in str
The last character has position
str.lengthO - 1.
64 Chapter 2 Fundamental Data Types
26. What is the length of the string "Java Program"?
2 7. Consider this string variable.
String str = "Java Program";
Give a call to the substri ng method that returns the substring "gram".
28. Use string concatenation to turn the string variable str from Self Check 27 into
"Java Programming".
29. What does the following statement sequence print?
String str = "Harry";
int n = str.JengthO;
String mystery = str.substring(0, 1) + str.substring(n - 1, n) ;
System. out. print! n (mystery) ;
30. Give an input statement to read a name of the form “John Q. Public”.
Practice It
Now you can try these exercises at the end of the chapter: R2.7, R2.ll, P2.15, P2.23.
Instance Methods and Static Methods
In this chapter, you have learned how to read, process, and print numbers and strings. Many of
these tasks involve various method calls. You may have noticed syntactical differences in these
method calls. For example, to compute the square root of a number num, you call Math . sqrt(num),
but to compute the length of a string str, you call str.JengthO. This section explains the rea¬
sons behind these differences.
The Java language distinguishes between values of primitive types and objects. Numbers
and characters, as well as the values fal se and true that you will see in Chapter 3, are primitive.
All other values are objects. Examples of objects are
• a string such as "Hello".
• a Scanner object obtained by calling in = new Scanner(System.in).
• System. in and System. out.
In Java, each object belongs to a class. For example,
• All strings are obj ects of the String class.
• A scanner object belongs to the Scanner class.
• System, out is an object of the PrintStream class. (It is useful to know this so that you can
look up the valid methods in the API documentation; see Programming Tip 2.4 on page 53.)
A class declares the methods that you can use with its objects. Here are examples of methods
that are invoked on objects:
"Hel lo" .substri ng(0, 1)
in.nextDoubleO
System. out. pri ntl n ("Hello")
A method is invoked with the dot notation: the object is followed by the name of the method,
and the method is followed by parameters enclosed in parentheses.
The method is This is the These parameters are
invoked on this object. name of the method, inputs to the method.
\ \ /
System. out. pri ntl n ("Hello")
You cannot invoke methods on numbers. For example, the call 2 . sqrtQ would be an error.
2.5 Strings 65
In Java, classes can declare methods that are not invoked on objects. Such methods are called
static methods. (The term “static” is a historical holdover from the C and C++ programming
languages. It has nothing to do with the usual meaning of the word.) For example, the Math
class declares a static method sqrt. You call it by giving the name of the class and method, then
the name of the numeric input: Math, sqrt (2).
The name of the class ^ The name of the static method
Math . sqrt(2)
In contrast, a method that is invoked on an object is called an instance method. As a rule of
thumb, you use static methods when you manipulate numbers. You use instance methods
when you process strings or perform input/output. You will learn more about the distinction
between static and instance methods in Chapter 8.
Using Dialog Boxes for Input and Output
Most program users find the console window rather old-fashioned. The easiest alternative is
to create a separate pop-up window for each input.
An Input Dialog Box
ONLINE EXAMPLE
© A complete program
that uses option
panes for input
and output.
Call the static showInputDialog method of the lOptionPane class, and supply the string that
prompts the input from the user. For example,
String input = ]OptionPane.showInputDialog("Enter price:");
That method returns a Stri ng object. Of course, often you need the input as a number. Use the
Integer . parselnt and Double . parseDoubl e methods to convert the string to a number:
double price = Double. parseDouble(input) ;
You can also display output in a dialog box:
]OptionPane.showMessageDialog(null , "Price: " + price);
VIDEO EXAMPLE 2.2
Computing Distances on Earth
^WILEYO
’PLUS
In this Video Example, you will see how to write a program that
computes the distance between any two points on Earth.
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
66 Chapter 2 Fundamental Data Types
Random Fact 2.2 International Alphabets and Unicode
The English alpha¬
bet is pretty simple:
upper- and lowercase a to z. Other
European languages have accent marks
and special characters. For example,
German has three so-called umlaut
characters, a, o, u, and a doubles char¬
acter li. These are not optional frills;
you couldn’t write a page of German
text without using these characters
a few times. German keyboards have
keys for these characters.
e v e o a -
I I I I | I | I 1 1 III
2 U 1 O P I U
i | 1 | 1 , i , i , I
H J K L a A
B N M
The German Keyboard Layout
Many countries don’t use the Roman
script at all. Russian, Greek, Hebrew,
Arabic, and Thai letters, to name just a
few, have completely different shapes.
To complicate matters, Hebrew and
Arabic are typed from right to left. Each
of these alphabets has about as many
characters as the English alphabet.
...
nx "laya1? D’xan D’ana
^-l1
WELCOME TO
EREZ CROSSING POINT
il
called Unicode that is capable of
encoding text in essentially all written
languages of the world. An early ver¬
sion of Unicode used 1 6 bits for each
character. The Java char type corre¬
sponds to that encoding.
Today Unicode has grown to a
21 -bit code, with definitions for over
100,000 characters. There are even
plans to add codes for extinct lan¬
guages, such as Egyptian hieroglyph¬
ics. Unfortunately, that means that a
Java char value does not always cor¬
respond to a Unicode character. Some
characters in languages such as Chi¬
nese or ancient Egyptian occupy two
char values.
Hebrew, Arabic, and English
The Chinese languages as well as
Japanese and Korean use Chinese char¬
acters. Each character represents an
idea or thing. Words are made up of
one or more of these ideographic char¬
acters. Over 70,000 ideographs are
known.
Starting in 1988, a consortium of
hardware and software manufacturers
developed a uniform encoding scheme
. . Z) — -
A A
1 Domestic Arrivals r\
ilb ni'M [
^ Infl/Hk, Macao, Taiwan Arrivals 1
31
A ra
1 Departures
_ » w _
4F
| Fig
The Chinese Script
CHAPTER SUMMARY
Declare variables with appropriate names and types.
A variable is a storage location with a name.
When declaring a variable, you usually specify an
initial value.
When declaring a variable, you also specify the type
of its values.
Use the i nt type for numbers that cannot have a fractional part.
Use the doubl e type for floating-point numbers.
By convention, variable names should start with a lowercase letter.
An assignment statement stores a new value in a variable, replacing
the previously stored value.
The assignment operator = does not denote mathematical equality.
'Vt
Chapter Summary 67
• You cannot change the value of a variable that is defined as fi nal
• Use comments to add explanations for humans who read your
code. The compiler ignores comments.
Write arithmetic expressions in Java.
Mixing integers and floating-point values in an arithmetic expression yields a
floating-point value.
The ++ operator adds 1 to a variable; the -- operator subtracts 1 .
If both arguments of / are integers, the remainder is discarded.
The % operator computes the remainder of an integer division.
The Java library declares many mathematical functions, such as Math . sqrt (square
root) and Math . pow (raising to a power).
You use a cast ( typeName ) to convert a value to a different type.
Write programs that read user input and print formatted output.
• Java classes are grouped into packages. Use the import statement to use classes
from packages.
• Use the Scanner class to read keyboard input in a console window.
• Use the pri ntf method to specify how values should be
formatted.
• The API (Application Programming Interface)
documentation lists the classes and methods of the
Java library.
Carry out hand calculations when developing an algorithm.
• Pick concrete values for a typical situation to use in a hand calculation.
Write programs that process strings.
• Strings are sequences of characters.
• The 1 ength method yields the number of characters in
a string.
• Use the + operator to concatenate strings; that is, to put them together to yield a
longer string.
• Whenever one of the arguments of the + operator is a string, the other argument is
converted to a string.
• Use the next method of the Scanner class to read a string containing
a single word.
• String positions are counted starting with 0.
• Use the substring method to extract a part of a string.
WORD
68 Chapter 2 Fundamental Data Types
STANDARD LIBRARY ITEMS INTRODUCED IN THIS CHAPTER
java.io.PrintStream
max
j ava . math . Bi gDeci mal
printf
mi n
add
java. lang. Double
pow
multiply
parseDouble
round
subtract
java. lang. Integer
si n
j ava. math. Biglnteger
MAX„VALUE
sqrt
add
MIN_VALUE
tan
multiply
parselnt
toDegrees
subtract
java. lang. Math
toRadians
java. util .Scanner
PI
java. lang. String
next
abs
charAt
nextDouble
cos
length
nextlnt
exp
substri ng
javax . swi ng . lOpti onPane
log
java. lang. System
showInputDialog
loglO
i n
showMessageDialog
REVIEW EXERCISES
. R2.1 What is the value of mystery after this sequence of statements?
int mystery = 1;
mystery = 1 - 2 * mystery;
mystery = mystery + 1;
. R2.2 What is wrong with the following sequence of statements?
int mystery = 1;
mystery = mystery + 1;
int mystery = 1 - 2 * mystery;
■ ■ R2.3 Write the following mathematical expressions in Java.
1 7
S = 50 + V0t + -gt~
G = 4k2 -
p2(m j + m2)
FV = PV
1 +
INT JYRS
100 J
C =
\[a
2 + b2 - lab
cosy
■ ■ R2 .4 Write the following J ava expressions in mathematical notation.
a. dm = m * (Math.sqrt(l + v / c) / Math.sqrt(l - v / c) - 1) ;
b. volume = Math. PI * r * r * h;
C. volume = 4 * Math. PI * Math.pow(r, 3) / 3;
d. z = Math.sqrt(x * x + y * y) ;
.. R2.5 What are the values of the following expressions? In each line, assume that
double x = 2.5;
double y = -1.5;
Review Exercises 69
int m = 18;
int n = 4;
a. x + n * y - (x + n) * y
b. m/n+m%n
C. 5 * x - n / 5
d. 1 - (1 - (1 - (1 - (1 - n))))
e. Math.sqrt(Math.sqrt(n))
R2.6 What are the values of the following expressions, assuming that n is 17 and m is 18?
a. n / 10 + n % 10
b, n%2 + m%2
C. (m + n) / 2
d. (m + n) / 2.0
e. (int) (0.5 * (m + n) )
f. (int) Math.round(0.5 * (m + n))
R2.7 What are the values of the following expressions? In each line, assume that
String s = "Hello";
String t = "World";
a. s.lengthO + t.length()
b. s.substring(l, 2)
C. s.substring(s.length() / 2, s.lengthO)
d. s + t
e. t + s
R2.8 Find at least five compile-time errors in the following program.
public class HasErrors
{
public static void main();
{
System. out. print(Please enter two numbers:)
x = in. readDouble;
y = in. readDouble;
System. out. printline("The sum is " + x + y);
}
}
R2.9 Find three run-time errors in the following program.
public class HasErrors
{
public static void main(String[] args)
{
int x = 0;
int y = 0;
Scanner in = new Scanner("System.in") ;
System. out. print("Please enter an integer:");
x = in. readlntO ;
System. out. print("Please enter another integer: ");
x = in. readlntO ;
System. out. println("The sum is " + x + y) ;
}
70 Chapter 2 Fundamental Data Types
■ R2. 1 0 Consider the following code segment.
double purchase = 19.93;
double payment = 20.00;
double change = payment - purchase;
System. out. println (change) ;
The code segment prints the change as 0.07000000000000028. Explain why. Give a
recommendation to improve the code so that users will not be confused.
■ R2.1 1 Explain the differences between 2, 2.0, '2', "2", and "2.0".
■ R2.1 2 Explain what each of the following program segments computes.
a. x = 2;
y = x + x;
b. s = "2";
t = s + s;
■ ■ R2.1 3 Write pseudocode for a program that reads a word and then prints the first character,
the last character, and the characters in the middle. For example, if the input is Harry,
the program prints H y arr.
■ ■ R2.14 Write pseudocode for a program that reads a name (such as Harold James Morgan)and
then prints a monogram consisting of the initial letters of the first, middle, and last
name (such as HJM).
■ ■ ■ R2. 1 5 Write pseudocode for a program that computes the first and last digit of a num¬
ber. For example, if the input is 23456, the program should print 2 and 6. Hint: %,
Math.loglO.
■ R2.1 6 Modify the pseudocode for the program in How To 2.1 so that the program gives
change in quarters, dimes, and nickels. You can assume that the price is a multiple of
5 cents. To develop your pseudocode, first work with a couple of specific values.
■ ■ R2.1 7 A cocktail shaker is composed of three cone sections.
Using realistic values for the radii and heights, compute the total
volume, using the formula given in Self Check 25 for a cone section.
Then develop an algorithm that works for arbitrary dimensions.
■ ■ ■ R2. 1 8 You are cutting off a piece of pie like this, where c is the length of the
straight part (called the chord length) and h is the height of the piece.
There is an approximate formula for the area:
A »
fch +
P
2c
Programming Exercises 71
However, h is not so easy to measure, whereas the diameter d of a pie is usually
well-known. Calculate the area where the diameter of the pie is 12 inches and the
chord length of the segment is 10 inches. Generalize to an algorithm that yields the
area for any diameter and chord length.
■ ■ R2.19 The following pseudocode describes how to obtain the name of a day, given the day
number (0 = Sunday, 1 = Monday, and so on.)
Peclare a string called names containing "SunMonTueWedThuFriSat".
Compute the starting position as 3 x the day number.
Extract the substring of names at the starting position with length 3.
Check this pseudocode, using the day number 4. Draw a diagram of the string that is
being computed, similar to Figure 5.
■ ■ ■ R2.20 The following pseudocode describes how to swap two letters in a word.
We are given a string str and two positions i and j. (i comes before j)
Set first to the substring from the start of the string to the last position before i.
Set middle to the substring from positions i + 1 to j - 1 .
Set last to the substring from position j + 1 to the end of the string.
Concatenate the following five strings: first, the string containing just the character at position j,
middle, the string containing just the character at position i, and last.
Check this pseudocode, using the string "Gateway" and positions 2 and 4. Draw a
diagram of the string that is being computed, similar to Figure 5.
■ ■ R2.2 1 How do you get the first character of a string? The last character? How do you
remove the first character? The last character?
■ ■ ■ R2.22 Write a program that prints the values
3 * 1000 * 1000 * 1000
3.0 * 1000 * 1000 * 1000
Explain the results.
■ R2.23 This chapter contains a number of recommendations regarding variables and con¬
stants that make programs easier to read and maintain. Briefly summarize these
recommendations.
PROGRAMMING EXERCISES
■ P2.1 Write a program that displays the dimensions of a letter-size (8.5 x 1 1 inches) sheet
of paper in millimeters. There are 25.4 millimeters per inch. Use constants and com¬
ments in your program.
■ P2.2 Write a program that computes and displays the perimeter of a letter-size (8.5 x 1 1
inches) sheet of paper and the length of its diagonal.
■ P2.3 Write a program that reads a number and displays the square, cube, and fourth
power. Use the Math . pow method only for the fourth power.
■ ■ P2.4 Write a program that prompts the user for two integers and then prints
• The sum
• The difference
72
Chapter 2 Fundamental Data Types
• The product
• The average
• The distance (absolute value of the difference)
• The maximum (the larger of the two)
• The minimum (the smaller of the two)
Hint: The max and mi n functions are declared in the Math class.
■ ■ P2.5 Enhance the output of Exercise P2.4 so that the numbers are properly aligned:
Sum:
45
Difference:
-5
Product:
500
Average:
22.50
Distance:
5
Maximum:
25
Minimum:
20
■ ■ P2.6 Write a program that prompts the user for a measurement in meters and then con¬
verts it to miles, feet, and inches.
■ P2.7 Write a program that prompts the user for a radius and then prints
• The area and circumference of a circle with that radius
• The volume and surface area of a sphere with that radius
■ ■ P2.8 Write a program that asks the user for the lengths of the sides of a rectangle. Then
print
• The area and perimeter of the rectangle
• The length of the diagonal (use the Pythagorean theorem)
■ P2.9 Improve the program discussed in How To 2.1 to allow input of quarters in addition
to bills.
■ ■■ P2.10 Write a program that helps a person decide whether to buy a hybrid car. Your
program’s inputs should be:
• The cost of a new car
• The estimated miles driven per year
• The estimated gas price
• The efficiency in miles per gallon
• The estimated resale value after 5 years
Compute the total cost of owning the car for
five years. (For simplicity, we will not take the
cost of financing into account.) Obtain
realistic prices for a new and used hybrid
and a comparable car from the Web. Run your program twice, using today’s gas
price and 1 5,000 miles per year. Include pseudocode and the program runs with your
assignment.
■ ■ P2.ll Write a program that asks the user to input
• The number of gallons of gas in the tank
• The fuel efficiency in miles per gallon
• The price of gas per gallon
Programming Exercises 73
Then print the cost per 100 miles and how far the car can go with the gas in the tank.
P2.12 File names and extensions. Write a program that prompts the user for the drive letter
(C), the path (\Windows\System), the file name (Readme), and the extension (txt). Then
print the complete file name C : \Wi ndows\System\Readme . txt. (If you use UNIX or a
Macintosh, skip the drive name and use / instead of \ to separate directories.)
P2.1 3 Write a program that reads a number between 1,000 and 999,999 from the user,
where the user enters a comma in the input. Then print the number without a
comma. Here is a sample dialog; the user input is in color:
Please enter an integer between 1,000 and 999,999: 23,456
23456
Hint: Read the input as a string. Measure the length of the string. Suppose it contains
n characters. Then extract substrings consisting of the first n — 4 characters and the
last three characters.
P2.14 Write a program that reads a number between 1,000 and 999,999 from the user and
prints it with a comma separating the thousands. Here is a sample dialog; the user
input is in color:
Please enter an integer between 1000 and 999999: 23456
23,456
P2. 1 5 Printing a grid. Write a program that prints the following grid to play tic-tac-toe.
+ —
I I I I
+ — +--+—+
I I I I
+ — + — + — +
I I I I
+ — + — + — +
Of course, you could simply write seven statements of the form
System . out . pri ntl n ;
You should do it the smart way, though. Declare string variables to hold two kinds
of patterns: a comb-shaped pattern and the bottom line. Print the comb three times
and the bottom line once.
P2. 1 6 Write a program that reads in an integer and breaks it into a sequence of individual
digits. For example, the input 16384 is displayed as
1 6 3 8 4
You may assume that the input has no more than five digits and is not negative.
P2.1 7 Write a program that reads two times in military format (0900, 1730) and prints the
number of hours and minutes between the two times. Here is a sample run. User
input is in color.
Please enter the first time: 0900
Please enter the second time: 1730
8 hours 30 minutes
Extra credit if you can deal with the case where the first time is later than the second:
Please enter the first time: 1730
Please enter the second time: 0900
15 hours 30 minutes
74
Chapter 2 Fundamental Data Types
■ ■ ■ P2. 1 8 Writing large letters. A large letter H can be produced like this:
* *
*****
* *
It can be declared as a string literal like this:
final string LETTERJ = "* *\n* *\n*****\n* *\n* *\n";
(The \n escape sequence denotes a “newline” character that causes subsequent
characters to be printed on a new line.) Do the same for the letters E, L, and 0. Then
write the message
H
E
L
L
0
in large letters.
■ ■ P2.19 Write a program that transforms numbers 1, 2, 3, ..., 12
into the corresponding month names January, February,
March, ..., December. Hint: Make a very long string "January
February March ... ", in which you add spaces such that each
month name has the same length. Then use substring to
extract the month you want.
■ ■ P2.20 Write a program that prints a Christmas tree:
A'
/ V
/ V
/ V
Remember to use escape sequences.
■ ■ P2.2 1 Easter Sunday is the first Sunday after the first full moon of spring. To compute
the date, you can use this algorithm, invented by the mathematician Carl Friedrich
Gauss in 1800:
1 . Let y be the year (such as 1800 or 2001).
2. Divide y by 19 and call the remainder a. Ignore the quotient.
3. Divide y by 100 to get a quotient b and a remainder c.
4. Divide b by 4 to get a quotient d and a remainder e.
5. Divide 8 * b + 13 by 25 to get a quotient g. Ignore the remainder.
6. Divide 19 * a + b - d - g + 15 by 30 to get a remainder h. Ignore the quotient.
7. Divide c by 4 to get a quotient j and a remainder k.
8. Divide a + 11 * h by 319 to get a quotient m. Ignore the remainder.
9. Divide 2*e + 2*j-k-h + m + 32by7to get a remainder r. Ignore the
quotient.
Programming Exercises 75
1 0. Divide h - m + r + 90 by 25 to get a quotient n. Ignore the remainder.
1 1 . Divide h - m + r + n + 19 by 32 to get a remainder p. Ignore the quotient.
Then Easter falls on day p of month n. For example, if y is 2001:
a = 6
h = 18
n = 4
b = 20, c = 1
i _ i.
II
O
7^
II
1—*
p = 15
d = 5, e = 0
m = 0
to
II
CD
r = 6
Therefore, in 2001, Easter Sunday fell on April 15. Write a program that prompts the
user for a year and prints out the month and day of Easter Sunday.
Business P2.22 The following pseudocode describes how a bookstore computes the price of an
order from the total price and the number of the books that were ordered.
Read the total book price and the number of books.
Compute the tax (7.5 percent of the total book price).
Compute the shipping charge VI per book).
The price of the order is the sum of the total book price, the tax, and the shipping charge.
Print the price of the order.
Translate this pseudocode into a Java program.
Business P2.23 The following pseudocode describes how to turn a string containing a ten-digit
phone number (such as "4155551212") into a more readable string with parentheses
and dashes, like this: "(415) 555-1212".
Take the substring consisting of the first three characters and surround it with T and ”) This is the
area code.
Concatenate the area code, the substring consisting of the next three characters, a hyphen, and the
substring consisting of the last four characters. This is the formatted number.
Translate this pseudocode into a Java program that reads a telephone number into a
string variable, computes the formatted number, and prints it.
Business P2.24 The following pseudocode describes how to extract the dollars and cents from a
price given as a floating-point value. For example, a price 2.95 yields values 2 and 95
for the dollars and cents.
Assign the price to an integer variable dollars.
Multiply the difference price - dollars by 1 00 and add 0.5.
Assign the result to an integer variable cents.
Translate this pseudocode into a Java program. Read a price and print the dollars and
cents. Test your program with inputs 2.95 and 4.35.
Business P2.25 Giving change. Implement a program that directs a cashier
how to give change. The program has two inputs: the
amount due and the amount received from the customer.
Display the dollars, quarters, dimes, nickels, and pennies
that the customer should receive in return. In order to avoid
roundoff errors, the program user should supply both
amounts in pennies, for example 274 instead of 2.74.
Business P2.26 An online bank wants you to create a program that shows prospective customers
how their deposits will grow. Your program should read the initial balance and the
76 Chapter 2 Fundamental Data Types
annual interest rate. Interest is compounded monthly. Print out the balances after the
first three months. Here is a sample run:
Initial balance: 1000
Annual interest rate in percent: 6.0
After first month: 1005.00
After second month: 1010.03
After third month: 1015.08
■ Business P2.27 A video club wants to reward its best members with a discount based on the mem¬
ber’s number of movie rentals and the number of new members referred by the
member. The discount is in percent and is equal to the sum of the rentals and the
referrals, but it cannot exceed 75 percent. {Hint: Math. min.) Write a program Discount-
Cal cul ator to calculate the value of the discount.
Here is a sample run:
Enter the number of movie rentals: 56
Enter the number of members referred to the video club: 3
The discount is equal to: 59.00 percent.
■ Science P2.28 Consider the following circuit.
I
r2
*3
T
J
Write a program that reads the resistances of the three resistors and computes the
total resistance, using Ohm’s law.
■ ■ Science P2.29 The dew point temperature T j can be calculated (approximately) from the relative
humidity RH and the actual temperature T by
b ■ f(T,RH)
a- f(T,RH)
f(T’RH) = jTT + 'a(RH)
where a = 17.27 and b = 237.7° C.
Write a program that reads the relative humidity (between 0 and 1) and the tem¬
perature (in degrees C) and prints the dew point value. Use the Java function log to
compute the natural logarithm.
■ ■ ■ Science P2.30 The pipe clip temperature sensors shown here are robust sensors that can be clipped
directly onto copper pipes to measure the temperature of the liquids in the pipes.
Programming Exercises 77
Each sensor contains a device called a thermistor. Thermistors are semiconductor
devices that exhibit a temperature-dependent resistance described by:
R — Rq e
T~fi
°
where R is the resistance (in £2) at the temperature T (in °K), and Rq is the resistance
(in Q) at the temperature T0 (in °K). /> i s a constant that depends on the material used
to make the thermistor. Thermistors are specified by providing values for R0, 7q,
and
The thermistors used to make the pipe clip temperature sensors have R0 = 1075 Q at
T0 = 85 °C, and = 3969 °K. (Notice that /3 has units of °K. Recall that the tempera¬
ture in °K is obtained by adding 273 to the temperature in °C.) The liquid tempera¬
ture, in °C, is determined from the resistance R, in Q, using
T =
PT0
TQln
‘ R X
V 0 7
+ P
- 273
Write a Java program that prompts the user for the thermistor resistance R and prints
a message giving the liquid temperature in °C.
■ ■■ Science P2.31 The circuit shown below illustrates some impor¬
tant aspects of the connection between a power
company and one of its customers. The customer is
represented by three parameters, Vt, P, and pf. Vt is
the voltage accessed by plugging into a wall outlet.
Customers depend on having a dependable value
of in order for their appliances to work prop¬
erly. Accordingly, the power company regulates
the value of Vt carefully. P describes the amount of
power used by the customer and is the primary factor in determining the customer’s
electric bill. The power factor, pf, is less familiar. (The power factor is calculated as
the cosine of an angle so that its value will always be between zero and one.) In this
problem you will be asked to write a Java program to investigate the significance of
the power factor.
Power
Company
vvv
R = \0Q.
i? = 10 Q
AAA
+
vt= 120 Vrms
T
P = 260 W
Pf= 0-6
vvv
Power
Lines
Customer
78 Chapter 2 Fundamental Data Types
In the figure, the power lines are represented, somewhat simplistically, as resistances
in Ohms. The power company is represented as an AC voltage source. The source
voltage, Vs, required to provide the customer with power P at voltage Vt can be
determined using the formula
V =
v, + ™
1 V
V Vt J
+
2 RP
JfVtj
\2
(l - Pt
(Vs has units of Vrms.) This formula indicates that the value of Vs depends on the
value of pf. Write a Java program that prompts the user for a power factor value and
then prints a message giving the corresponding value of Vs, using the values for P, R,
and Vt shown in the figure above.
■ ■ ■ Science P2.32 Consider the following tuning circuit connected to an antenna, where C is a variable
capacitor whose capacitance ranges from Cmm to Cmax.
The tuning circuit selects the frequency / =
In
Jlc
. To design this circuit for a given
frequency, take C = and calculate the required inductance L from/and
2 71
C. Now the circuit can be tuned to any frequency in the range /min = , to
r _ 27T \IL Cmax
/max •
V ^ ^min
Write a Java program to design a tuning circuit for a given frequency, using a variable
capacitor with given values for Cmm and Cmax. (A typical input is/= 16.7 MHz,
Cmin = 14 pF, and Cmax = 365 pF.) The program should read in/(in Hz), Cm \ n and
Cmax (in F), and print the required inductance value and the range of frequencies to
which the circuit can be tuned by varying the capacitance.
Science P2.33 According to the Coulomb force law, the electric force between two charged
particles of charge Qj and Q2 Coulombs, that are a distance r meters apart, is
F = — Newtons, where £ = 8.854 x 10-12 Farads/meter. Write a program
47t£r2
that calculates the force on a pair of charged particles, based on the user input of Qj
Coulombs, Q2 Coulombs, and r meters, and then computes and displays the electric
force.
Answers to Self-Check Questions 79
ANSWERS TO SELF-CHECK QUESTIONS
1 . One possible answer is
int bottlesPerCase = 8;
You may choose a different variable name or a
different initialization value, but your variable
should have type i nt.
2. There are three errors:
■ You cannot have spaces in variable names.
■ The variable type should be doubl e because
it holds a fractional value.
■ There is a semicolon missing at the end of
the statement.
3. double unitPrice = 1.95;
int quantity = 2;
4. System. out. print("Total price: ");
System. out. println(unitPrice * quantity);
5. Change the declaration of cansPerPack to
int cansPerPack = 4;
6. You need to use a */ delimiter to close a com¬
ment that begins with a /*:
double canVolume = O.S55;
/* Liters in a 12-ounce can */
7. The program would compile, and it would
display the same result. However, a person
reading the program might find it confusing
that fractional cans are being considered.
8. Its value is modified by the assignment
statement.
9. Assignment would occur when one car is
replaced by another in the parking space.
10. double interest = balance * percent / 100;
1 1 . double sideLength = Math.sqrt(area) ;
12. 4 * PI * Math.pow(radius, S) / 3
or (4.0 / 3) * PI * Math.pow(radius, 3),
but not (4 / 3) * PI * Math.pow(radius, 3)
13. 172 and 9
1 4. It is the second-to-last digit of n. For example,
if n is 1729, then n / 10 is 172, and (n / 10) % 10
is 2.
1 5. System. out. print("How old are you? ") ;
int age = in.nextlnt();
1 6. There is no prompt that alerts the program
user to enter the quantity.
1 7. The second statement calls nextlnt, not next-
Double. If the user were to enter a price such as
1.95, the program would be terminated with an
“input mismatch exception”.
1 8. There is no colon and space at the end of the
prompt. A dialog would look like this:
Please enter the number of cans6
19. The total volume is 10
There are four spaces between i s and 10. One
space originates from the format string (the
space between s and %), and three spaces are
added before 10 to achieve a field width of 5.
20. Here is a simple solution:
System. out. printf("Bottles: %8d\n", bottles);
System. out. printf("Cans: %8d\n", cans);
Note the spaces after Cans : . Alternatively,
you can use format specifiers for the strings.
You can even combine all output into a single
statement:
System . out . pri ntf ("%-9s%8d\n%-9s%8d\n" ,
"Bottles: ", bottles, "Cans:", cans);
21. int pairs = (totalWidth - tileWidth)
/ (2 * tileWidth) ;
int tiles = 1 + 2 * pairs;
double gap = (totalWidth -
tiles * tileWidth) / 2.0;
Be sure that pai rs is declared as an i nt.
22. Now there are groups of four tiles (gray/
white/ gray/black) following the initial black
tile. Therefore, the algorithm is now
number of groups = integer part of (total width - tile width) /
(4 x tile width)
number of tiles = 1 + 4 x number of groups
The formula for the gap is not changed.
23. Clearly, the answer depends only on whether
the row and column numbers are even or odd,
so let’s first take the remainder after divid¬
ing by 2. Then we can enumerate all expected
answers:
Row % l Column % 1 Color
0 0 0
0 1 1
1 0 1
1 1 0
80 Chapter 2 Fundamental Data Types
In the first three entries of the table, the color
is simply the sum of the remainders. In the
fourth entry, the sum would be 2, but we want
a zero. We can achieve that by taking another
remainder operation:
color * ((row % l) * (column % 2)1 % l
24. In nine years, the repair costs increased by
$1,400. Therefore, the increase per year is
$1,400 / 9 « $156. The repair cost in year 3
would be $100 + 2 x $156 = $412. The repair
cost in year n is $100 + n x $156. To avoid
accumulation of roundoff errors, it is actually
a good idea to use the original expression that
yielded $156, that is,
Repair cost in year n = 1 00 + n x 1 400/9
25. The pseudocode follows easily from the
equations:
bottom volume * n x X\ - x hj
top volume = jt x r/ x
middle volume = jt x (r^ ♦ rj x r^ + r /) x bj / 3
total volume = bottom volume + top volume + middle volume
Measuring a typical wine bottle yields
r\ - 3.6, r2 = 1.2, h\ - 15, /?2 = 7, ^3 = 6
(all in centimeters). Therefore,
bottom volume = 610.73
top volume = 31.67
middle volume = 135.72
total volume = 778.12
The actual volume is 750 ml, which is close
enough to our computation to give confidence
that it is correct.
26. The length is 12. The space counts as a
character.
27. str.substnng(8, 12) or str.substring(8)
28. str = str + "mi ng" ;
29. Hy
30. St ring first = in.next();
String middle = in.nextO;
String last = in.nextO;
CHAPTER
3
DECISIONS
CHAPTER COALS
To implement decisions using i f
statements
To compare integers, floating-point numbers, and strings
To write statements using the Boolean data type
To develop strategies for testing your programs
To validate user input
CHAPTER CONTENTS
3.1 THE IF STATEMENT 82
Syntax 3.1: if Statement 84
Programming Tip 3.1 : Brace Layout 86
Programming Tip 3.2: Always Use Braces 86
Common Error 3.1 : A Semicolon After the
ifCondition 86
Programming Tip 3.3: Tabs 87
Special Topic 3.1 : The Conditional Operator 87
Programming Tip 3.4: Avoid
Duplication in Branches 88
3.2 COMPARING NUMBERS
AND STRINGS 88
Syntax 3.2: Comparisons 89
Common Error 3.2: Exact Comparison of
Floating-Point Numbers 91
Common Error 3. 3: Using ==to Compare Strings 92
Special Topic 3.2: Lexicographic Ordering
ofStrings 92
HowTo3.1: Implementing an if Statement 93
Worked Example 3.1 : Extracting the Middle ©
Random Fact 3.1 : The Denver Airport Luggage
Handling System 95
3.3 MULTIPLE ALTERNATIVES 96
Special Topic 3.3: The switch Statement 99
3.4 NESTED BRANCHES 100
Programming Tip 3.5: Hand-Tracing 1 03
Common Error 3.4: The Dangling else Problem 1 04
Special Topic 3.4: Enumeration Types 105
Video Example 3.1 : Computing the Plural of an
English Word ©
3.5 PROBLEM SOLVING: FLOWCHARTS 1 05
3.6 PROBLEM SOLVING: TEST CASES 108
Programming Tip 3.6: Make a Schedule and Make
Time for Unexpected Problems 109
Special Topic 3.5: Logging 1 1 0
3.7 BOOLEAN VARIABLES
AND OPERATORS 111
Common Error 3.5: Combining Multiple
Relational Operators 1 1 3
Common Error 3.6: Confusing && and ||
Conditions 1 1 4
Special Topic 3.6: Short-Circuit Evaluation of
Boolean Operators 114
Special Topic 3.7: De Morgan's Law 1 1 5
3.8 APPLICATION: INPUT VALIDATION 116
Video Example 3.2: The Genetic Code ©
Random Fact 3.2: Artificial Intelligence 1 19
One of the essential features of computer programs is
their ability to make decisions. Like a train that changes
tracks depending on how the switches are set, a program
can take different actions depending on inputs and other
circumstances.
In this chapter, you will learn how to program simple and
complex decisions. You will apply what you learn to the
task of checking user input.
3.1 The if Statement
The if statement
allows a program to
carry out different
actions depending on
the nature of the data
to be processed.
The i f statement is used to implement a decision (see Syntax 3.1). When a condition is
fulfilled, one set of statements is executed. Otherwise, another set of statements is
executed.
Here is an example using the if statement: In
many countries, the number 13 is considered
unlucky. Rather than offending superstitious ten¬
ants, building owners sometimes skip the thir¬
teenth floor; floor 12 is immediately followed by
floor 14. Of course, floor 13 is not usually left
empty or, as some conspiracy theorists believe,
filled with secret offices and research labs. It is
simply called floor 14. The computer that controls
the building elevators needs to compensate for
this foible and adjust all floor numbers above 13.
Let’s simulate this process in Java. We will ask
the user to type in the desired floor number and
then compute the actual floor. When the input is
above 13, then we need to decrement the input to
obtain the actual floor. For example, if the user This elevator panel skips the
■i ■ * r ta j _ ■ thirteenth floor. The floor is not
provides an input ol 20, the program determines V
r, i n r ’ r . ° , actually missing — the computer
the actual floor as 19. Otherwise, we simply use that controls the elevator adjusts
the supplied floor number. the floor numbers above 1 3.
int actual Floor;
if (floor > 13)
{
actual Floor = floor - 1;
}
else
{
actual Floor = floor;
}
The flowchart in Figure 1 shows the branching behavior.
In our example, each branch of the i f statement contains a single statement. You
can include as many statements in each branch as you like. Sometimes, it happens that
82
B.l The if Statement 83
Condition
True
floor > 13?
False
actual Floor =
floor - 1
actual Floor =
floor
No el se branch
True False
rioor > Lit
actual Floor —
Figure 1 Figure 2
Flowchart for if Statement Flowchart for if Statement with No else Branch
there is nothing to do in the el se branch of the statement. In that case, you can omit it
entirely, such as in this example:
int actualFloor = floor;
if (floor > 13)
{
actual Floor — ;
} // No el se needed
See Figure 2 for the flowchart.
An i f statement is like a fork in
the road. Depending upon a
decision, different parts of the
program are executed.
84 Chapter B Decisions
Syntax 3 if Statement
Syntax if ( condition ) if ( condition ) { statements l }
f else { statements2 }
statements
}
Braces are wot required
if the brawch cowtaiws a
siwgle statement, but it's
good to always use them.
£ See page 86.
Omit the el se brawch
if there is wothiwg to do.
A condition that is true or false.
Often uses relational operators:
== !=<<=>>= (See page 89.)
r
if (floor > 13)
{
actual Floor = floor
}
else
{
actual Floor = floor;
}
Lining up braces
> is a good idea.
See page 86.
Pon't put a semicolon here!
See page 86.
If the condition is true, the statement(s)
in this branch are executed in sequence;
if the condition is false, they are skipped.
If the condition is false, the statement(s)
in this branch are executed in sequence;
if the condition is true, they are skipped.
The following program puts the i f statement to work. This program asks for the
desired floor and then prints out the actual floor.
section. 1/ElevatorSimulation. java
1 import java. util .Scanner;
2
3 /**
4 This program simulates an elevator panel that skips the 13th floor.
5 */
6 public class ElevatorSimulation
7 {
8 public static void main(String[] args)
9 {
10 Scanner in = new Scanner(System.in) ;
11 System, out. print(:iFloor: );
12 int floor = in.nextlntO;
13
14 // Adjust floor if necessary
15
16 int actualFloor;
17 if (floor > 13)
18 {
19 actualFloor = floor - 1;
20 }
21 else
22 {
B.l The if Statement 85
23 actualFloor = floor;
24 }
25
26 System. out. println ("The elevator will travel to the actual floor
27 + actual Floor) ;
28 }
29 }
Program Run
Floor: 20
The elevator will travel to the actual floor 19
1 . In some Asian countries, the number 14 is considered unlucky. Some building
owners play it safe and skip both the thirteenth and the fourteenth floor. How
would you modify the sample program to handle such a building?
2. Consider the following i f statement to compute a discounted price:
if (original Price > 100)
{
discountedPrice = originalPrice - 20;
}
else
{
discountedPrice = originalPrice - 10;
}
What is the discounted price if the original price is 95? 100? 105?
3. Compare this i f statement with the one in Self Check 2:
if (originalPrice < 100)
{
discountedPrice = originalPrice - 10;
}
else
{
discountedPrice = originalPrice - 20;
}
Do the two statements always compute the same value? If not, when do the
values differ?
4. Consider the following statements to compute a discounted price:
discountedPrice = originalPrice;
if (originalPrice > 100)
{
discountedPrice = originalPrice - 10;
}
What is the discounted price if the original price is 95? 100? 105?
5. The variables fuel Amount and fuel Capacity hold the actual amount of fuel and the
size of the fuel tank of a vehicle. If less than 1 0 percent is remaining in the tank, a
status light should show a red color; otherwise it shows a green color. Simulate
this process by printing out either "red" or "green".
Practice It Now you can try these exercises at the end of the chapter: R3.5, R3.6, P3.31.
86 Chapter B Decisions
Programming Tip B.l
Q
Programming Tip 3.2
&
Common Error 3.1
Brace Layout
The compiler doesn’t care where you place
braces. In this book, we follow the simple rule
of making { and } line up.
if (floor > 13)
{
floor--;
}
This style makes it easy to spot matching
braces. Some programmers put the opening
brace on the same line as the i f :
if (floor > 13) {
floor--;
}
This style makes it harder to match the braces, but it saves a line of code, allowing you to view
more code on the screen without scrolling. There are passionate advocates of both styles.
It is important that you pick a layout style and stick with it consistently within a given
programming project. Which style you choose may depend on your personal preference or a
coding style guide that you need to follow.
Properly lining up your code makes your pro¬
grams easier to read.
Always Use Braces
When the body of an i f statement consists of a single statement, you need not use braces. For
example, the following is legal:
if (floor > 13)
floor-- ;
However, it is a good idea to always include the braces:
if (floor > 13)
I
floor--;
}
The braces make your code easier to read. They also make it easier for you to maintain the
code because you won’t have to worry about adding braces when you add statements inside
an i f statement.
A Semicolon After the if Condition
The following code fragment has an unfortunate error:
if (floor > 13) ; // ERROR
I
floor--;
}
There should be no semicolon after the i f condition. The compiler interprets this statement as
follows: If floor is greater than 13, execute the statement that is denoted by a single semicolon,
that is, the do-nothing statement. The statement enclosed in braces is no longer a part of the i f
B.l The if Statement 87
statement. It is always executed. In other words, even if the value of fl oor is not above 13, it is
decremented.
Tabs
Block-structured code has the property that nested statements are indented by one or more
levels:
public class ElevatorSimulation
{
| public static void main(String[] args)
I I
| | int floor;
if (floor > 13)
i I I
| | | floor--;
i I I
0 12 3 Indentation level
You use
the Tab key
to move the
cursor to the next
indentation level.
How do you move the cursor from the leftmost column to the appropriate indentation level?
A perfectly reasonable strategy is to hit the space bar a sufficient number of times. With most
editors, you can use the Tab key instead. A tab moves the cursor to the next indentation level.
Some editors even have an option to fill in the tabs automatically.
While the Tab key is nice, some editors use tab characters for alignment, which is not so
nice. Tab characters can lead to problems when you send your file to another person or a
printer. There is no universal agreement on the width of a tab character, and some software
will ignore tab characters altogether. It is therefore best to save your files with spaces instead of
tabs. Most editors have a setting to automatically convert all tabs to spaces. Look at the docu¬
mentation of your development environment to find out how to activate this useful setting.
The Conditional Operator
Java has a conditional operator of the form
condition ? valuer : value2
The value of that expression is either valuer if the test passes or value2 if it fails. For example,
we can compute the actual floor number as
actualFloor = floor > 13 ? floor - 1 : floor;
which is equivalent to
if (floor > 13) { actualFloor = floor - 1; } else { actualFloor = floor; }
You can use the conditional operator anywhere that a value is expected, for example:
System. out. pri ntl n("Actual floor: " + (floor > 13 ? floor - 1 : floor));
We don’t use the conditional operator in this book, but it is a convenient construct that you
will find in many Java programs.
88 Chapter B Decisions
Avoid Duplication in Branches
Look to see whether you duplicate code in each branch. If so, move it out of the i f statement.
Here is an example of such duplication:
if (floor > 13)
{
actualFloor = floor - 1;
System. out. println("Actual floor: " + actualFloor);
}
el se
{
actualFloor = floor;
System. out. println("Actual floor: " + actualFloor);
}
The output statement is exactly the same in both branches. This is not an error— the program
will run correctly. However, you can simplify the program by moving the duplicated state¬
ment, like this:
if (floor > 13)
{
actualFloor = floor - 1;
}
el se
{
actualFloor = floor;
}
System. out. println("Actual floor: " + actualFloor);
Removing duplication is particularly important when programs are maintained for a long
time. When there are two sets of statements with the same effect, it can easily happen that a
programmer modifies one set but not the other.
3.2 Comparing Numbers and Strings
Use relational
operators
(< <= > >= == !=)
to compare numbers.
Every if statement contains a condi¬
tion. In many cases, the condition
involves comparing two values. For
example, in the previous examples we
tested floor > 13. The comparison > is
called a relational operator. Java has
six relational operators (see Table 1).
As you can see, only two Java rela¬
tional operators (> and <) look as you
would expect from the mathematical
notation. Computer keyboards do not
have keys for >, <, or but the >=, <=,
and I = operators are easy to remember
because they look similar. The == opera¬
tor is initially confusing to most new¬
comers to Java.
In Java, you use a relational operator to check
whether one value is greater than another.
3.2 Comparing Numbers and Strings 89
Table 1 Relational Operators
Java
Math Notation Description
>
> Greater than
>=
a Greater than or equal
<
< Less than
<=
s Less than or equal
==
= Equal
! =
* Not equal
In Java, = already has a meaning, namely assignment. The == operator denotes equality
testing:
floor = 13; // Assign 13 to floor
if (floor == 13) // Test whether floor equals 13
You must remember to use == inside tests and to use = outside tests.
Syntax 3 Comparisons
These quantities are compared.
/A
Check that you have the right direction:
floor > 13
> (greater) or < (less)
One of: == !=<<=>>= (See page 89.)
Check the boundary condition:
> (greater) or >= (greater or equal)?
floor == 13
^ Checks for equality.
Use ==, not =.
String input;
if (input. equals("Y"))
^ Use equals to compare strings. (See page 9 Z.)
double x; double y; final double EPSILON = IE-14;
if (Math.abs(x - y) < EPSILON)
V
Checks that these floating-point numbers are very close.
See page 9 1 .
90 Chapter B Decisions
ONLINE EXAMPLE
A program that
demonstrates
comparisons of
numbers and strings.
Do not use the = =
operator to compare
strings. Use the
equal s method
instead.
The relational operators in Table 1 have a lower precedence than the arithmetic opera¬
tors. That means, you can write arithmetic expressions on either side of the relational
operator without using parentheses. For example, in the expression
floor - 1 < IB
both sides (floor - 1 and 13) of the < operator are evaluated, and the results are com¬
pared. Appendix B shows a table of the Java operators and their precedence.
To test whether two strings are equal to each other, you must use the method called
equals:
if (stringl.equals(string2)) . . .
Do not use the == operator to compare strings. The comparison
if (stringl == string2) // Not useful
has an unrelated meaning. It tests whether the two strings are stored in the same loca¬
tion. You can have strings with identical contents stored in different locations, so this
test never makes sense in actual programming; see Common Error 3.3 on page 92.
Table 2 summarizes how to compare values in Java.
Table 2 Relational Operator Examples
Expression
Value
Comment
3 <= 4
true
3 is less than 4; <= tests for “less than or equal”.
■'d'
V
II
m
0
Error
The “less than or equal” operator is <=, not =<.
The “less than” symbol comes first.
3 > 4
false
> is the opposite of <=.
4 < 4
fal se
The left-hand side must be strictly smaller than
the right-hand side.
4 <= 4
true
Both sides are equal; <= tests for “less than or
equal”.
3 == 5 - 2
true
== tests for equality.
3 != 5 - 1
true
!= tests for inequality. It is true that 3 is not 5-1.
Q 3 = 6/2
Error
Use == to test for equality.
1.0 / 3.0 == 0.333333333
false
Although the values are very close to one
another, they are not exactly equal. See Common
Error 3 .2 on page 9 1 .
0 "10" > 5
Error
You cannot compare a string to a number.
"Tomato". substring(0, 3) .equals("Tom")
true
Always use the equal s method to check whether
two strings have the same contents.
"Tomato". substringCO, 3) == ("Tom")
fal se
Never use == to compare strings; it only checks
whether the strings are stored in the same
location. See Common Error 3.3 on page 92.
3.2 Comparing Numbers and Strings 91
6. Which of the following conditions are true, provided a is 3 and b is 4?
a. a + 1 <= b
b. a + 1 >= b
c. a + 1 != b
7. Give the opposite of the condition
floor > 13
8. What is the error in this statement?
if (scoreA = scoreB)
{
System. out. println("Tie") ;
}
9. Supply a condition in this i f statement to test whether the user entered a Y:
System. out. println("Enter Y to quit.");
String input = in.next();
if (■ ■ ■)
{
System. out . pri ntln ("Goodbye. ") ;
}
1 0. How do you test that a string str is the empty string?
Practice It Now you can try these exercises at the end of the chapter: R3.4, R3.7, P3.18.
Exact Comparison of Floating-Point Numbers
Floating-point numbers have only a limited precision, and cal¬
culations can introduce roundoff errors. You must take these
inevitable roundoffs into account when comparing floating¬
point numbers. For example, the following code multiplies the
square root of 2 by itself. Ideally, we expect to get the answer 2:
double r = Math.sqrt(2.0) ;
if (r 11 r == 2.0)
{
System. out. println("Math.sqrt(2.0) squared is 2.0");
}
el se
{
System. out. println("Math.sqrt(2.0) squared is not 2.0 but
+ r * r) ;
}
Take limited precision into
account when comparing
floating-point numbers.
This program displays
Math. sqrt(2 .0) squared is not 2.0 but 2.00000000000000044
It does not make sense in most circumstances to compare floating-point numbers exactly.
Instead, we should test whether they are close enough. That is, the magnitude of their differ¬
ence should be less than some threshold. Mathematically, we would write that x and y are close
enough if
x - y | < e
92 Chapter B Decisions
Common Error 3.3
■" f.
for a very small number, £. e is the Greek letter epsilon, a letter used to denote a very small
quantity. It is common to set £ to 10-14 when comparing doubl e numbers:
final double EPSILON = IE-14;
double r = Math.sqrt(2.0) ;
if (Math.abs(r * r - 2.0) < EPSILON)
{
System. out. println("Math.sqrt(2.0) squared is approximately 2.0");
}
Using == to Compare Strings
If you write
if (nickname == "Rob")
then the test succeeds only if the variable ni ckname refers to the exact same location as the string
literal "Rob". The test will pass if a string variable was initialized with the same string literal:
String nickname = "Rob";
if (nickname == "Rob") // Test is true
However, if the string with the letters Rob has been assembled in some other way, then the test
will fail:
String name = "Robert";
String nickname = name.substring(0, 3);
if (nickname == "Rob") // Test is false
In this case, the substring method produces a string in a different memory location. Even
though both strings have the same contents, the comparison fails.
You must remember never to use == to compare strings. Always use equal s to check whether
two strings have the same contents.
Lexicographic Ordering of Strings
If two strings are not identical to each other, you still
may want to know the relationship between them. The
compareTo method compares strings in "lexicographic”
order. This ordering is very similar to the way in which
words are sorted in a dictionary. If
stringl.compareTo(string2) < 0
then the string stringl comes before the string string2
in the dictionary. For example, this is the case if stri ngl
is "Harry", and string2 is "Hello". If
stringl. compareTo(string2) > 0
then stri ngl comes after stri ng2 in dictionary order.
Finally, if
stringl. compareTo(string2) == 0
then stri ngl and stri ng2 are equal.
To see which of two terms comes
first in the dictionary, consider the
first letter in which they differ.
3.2 Comparing Numbers and Strings 93
There are a few technical differences between the ordering in a
dictionary and the lexicographic ordering in Java. In Java:
• All uppercase letters come before the lowercase letters. For
example, "Z" comes before "a".
• The space character comes before all printable characters.
• Numbers come before letters.
• For the ordering of punctuation marks, see Appendix A.
When comparing two strings, you compare the first letters of each
word, then the second letters, and so on, until one of the strings ends
or you find the first letter pair that doesn’t match.
If one of the strings ends, the longer string is considered the
“larger” one. For example, compare "car" with "cart". The first
three letters match, and we reach the end of the first string. There¬
fore "car" comes before "cart" in lexicographic ordering.
When you reach a mismatch, the string containing the “larger”
character is considered “larger”. For example, let’s compare "cat"
with "cart". The first two letters match. Because t comes after r, the
string "cat" comes after "cart" in the lexicographic ordering.
The compareTo
method compares
strings in
lexicographic order.
c a
r
cart
c a
t
Letters r comes
match before t
Lexicographic
Ordering
HOW TO 3.1
Step 2
Implementing an if Statement
This How To walks you through the process of implementing an i f statement. We will illus¬
trate the steps with the following example problem:
The university bookstore has a Kilobyte Day sale every October 24, giving an 8 percent
discount on all computer accessory purchases if the price is less than $128, and a 16 percent
discount if the price is at least $128. Write a program that asks the cashier for the original price
and then prints the discounted price.
Decide upon the branching condition.
In our sample problem, the obvious choice for the
condition is:
original price < \W.
That is just fine, and we will use that condition in
our solution.
But you could equally well come up with a
correct solution if you choose the opposite condi¬
tion: Is the original price at least $128? You might
choose this condition if you put yourself into the
position of a shopper who wants to know when
the bigger discount applies.
Give pseudocode for the work that needs to be
done when the condition is true.
Sales discounts are often higher for
expensive products. Use the if statement
to implement such a decision.
In this step, you list the action or actions that are taken in the “positive” branch. The details
depend on your problem. You may want to print a message, compute values, or even exit the
program.
94 Chapter B Decisions
Step 3
Step 4
Step 5
Step 6
Step 7
In our example, we need to apply an 8 percent discount:
discounted price * 0.92 x original price
Give pseudocode for the work (if any) that needs to be done when the condition is not true.
What do you want to do in the case that the condition of Step 1 is not satisfied? Sometimes,
you want to do nothing at all. In that case, use an i f statement without an el se branch.
In our example, the condition tested whether the price was less than $128. If that condition
is not true, the price is at least $128, so the higher discount of 16 percent applies to the sale:
discounted price * 0.S4 x original price
Double-check relational operators.
First, be sure that the test goes in the right direction. It is a common error to confuse > and <.
Next, consider whether you should use the < operator or its close cousin, the <= operator.
What should happen if the original price is exactly $128? Reading the problem carefully, we
find that the lower discount applies if the original price is less than $128, and the higher dis¬
count applies when it is at least $128. A price of $128 should therefore not fulfill our condition,
and we must use <, not <=.
Remove duplication.
Check which actions are common to both branches, and move them outside. (See Program¬
ming Tip 3.4 on page 88.)
In our example, we have two statements of the form
discounted price * _ x original price
They only differ in the discount rate. It is best to just set the rate in the branches, and to do the
computation afterwards:
If original price <128
discount rate * 0.92
Else
discount rate * 0.84
discounted price * discount rate x original price
Test both branches.
Formulate two test cases, one that fulfills the condition of the i f statement, and one that does
not. Ask yourself what should happen in each case. Then follow the pseudocode and act each
of them out.
In our example, let us consider two scenarios for the original price: $100 and $200. We
expect that the first price is discounted by $8, the second by $32.
When the original price is 100, then the condition 100 < 128 is true, and we get
discount rate * 0.92
discounted price * 0.92 x 1 00 = 92
When the original price is 200, then the condition 200 < 128 is false, and
discount rate * 0.84
discounted price * 0.84 x 200 = 168
In both cases, we get the expected answer.
Assemble the i f statement in Java.
Type the skeleton
if O
1
3.2 Comparing Numbers and Strings 95
ONLINE EXAMPLE
© The complete
program for
calculating a
discounted price.
}
el se
{
}
and fill it in, as shown in Syntax 3.1 on page 84. Omit the el se branch if it is not needed.
In our example, the completed statement is
if (original Pri ce < 128)
{
discountRate = 0.92;
}
el se
{
discountRate = 0.84;
}
di scountedPri ce = discountRate * original Price;
WORKED EXAMPLE B.l
Extracting the Middle
This Worked Example shows how to extract the middle character from a
string, or the two middle characters if the length of the string is even.
t e
0 12 3 4
Random Fact 3.1 The Denver Airport Luggage Handling System
j Making decisions is
* ™ an essential part of
any computer program. Nowhere is
this more obvious than in a computer
system that helps sort luggage at an
airport. After scanning the luggage
identification codes, the system sorts
the items and routes them to differ¬
ent conveyor belts. Human operators
then place the items onto trucks. When
the city of Denver built a huge airport
to replace an outdated and congested
facility, the luggage system contractor
went a step further. The new system
was designed to replace the human
operators with robotic carts. Unfortu¬
nately, the system plainly did not
work. It was plagued by mechanical
problems, such as luggage falling onto
the tracks and jamming carts. Equally
frustrating were the software glitches.
Carts would uselessly accumulate at
some locations when they were needed
elsewhere.
The airport had been scheduled
to open in 1993, but without a func¬
tioning luggage system, the opening
was delayed for over a year while the
contractor tried to fix the problems.
The contractor never succeeded,
and ultimately a manual system was
installed. The delay cost the city and
airlines close to a billion dollars, and
the contractor, once the leading lug¬
gage systems vendor in the United
States, went bankrupt.
Clearly, it is very risky to build a
large system based on a technology
that has never been tried on a smaller
scale. As robots and the software that
controls them get better over time,
they will take on a larger share of lug¬
gage handling in the future. But it is
likely that this will happen in an incre¬
mental fashion.
The Denver airport originally had a
fully automatic system for moving lug¬
gage, replacing human operators with
robotic carts. Unfortunately, the sys¬
tem never worked and was dismantled
before the airport was opened.
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
96 Chapter B Decisions
3.3 Multiple Alternatives
Multiple if
statements can be
combined to evaluate
complex decisions.
In Section 3.1, you saw how to program a two-way branch with an if statement. In
many situations, there are more than two cases. In this section, you will see how to
implement a decision with multiple alternatives.
For example, consider a program that displays the effect of an earthquake, as mea¬
sured by the Richter scale (see Table 3).
The 1 989 Loma Prieta
earthquake that
damaged the Bay
Bridge in San Francisco
and destroyed many
buildings measured 7. 1
on the Richter scale.
Table 3 Richter Scale
Value
Effect
8
Most structures fall
7
Many buildings destroyed
6
Many buildings considerably
damaged, some collapse
4.5
Damage to poorly constructed
buildings
Multiple Alternatives
The Richter scale is a measurement of the strength of an earthquake. Every step in
the scale, for example from 6.0 to 7.0, signifies a tenfold increase in the strength of the
quake.
In this case, there are five branches: one each for the four descriptions of damage,
and one for no destruction. Figure 3 shows the flowchart for this multiple-branch
statement.
You use multiple i f statements to implement multiple alternatives, like this:
if (richter >= 8.0)
{
System. out. printin ("Most structures fail");
}
else if (richter >= 7.0)
{
System. out. println("Many buildings destroyed");
}
else if (richter >= 6.0)
{
System. out. println("Many buildings considerably damaged, some collapse");
}
else if (richter >= 4.5)
{
System. out. println("Damage to poorly constructed buildings");
}
else
{
System. out. println("No destruction of buildings");
}
As soon as one of the four tests succeeds, the effect is displayed, and no further tests
are attempted. If none of the four cases applies, the final else clause applies, and a
default message is printed.
B.B Multiple Alternatives 97
Figure 3
Multiple Alternatives
ri chter > 8.0?
True
False
Most
structures
fall
True Many
richter >7.0? buildings
destroyed
False
^ ^ Many buildings
ri chter >6.0? *UL considerably
damaged,
some collapse
False
True Damage to
ri chter >4.5? poorly constructed
buildings
False
No destruction
of buildings
Here you must sort the conditions and test against the largest cutoff first.
Suppose we reverse the order of tests:
if (ri chter >= 4.5) // Tests in wrong order
{
System. out. println ("Damage to poorly constructed buildings");
}
else if (richter >= 6.0)
{
System. out. println("Many buildings considerably damaged, some collapse");
}
else if (richter >= 7.0)
{
System. out. println("Many buildings destroyed");
98 Chapter B Decisions
When using multiple
if statements, test
general conditions
after more specific
conditions.
ONLINE EXAMPLE
The complete
program for printing
earthquake
descriptions.
}
else if (richter >= 8.0)
{
System. out. println ("Most structures fall");
}
This does not work. Suppose the value of richter is 7.1. That value is at least 4.5,
matching the first case. The other tests will never be attempted.
The remedy is to test the more specific conditions first. Here, the condition
richter >= 8.0 is more specific than the condition richter >= 7.0, and the condition
ri chter >= 4 . 5 is more general (that is, fulfilled by more values) than either of the first
two.
In this example, it is also important that we use an if/else if/else sequence, not
just multiple independent i f statements. Consider this sequence of independent tests.
if
{
}
if
{
}
if
{
}
if
{
}
(richter >= 8.0) // Didn’t use else
System. out. println("Most structures fall");
(richter >= 7.0)
System. out. println("Many buildings destroyed");
(richter >= 6.0)
System. out. println("Many buildings considerably damaged, some collapse");
(richter >= 4.5)
System. out. println("Damage to poorly constructed buildings");
Now the alternatives are no longer exclusive. If richter is 7.1, then the last three tests
all match, and three messages are printed.
11. In a game program, the scores of players A and B are stored in variables scoreA
and scoreB. Assuming that the player with the larger score wins, write an i f/
else if/el se sequence that prints out "A won", "B won", or "Came tied".
1 2. Write a conditional statement with three branches that sets s to 1 if x is positive,
to -1 if x is negative, and to 0 if x is zero.
1 3. How could you achieve the task of Self Check 12 with only two branches?
1 4. Beginners sometimes write statements such as the following:
if (price > 100)
{
discountedPrice = price - 20;
}
else if (price <= 100)
{
discountedPrice = price - 10;
}
Explain how this code can be improved.
1 5. Suppose the user enters -1 into the earthquake program. What is printed?
B.B Multiple Alternatives 99
1 6. Suppose we want to have the earthquake program check whether the user en¬
tered a negative number. What branch would you add to the i f statement, and
where?
Practice It Now you can try these exercises at the end of the chapter: R3.22, P3.9, P3.34.
The switch Statement
An if/else if/else sequence that compares a value against several alternatives can be imple¬
mented as a swi tch statement. For example,
int digit = .
switch (digit)
{
}
case 1
digitName =
case 2
digitName =
case 3
digitName =
case 4
digitName =
case 5
digitName =
case 6
digitName =
case 7
digitName =
case 8
digitName =
case 9
digitName =
default: digitName =
one"; break;
two"; break;
three"; break;
four"; break;
five"; break;
six"; break;
seven"; break;
eight"; break;
nine"; break;
break;
The switch statement lets you choose
from a fixed set of alternatives.
This is a shortcut for
i nt di gi t = . . . ;
if (digit == 1) { digitName = "one"; }
else if (digit == 2) { digitName = "two"; }
else if (digit == 3) { digitName = "three"; }
else if (digit == 4) { digitName = "four"; }
else if (digit == 5) { digitName = "five"; }
else if (digit == 6) { digitName = "six"; }
else if (digit == 7) { digitName = "seven"; }
else if (digit == 8) { digitName = "eight"; }
else if (digit == 9) { digitName = "nine"; }
else { digitName = }
It isn’t much of a shortcut, but it has one advantage — it is obvious that all branches test the
same value, namely digit.
The switch statement can be applied only in narrow circumstances. The values in the case
clauses must be constants. They can be integers or characters. As of Java 7, strings are permit¬
ted as well. You cannot use a swi tch statement to branch on floating-point values.
Every branch of the switch should be terminated by a break instruction. If the break is miss¬
ing, execution falls through to the next branch, and so on, until a break or the end of the switch
is reached. In practice, this fall-through behavior is rarely useful, but it is a common cause
of errors. If you accidentally forget a break statement, your program compiles but executes
unwanted code. Many programmers consider the swi tch statement somewhat dangerous and
prefer the i f statement.
We leave it to you to use the swi tch statement for your own code or not. At any rate, you
need to have a reading knowledge of swi tch in case you find it in other programmers’ code.
100 Chapter 3 Decisions
3.4 Nested Branches
When a decision
statement is
contained inside the
branch of another
decision statement,
the statements
are nested.
It is often necessary to include an i f statement inside another. Such an arrangement is
called a nested set of statements.
Here is a typical example: In the United States, different tax rates are used depend¬
ing on the taxpayer’s marital status. There are different tax schedules for single and
for married taxpayers. Married taxpayers add their income together and pay taxes on
the total. Table 4 gives the tax rate computations, using a simplification of the sched¬
ules in effect for the 2008 tax year. A different tax rate applies to each “bracket”. In
this schedule, the income in the first bracket is taxed at 10 percent, and the income in
the second bracket is taxed at 25 percent. The income limits for each bracket depend
on the marital status.
Table 4 Federal Tax Rate Schedule
If your status is Single and
if the taxable income is
the tax is
of the amount over
at most $32,000
10%
$0
over $32,000
$3,200 + 25%
$32,000
If your status is Married and
if the taxable income is
the tax is
of the amount over
at most $64,000
10%
$0
over $64,000
$6,400 + 25%
$64,000
Nested decisions
are required for
problems that
have two levels of
decision making.
Nested Branches
Now compute the taxes due, given a marital status and an income figure. The key
point is that there are two levels of decision making. First, you must branch on the
marital status. Then, for each marital status, you must have another branch on income
level.
The two-level decision process is reflected in two levels of i f statements in the pro¬
gram at the end of this section. (See Figure 4 for a flowchart.) In theory, nesting can go
deeper than two levels. A three-level decision process (first by state, then by marital
status, then by income level) requires three nesting levels.
Computing income taxes requires
multiple levels of decisions.
B.4 Nested Branches
101
Single?
True income True
< 32,000
False
False
10%
bracket
25%
bracket
income True 10%
< 64,000 bracket
False
25%
bracket
Figure 4 Income Tax Computation
section_4/TaxCalculator.java
1 import java. util .Scanner;
2
3 /**
4 This program computes income taxes, using a simplified tax schedule.
5 */
6 public class TaxCalculator
7 {
8 public static void main(String[] args)
9 {
10 final double RATE1 = 0.10;
11 final double RATE2 =0.2 ;
12 final double RATE1_SINCLEJ_IMIT = 32000;
13 final double RATE1_MARRIED_LIMIT = 64000;
14
1 5 double taxi = 0;
16 double tax2 = 0;
17
18 // Read income and marital status
19
20 Scanner in = new Scanner(System.in) ;
21 System. out. print( ’lease enter your income: );
22 double income = in.nextDouble();
23
24 System. out. print("Please enter s for single, m for married: ") ;
25 String maritalStatus = in.nextO;
26
27 // Compute taxes due
28
102 Chapter 3 Decisions
29 if (marital Status. equal s( s"))
30 {
31 if (income <= RATE1_SINGLE_LIMIT)
32 {
33 taxi = RATE1 * income;
34 }
35 else
36 {
taxi = RAT El * RATE1_SINGLE_LIMIT ;
38 tax2 = RATE 2 * (income - RATE1_SINCLE_LIMIT) ;
39 }
40 }
41 else
42 {
43 if (income <= RATE1_MARRIED_LIMIT)
44 {
45 taxi = RATE1 * income;
46 }
47 else
48 {
49 taxi = RAT El * RATE1_MARRIED_LIMIT ;
tax2 = RATE 2 * (income - RATE1_MARRIED_LIMIT) ;
51 }
52 }
53
54 double totalTax = taxi + tax2;
55
56 System. out. println("The tax is $" + totalTax);
57 }
58 }
Program Run
Please enter your income: 80000
Please enter s for single, m for married: m
The tax is $10400
1 7. What is the amount of tax that a single taxpayer pays on an income of $32,000?
1 8. Would that amount change if the first nested i f statement changed from
if (income <= RATE1_SINGLEJ_IMIT)
to
if (income < RATE1_SINGLE_LIMIT)
1 9. Suppose Harry and Sally each make $40,000 per year. Would they save taxes if
they married?
20. How would you modify the TaxCalculator . java program in order to check that
the user entered a correct value for the marital status (i.e., s or m) ?
2 1 . Some people object to higher tax rates for higher incomes, claiming that you
might end up with less money after taxes when you get a raise for working hard.
What is the flaw in this argument?
Practice It
Now you can try these exercises at the end of the chapter: R3.9, R3.21, P3.18, P3.21.
B.4 Nested Branches 103
Hand-Tracing
A very useful technique for understanding whether a pro¬
gram works correctly is called hand-tracing. You simulate
the program’s activity on a sheet of paper. You can use this
method with pseudocode or Java code.
Get an index card, a cocktail napkin, or whatever sheet
of paper is within reach. Make a column for each variable.
Have the program code ready. Use a marker, such as a
paper clip, to mark the current statement. In your mind,
execute statements one at a time. Every time the value of a
variable changes, cross out the old value and write the new
value below the old one.
For example, let’s trace the tax program with the data
from the program run onpage 1 02. In lines 1 5 and 1 6, taxi and
tax2 are initialized to 0.
Hand-tracing helps you
understand whether a
program works correctly.
8 public static void main(String[] args)
9 {
10
final double RATE1 = 0.10;
1 1
final double RATE2 = 0.25;
12
final double RATE1_SINGLE_LIMIT =
32000;
13
14
final double RATE1_MARRIED_LIMIT
= 64000;
15
double taxi = 0;
16
17
double tax2 = 0;
In lines 22 and 25, i ncome and mari tal Status are
initialized by input statements.
20 Scanner in = new Scanner(System.in) ;
21 System. out. print ("PI ease enter your income: ") ;
22 double income = in.nextDoubleO ;
23
24
25
\ taxi
taxZ
income
marital
status
/ °
0
\
r
L
_
\ taxi
taxZ
income
marital
status
/ °
0
80000
m 1
r
L
System. out. print ("PI ease enter s for single, m for married: ") ;
String mari tal Status = in.nextQ;
Because mari tal Status is not "s", we move to the else branch of the outer if statement
(line 41).
29 if (mari tal Status, equal s("s"))
30 {
31 if (income <= RATE1_SINGLE_LIMIT)
32 {
33 taxi = RATE1 * income;
34 }
35 else
36 {
37 taxi = RATE1 * RATE1_SINGLE_LIMIT ;
38 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT) ;
39 }
40 }
41 else
42 {
Because i ncome is not <= 64000, we move to the el se branch of the inner i f statement (line 47).
43 if (income <= RATE1_MARRIED_LIMIT)
44 {
45 taxi = RATE1 * income;
46 }
47 else
48 {
49 taxi = RATE1 * RATE1_MARRIED_LIMIT ;
50 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT) ;
51
}
104 Chapter 3 Decisions
The values of taxi and tax2 are updated.
48
49
50
51
52
53
Their sum total Tax is computed and printed.
Then the program ends.
54 double totalTax = taxi + tax2;
55
56 System. out. println("The tax is $" + totalTax);
57 }
Because the program trace shows the expected
output ($10,400), it successfully demonstrated
that this test case works correctly.
\ taxi
ta xl
income
marital
status
/ ^
$
soooo
m 1
| 6400
4000
_
\ taxi
taxZ
income
marital
status
total
tax
/ ^
X
soooo
m
\
| 6400
4000
10400
L
{
taxi = RATE1 4 RATE1_MARRIED_LIMIT ;
tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT) ;
}
}
Common Error 3.4
- f.
The Dangling else Problem
When an i f statement is nested inside another i f statement, the following error may occur.
double shippi ngCharge = 5.00; // $5 inside continental U.S.
if (country. equal s("USA"))
if (state. equal s("HI"))
shi ppi ngCharge = 10.00; // Hawaii is more expensive
else // Pitfall!
shi ppi ngCharge = 20.00; // As are foreign shipments
The indentation level seems to suggest that the else is grouped with the test country.
equals("USA"). Unfortunately, that is not the case. The compiler ignores all indentation and
matches the else with the preceding i f . That is, the code is actually
double shippi ngCharge = 5.00; // $5 inside continental U.S.
if (country. equal s("USA"))
if (state. equal s("HI"))
shippi ngCharge = 10.00; // Hawaii is more expensive
else // Pitfall!
shi ppi ngCharge = 20.00; // As are foreign shipments
That isn’t what you want. You want to group the else with the first i f .
The ambiguous else is called a dangling else. You can avoid this pitfall if you always use
braces, as recommended in Programming Tip 3.2 on page 86:
double shippi ngCharge = 5.00; // $5 inside continental U.S.
if (country. equal s("USA"))
{
if (state. equal s("HI"))
{
shippi ngCharge = 10.00; // Hawaii is more expensive
}
}
el se
{
shi ppi ngCharge = 20.00; // As are foreign shipments
}
B.5 Problem Solving: Flowcharts 105
Enumeration Types
In many programs, you use variables that can hold one of a finite number of values. For exam¬
ple, in the tax return class, the marital Status variable holds one of the values "s" or "m". If, due
to some programming error, the marital Status variable is set to another value (such as "d" or
"w"), then the programming logic may produce invalid results.
In a simple program, this is not really a problem. But as programs grow over time, and more
cases are added (such as the “married filing separately” status), errors can slip in. Java version
5.0 introduces a remedy: enumeration types. An enumeration type has a finite set of values,
for example
public enum FilingStatus { SINGLE, MARRIED, MARRIED_FILING_SEPARATELY }
You can have any number of values, but you must include them all in the enum declaration.
You can declare variables of the enumeration type:
FilingStatus status = FilingStatus. SINGLE;
If you try to assign a value that isn’t a Fi 1 i ngStatus, such as 2 or "S", then the compiler reports
an error.
Use the == operator to compare enumeration values, for example:
if (status == Fi 1 i ngStatus . SINGLE) . . .
Place the enum declaration inside the class that implements your program, such as
public class TaxReturn
{
public enum FilingStatus { SINGLE, MARRIED, MARRIED_FILING_SEPARATELY }
public static void main(String[] args)
{
}
}
VIDEO EXAMPLE B.l
Computing the Plural of an English Word
fWILEYb
'PLUS
The plural of apple is apples, but the plural of cherry is cherries. In
this Video Example, we develop an algorithm for computing the
plural of an English word.
3.5 Problem Solving: Flowcharts
Flow charts are made
up of elements for
tasks, input/output,
and decisions.
You have seen examples of flowcharts earlier in this chapter. A flowchart shows the
structure of decisions and tasks that are required to solve a problem. When you have
to solve a complex problem, it is a good idea to draw a flowchart to visualize the flow
of control.
The basic flowchart elements are shown in Figure 5.
© Available online in WileyPLUS and at www.wiley.com/college/horstmann.
106 Chapter 3 Decisions
Figure 5
Flowchart Elements
False
Simple task
Input/ output
Condition
True
Each branch of a
decision can contain
tasks and further
decisions.
Never point an
arrow inside
another branch.
The basic idea is simple enough. Link tasks and input/ output boxes in the sequence in
which they should be executed. Whenever you need to make a decision, draw a dia¬
mond with two outcomes (see Figure 6).
Each branch can contain a sequence of tasks and even additional decisions. If there
are multiple choices for a value, lay them out as in Figure 7.
There is one issue that you need to be aware of when drawing flowcharts. Uncon¬
strained branching and merging can lead to “spaghetti code”, a messy network of
possible pathways through a program.
There is a simple rule for avoiding spaghetti code: Never point an arrow inside
another branch.
To understand the rule, consider this example: Shipping costs are $5 inside the
United States, except that to Hawaii and Alaska they are $10. International shipping
costs are also $10.
Condition
True
False
False branch
True branch
Choice 1
False
True
“Choice 1
branch
Choice 2
False
True
“Choice 2”
branch
Choice 3
False
True
“Choice 3”
branch
“Other”
branch
Figure 6 Flowchart with Two Outcomes
Figure 7 Flowchart with Multiple Choices
B.5 Problem Solving: Flowcharts
107
You might start out with a flowchart like the following:
Inside US?
True
False
Shipping
cost = $10
Continental US? TrUe ShiPP“f
cost = q>5
False
Now you may be tempted to reuse the “shipping cost = $10” task:
Inside US?
True
False
< -
Shipping
cost = $10
Continental US? ^ ShlPP“f
cost = q>5
False
Don’t do that! The red arrow points inside a different branch. Instead, add another
task that sets the shipping cost to $10, like this:
Inside US?
True
False
Shipping
cost = $10
Continental US?
True
False
Shipping
Shipping
cost = $10
cost = $5
108 Chapter B Decisions
ONLINE EXAMPLE
A program to
compute shipping
costs.
Not only do you avoid spaghetti code, but it is also a
better design. In the future it may well happen that the
cost for international shipments is different from that
to Alaska and Hawaii.
Flowcharts can be very useful for getting an intui¬
tive understanding of the flow of an algorithm. How¬
ever, they get large rather quickly when you add more
details. At that point, it makes sense to switch from
flowcharts to pseudocode.
Spaghetti code has so many
pathways that it becomes
impossible to understand.
Practice It
Draw a flowchart for a program that reads a
is less than zero.
value temp and prints “Frozen” if it
What is wrong with the flowchart at right?
How do you fix the flowchart of
Self Check 23 ?
True
Input <0?
Draw a flowchart for a program that reads a
value x. If it is less than zero, print “Error”.
Otherwise, print its square root.
False
Draw a flowchart for a program that reads a
value temp. If it is less than zero, print “Ice”.
True
Input >100?
If it is greater than 100, print “Steam”. Oth¬
erwise, print “Liquid”.
False
Status = “OK” Status = “Error”
Now you can try these exercises at the end of the
chapter: R3.12, R3.13, R3.14.
3.6 Problem Solving: Test Cases
Each branch of your
program should
be covered by a
test case.
Consider how to test the tax computation program from Section 3.4. Of course,
you cannot try out all possible inputs of marital status and income level. Even if you
could, there would be no point in trying them all. If the program correctly computes
one or two tax amounts in a given bracket, then we have a good reason to believe that
all amounts will be correct.
You want to aim for complete coverage of all decision points. Here is a plan for
obtaining a comprehensive set of test cases:
• There are two possibilities for the marital status and two tax brackets for each
status, yielding four test cases.
• Test a handful of boundary conditions, such as an income that is at the boundary
between two brackets, and a zero income.
• If you are responsible for error checking (which is discussed in Section 3.8), also
test an invalid input, such as a negative income.
3.6 Problem Solving: Test Cases
109
Make a list of the test cases and the expected outputs:
Test Case
Expected Output
Comment
30,000 s
3,000
1 0£ bracket
72,000 s
13,200
3,200 + 25^ of 40,000
50,000 m
5,000
1 0?T bracket
104,000 m
16,400
6,400 + m of 40,000
32,000 s
3,200
boundary case
0
0
boundary case
It is a good idea to
design test cases
before implementing
a program.
When you develop a set of test cases, it is helpful to have a flowchart of your program
(see Section 3.5). Check off each branch that has a test case. Include test cases for the
boundary cases of each decision. For example, if a decision checks whether an input is
less than 100, test with an input of 100.
It is always a good idea to design test cases before starting to code. Working
through the test cases gives you a better understanding of the algorithm that you are
about to implement.
2 7. Using Figure 1 on page 83 as a guide, follow the process described in Section 3 .6 to
design a set of test cases for the ElevatorSimulation. java program in Section 3.1.
28. What is a boundary test case for the algorithm in HowTo 3.1 on page 93? What is
the expected output?
29. Using Figure 3 on page 97 as a guide, follow the process described in Section 3.6 to
design a set of test cases for the EarthquakeStrength. java program in Section 3.3.
30. Suppose you are designing a part of a program for a medical ro¬
bot that has a sensor returning an x- and y-location (measured in
cm). You need to check whether the sensor location is inside the
circle, outside the circle, or on the boundary (specifically, hav¬
ing a distance of less than 1 mm from the boundary). Assume the
circle has center (0, 0) and a radius of 2 cm. Give a set of test cases.
Practice It Now you can try these exercises at the end of the chapter: R3.15, R3.16.
Make a Schedule and Make Time for Unexpected Problems
Commercial software is notorious for being delivered later than promised. For example,
Microsoft originally promised that its Windows Vista operating system would be available late
in 2003, then in 2005, then in March 2006; it finally was released in January 2007. Some of the
early promises might not have been realistic. It was in Microsoft’s interest to let prospective
customers expect the imminent availability of the product. Had customers known the actual
delivery date, they might have switched to a different product in the meantime. Undeniably,
though, Microsoft had not anticipated the full complexity of the tasks it had set itself to solve.
Microsoft can delay the delivery of its product, but it is likely that you cannot. As a student
or a programmer, you are expected to manage your time wisely and to finish your assignments
on time. You can probably do simple programming exercises the night before the due date,
but an assignment that looks twice as hard may well take four times as long, because more
things can go wrong. You should therefore make a schedule whenever you start a program¬
ming project.
110 Chapter 3 Decisions
First, estimate realistically how much time it
will take you to:
• Design the program logic.
• Develop test cases.
• Type the program in and fix syntax errors.
• Test and debug the program.
For example, for the income tax program I might
estimate an hour for the design; 30 minutes for
developing test cases; an hour for data entry and
fixing syntax errors; and an hour for testing and
debugging. That is a total of 3.5 hours. If I work
two hours a day on this project, it will take me
almost two days.
Then think of things that can go wrong. Your computer might break down. You might be
stumped by a problem with the computer system. (That is a particularly important concern
for beginners. It is very common to lose a day over a trivial problem just because it takes time
to track down a person who knows the magic command to overcome it.) As a rule of thumb,
double the time of your estimate. That is, you should start four days, not two days, before the
due date. If nothing went wrong, great; you have the program done two days early. When the
inevitable problem occurs, you have a cushion of time that protects you from embarrassment
and failure.
Make a schedule for your programming
work and build in time for problems.
Logging
Sometimes you run a program and you are not sure where it spends its time. To get a printout
of the program flow, you can insert trace messages into the program, such as this one:
if (status == SINGLE)
{
System. out. println("status is SINGLE");
}
However, there is a problem with using System. out. print! n for trace messages. When you are
done testing the program, you need to remove all print statements that produce trace mes¬
sages. If you find another error, however, you need to stick the print statements back in.
To overcome this problem, you should use the Logger class, which allows you to turn off the
trace messages without removing them from the program.
Instead of printing directly to System. out, use the global logger object that is returned
by the call Logger. getGlobal (). (Prior to Java 7, you obtained the global logger as
Logger . get Logger ("global ").) Then call the i nfo method:
Logger. getGl obal () ,info("status is SINGLE");
By default, the message is printed. But if you call
Logger. getGl obal () .setLevel (Level .OFF) ;
at the beginning of the mai n method of your program, all log message printing is suppressed.
Set the level to Level .INFO to turn logging of info messages on again. Thus, you can turn off
the log messages when your program works fine, and you can turn them back on if you find
another error. In other words, using Logger. getGlobal () .info is just like System. out. println,
except that you can easily activate and deactivate the logging.
The Logger class has many other options for industrial-strength logging. Check out the API
documentation if you want to have more control over logging.
Logging messages can be
deactivated when testing
is complete.
3.7 Boolean Variables and Operators 111
3.7 Boolean Variables and Operators
The Boolean type
boolean has two
values, false
and true.
A Boolean variable
is also called a flag
because it can be
either up (true) or
down (false).
Java has two Boolean
operators that
combine conditions:
&& (and) and | | (or).
Sometimes, you need to evaluate a logical condition in one part of a program and use
it elsewhere. To store a condition that can be true or false, you use a Boolean variable.
Boolean variables are named after the mathematician George Boole (1815-1864), a
pioneer in the study of logic.
In Java, the boolean data type has exactly two values, denoted false and true. These
values are not strings or integers; they are special values, just for Boolean variables.
Here is a declaration of a Boolean variable:
boolean failed = true;
You can use the value later in your program to make a decision:
if (failed) // Only executed if failed has been set to true
{
}
When you make complex decisions, you often need to combine Boolean values. An
operator that combines Boolean conditions is called a Boolean operator. In Java, the
&& operator (called and) yields true only when both conditions are true. The 1 1 opera¬
tor (called or) yields the result true if at least one of the conditions is true.
Suppose you write a program that processes temperature values, and you want
to test whether a given temperature corresponds to liquid water. (At sea level, water
freezes at 0 degrees Celsius and boils at 100 degrees.) Water is liquid if the tempera¬
ture is greater than zero and less than 100:
if (temp > 0 && temp < 100) { System. out. printlnCLiquid"); }
The condition of the test has two parts, joined by the && operator. Each part is a Bool¬
ean value that can be true or false. The combined expression is true if both individual
expressions are true. If either one of the expressions is false, then the result is also false
(see Figure 8).
The Boolean operators && and 1 1 have a lower precedence than the relational opera¬
tors. For that reason, you can write relational expressions on either side of the Bool¬
ean operators without using parentheses. For example, in the expression
temp > 0 && temp < 100
the expressions temp > 0 and temp < 100 are evaluated first. Then the && operator com¬
bines the results. Appendix B shows a table of the Java operators and their
precedence.
A
B
A && B
A
B
A|| B
A
! A
true
true
true
true
true
true
true
false
true
fal se
fal se
true
fal se
true
fal se
true
fal se
true
fal se
false
true
true
fal se
fal se
fal se
false
fal se
fal se
Figure 8 Boolean Truth Tables
Chapter 3 Decisions
112
ONLINE EXAMPLE
A program
comparing numbers
using Boolean
expressions.
To invert a condition,
use the ! (mot)
operator.
Conversely, let’s test whether water is not liquid at a given temperature. That is the
case when the temperature is at most 0 or at least 100. Use the 1 1 (or) operator to com¬
bine the expressions:
if (temp <= 0 | | temp >= 100) { System. out. printin("Not liquid"); }
Figure 9 shows flowcharts for these examples.
Sometimes you need to invert a condition with the not Boolean operator. The
! operator takes a single condition and evaluates to true if that condition is false and to
fal se if the condition is true. In this example, output occurs if the value of the Boolean
variable frozen is false:
if (ifrozen) { System. out. println("Not frozen"); }
Table 5 illustrates additional examples of evaluating Boolean operators.
and
or
Temperature
>0?
False
Temperature
=s0?
False
Temperature
> 100?
False
Both conditions
must be true
True
Temperature
< 100?
False
True
True
At least
one condition
must be true
True
Water is
Water is
liquid
not liquid
Figure 9 Flowcharts for and and or Combinations
3.7 Boolean Variables and Operators 113
Table 5 Boolean Operator Examples
Expression
Value
Comment
0 < 200 && 200 < 100
fal se
Only the first condition is true.
0 < 200 || 200 < 100
true
The first condition is true.
0 < 200 || 100 < 200
true
The 1 1 is not a test for “either-or”. If both
conditions are true, the result is true.
0 < x && x < 100 || x == -1
(0 < x && x < 100)
II x - -1
The && operator has a higher precedence than the
1 1 operator (see Appendix B).
Q 0 < x < 100
Error
Error: This expression does not test whether x is
between 0 and 100. The expression 0 < x is a
Boolean value. You cannot compare a Boolean
value with the integer 100.
x && y > 0
Error
Error: This expression does not test whether x and
y are positive. The left-hand side of && is an integer,
x, and the right-hand side, y > 0, is a Boolean value.
You cannot use && with an integer argument.
! (0 < 200)
fal se
0 < 200 is true, therefore its negation is false.
frozen == true
frozen
There is no need to compare a Boolean variable
with true.
frozen == false
[frozen
It is clearer to use ! than to compare with fal se.
3 1 . Suppose x and y are two integers. How do you test whether both of them are
zero?
32. How do you test whether at least one of them is zero?
33. How do you test whether exactly one of them is zero ?
34. What is the value of ! ! frozen?
35. What is the advantage of using the type bool ean rather than strings "fal se"/"true"
or integers 0/1?
Practice It Now you can try these exercises at the end of the chapter: R3.29, P3.25, P3.27.
Combining Multiple Relational Operators
Consider the expression
if (0 <= temp <= 100) // Error
This looks just like the mathematical test 0 s temp s 100. But in Java, it is a compile-time error.
Let us dissect the condition. The first half, 0 <= temp, is a test with an outcome true or fal se.
The outcome of that test (true or false) is then compared against 100. This seems to make no
Chapter 3 Decisions
1 14
sense. Is true larger than 100 or not? Can one compare truth values and numbers? In Java, you
cannot. The Java compiler rejects this statement.
Instead, use && to combine two separate tests:
if (0 <= temp && temp <= 100) . . .
Another common error, along the same lines, is to write
if (input == 1 | | 2) . . . // Error
to test whether input is 1 or 2. Again, the Java compiler flags this construct as an error. You
cannot apply the 1 1 operator to numbers. You need to write two Boolean expressions and join
them with the | | operator:
if (input == 1 | | input == 2) . . .
Common Error 3.6
- if\
Confusing &&and | | Conditions
It is a surprisingly common error to confuse and and or conditions. A value lies between 0 and
100 if it is at least 0 and at most 100. It lies outside that range if it is less than 0 or greater than
100. There is no golden rule; you just have to think carefully.
Often the and or or is clearly stated, and then it isn’t too hard to implement it. But some¬
times the wording isn’t as explicit. It is quite common that the individual conditions are nicely
set apart in a bulleted list, but with little indication of how they should be combined. Consider
these instructions for filing a tax return. You can claim single filing status if any one of the fol¬
lowing is true:
• You were never married.
• You were legally separated or divorced on the last day of the tax year.
• You were widowed, and did not remarry.
Since the test passes if any one of the conditions is true, you must combine the conditions with
or. Elsewhere, the same instructions state that you may use the more advantageous status of
married filing jointly if all five of the following conditions are true:
• Your spouse died less than two years ago and you did not remarry.
• You have a child whom you can claim as dependent.
• That child lived in your home for all of the tax year.
• You paid over half the cost of keeping up your home for this child.
• You filed a joint return with your spouse the year he or she died.
Because all of the conditions must be true for the test to pass, you must combine them with an
and.
Short-Circuit Evaluation of Boolean Operators
The && and 1 1 operators are computed using short-circuit evaluation.
In other words, logical expressions are evaluated from left to right,
and evaluation stops as soon as the truth value is determined. When
an && is evaluated and the first condition is false, the second condition
is not evaluated, because it does not matter what the outcome of the
second test is.
For example, consider the expression
quantity > 0 && price / quantity < 10
The && and | |
operators are
computed using
short-circuit
evaluation: As soon
as the truth value is
determined, no
further conditions
are evaluated.
3.7 Boolean Variables and Operators 115
Suppose the value of quantity is zero. Then the test quantity > 0 fails, and the second test is not
attempted. That is just as well, because it is illegal to divide by zero.
Similarly, when the first condition of an | | expression is true, then the remainder is not
evaluated because the result must be true.
This process is called short-circuit evaluation.
In a short circuit, electricity travels along the path of least
resistance. Similarly, short-circuit evaluation takes the fast¬
est path for computing the result of a Boolean expression.
De Morgan’s Law
Humans generally have a hard time comprehending logical conditions with not operators
applied to and/or expressions. De Morgan’s Law, named after the logician Augustus De Mor¬
gan (1806-1871), can be used to simplify these Boolean expressions.
Suppose we want to charge a higher shipping rate if we don’t ship within the continental
United States.
if (! (country. equal s("USA") && !state.equals("AK") && !state.equals("HI")))
{
shippingCharge = 20.00;
}
This test is a little bit complicated, and you have to think carefully through the logic. When it
is not true that the country is USA and the state is not Alaska and the state is not Hawaii, then
charge $20.00. Huh? It is not true that some people won’t be confused by this code.
The computer doesn’t care, but it takes human programmers to write and maintain the
code. Therefore, it is useful to know how to simplify such a condition.
De Morgan’s Law has two forms: one for the negation of an
and expression and one for the negation of an or expression: Qe Morgan’s law tells
I (A && B) isthesameas 1A 1 1 IB
I (A || B) isthesameas !A && !B
Pay particular attention to the fact that the and and or operators are reversed by moving the
not inward. For example, the negation of “the state is Alaska or it is Hawaii”,
! (state. equals("AK") || state. equals("HI"))
is “the state is not Alaska and it is not Hawaii”:
!state.equals("AK") && !state.equals("HI")
Now apply the law to our shipping charge computation:
! (country . equal s("USA")
&& I state . equal s("AK")
&& I state . equal s("HI"))
is equivalent to
! country. equals ("USA")
|| I I state. equal s("AK")
| I !state.equals("HI"))
116 Chapter 3 Decisions
Because two ! cancel each other out, the result is the simpler test
! country. equal s( "USA")
| | state. equals("AK")
| | state. equals("HI")
In other words, higher shipping charges apply when the destination is outside the United
States or to Alaska or Hawaii.
To simplify conditions with negations of and or or expressions, it is usually a good idea to
apply De Morgan’s Law to move the negations to the innermost level.
3.8 Application: Input Validation
An important application for the if statement is input validation. Whenever
your program accepts user input, you need to make sure that the user-supplied
values are valid before you use them in your computations.
Consider our elevator simulation program. Assume that the elevator panel
has buttons labeled 1 through 20 (but not 13). The following are illegal inputs:
• The number 13
• Zero or a negative number
• A number larger than 20
• An input that is not a sequence of digits, such as five
In each of these cases, we will want to give an error message and exit the
program.
It is simple to guard against an input of 13:
if (floor == 13)
{
System. out. println("Error: There is no thirteenth floor.");
}
Here is how you ensure that the user doesn’t enter a number outside the valid range:
if (floor <= 0 | | floor > 20)
{
System. out. println("Error: The floor must be between 1 and 20.");
}
However, dealing with an input that is not a valid integer is a more serious problem.
When the statement
Like a quality control worker,
you want to make sure that
user input is correct before
processing it.
Call the hasNextlnt or
hasNextDouble
method to ensure
that the next input is
a number.
floor = in.nextlntO;
is executed, and the user types in an input that is not an integer (such as five), then
the integer variable floor is not set. Instead, a run-time exception occurs and the pro¬
gram is terminated. To avoid this problem, you should first call the hasNextlnt method
which checks whether the next input is an integer. If that method returns true, you
can safely call nextlnt. Otherwise, print an error message and exit the program.
if (in.hasNextlntO)
{
int floor = in.nextlntO;
Process the input value
}
B.8 Application: Input Validation 117
else
{
System. out. println("Error: Not an integer.");
}
Here is the complete elevator simulation program with input validation:
section_8/ElevatorSimulation2.java
1 import java. util .Scanner;
2
3 /**
4 This program simulates an elevator panel that skips the 13th floor, checking for
5 input errors.
6 */
7 public class ElevatorSimulation2
8 {
9
10
1 1
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 }
Program Run
Floor: 13
Error: There is no thirteenth floor.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in) ;
System. out. print( Floor: );
if (in.hasNextlntO)
{
// Now we know that the user entered an integer
int floor = in.nextlntO ;
if (floor == 13)
{
System. out. println("Error: There is no thirteenth floor.');
}
else if (floor <= 0 | | floor > 20)
{
System. out. println("Error: The floor must be between 1 and 20. );
}
el se
{
// Now we know that the input is valid
int actual Floor = floor;
if (floor > 13)
{
actual Floor = floor - 1;
}
System. out. println("The elevator will travel to the actual floor
+ actual Floor) ;
}
}
else
{
System. out. printing Error: Not an integer. );
}
118 Chapter 3 Decisions
36. In the El evatorSi mul ati on2 program, what is the output when the input is
a. 100?
b. -1?
c. 20?
d. thirteen?
37. Your task is to rewrite lines 19-26 of the El evatorSi mul ati on2 program so that
there is a single i f statement with a complex condition. What is the condition?
if (■ ■ ■)
{
System. out. println("Error: Invalid floor number");
}
38. In the Sherlock Holmes story “The Adventure of the Sussex Vampire”, the
inimitable detective uttered these words: “Matilda Briggs was not the name of
a young woman, Watson, ... It was a ship which is associated with the giant rat
of Sumatra, a story for which the world is not yet prepared.” Over a hundred
years later, researchers found giant rats in Western New Guinea, another part of
Indonesia.
Suppose you are charged with writing a program that processes rat weights. It
contains the statements
System. out. print("Enter weight in kg: ");
double weight = in . nextDoubleO ;
What input checks should you supply?
When processing inputs, you want to reject values that are too large. But how large is too large?
These giant rats, found in Western New Guinea, are about five times the size of a city rat.
39. Run the following test program and supply inputs 2 and three at the prompts.
What happens? Why?
import java. util .Scanner
public class Test
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in) ;
System. out. print("Enter an integer: ");
int m = in.nextlntO ;
System. out. print("Enter another integer: ");
int n = in.nextlntO I
System. out. println(m + " " + n);
}
Practice It Now you can try these exercises at the end of the chapter: R3.3, R3.32, P3.ll.
VIDEO EXAMPLE 3.2
The Genetic Code
fWILEYO
rPLUS
Watch this Video Example to see how to build a “decoder ring” for
the genetic code.
© Available online in WileyPLUS and at www.wiley.com/college/horstmann.
B.8 Application: Input Validation 119
Random Fact 3.2 Artificial Intelligence
V "Wj When one uses a
% sophisticated com¬
puter program such as a tax prepara¬
tion package, one is bound to attribute
some intelligence to the computer.
The computer asks sensible questions
and makes computations that we find
a mental challenge. After all, if doing
one’s taxes were easy, we wouldn't
need a computer to do it for us.
As programmers, however, we
know that all this apparent intelligence
is an illusion. Human programmers
have carefully “coached” the software
in all possible scenarios, and it simply
replays the actions and decisions that
were programmed into it.
Would it be possible to write com¬
puter programs that are genuinely
intelligent in some sense? From the
earliest days of computing, there was
a sense that the human brain might
be nothing but an immense computer,
and that it might well be feasible to
program computers to imitate some
processes of human thought. Serious
research into artificial intelligence
began in the mid-1950s, and the first
twenty years brought some impres¬
sive successes. Programs that play
chess — surely an activity that appears
to require remarkable intellectual pow¬
ers — have become so good that they
now routinely beat all but the best
human players. As far back as 1975,
an expert-system program called
Mycin gained fame for being better in
diagnosing meningitis in patients than
the average physician.
However, there were serious set¬
backs as well. From 1982 to 1992,
the Japanese government embarked
on a massive research project, funded
at over 40 billion Japanese yen. It was
known as the Fifth-Generation Project.
Its goal was to develop new hardware
and software to greatly improve the
performance of expert system soft¬
ware. At its outset, the project created
fear in other countries that the Japa¬
nese computer industry was about to
become the undisputed leader in the
field. However, the end results were
disappointing and did little to bring
artificial intelligence applications to
market.
From the very outset, one of the
stated goals of the Al community was
to produce software that could trans¬
late text from one language to another,
for example from English to Russian.
That undertaking proved to be enor¬
mously complicated. Human language
appears to be much more subtle and
interwoven with the human experi¬
ence than had originally been thought.
Even the grammar-checking tools that
come with word-processing programs
today are more of a gimmick than a
useful tool, and analyzing grammar
is just the first step in translating
sentences.
The CYC (from encyclopedia) proj¬
ect, started by Douglas Lenat in 1 984,
tries to codify the implicit assump¬
tions that underlie human speech and
writing. The team members started
out analyzing news articles and asked
themselves what unmentioned facts
are necessary to actually understand
the sentences. For example, consider
the sentence, “Last fall she enrolled in
Michigan State”. The reader automati¬
cally realizes that “fall” is not related
to falling down in this context, but
refers to the season. While there is
a state of Michigan, here Michigan
State denotes the university. A priori,
a computer program has none of this
knowledge. The goal of the CYC proj¬
ect is to extract and store the requi¬
site facts — that is, (1) people enroll in
universities; (2) Michigan is a state; (3)
many states have universities named
X State University, often abbreviated
as X State; (4) most people enroll in
a university in the fall. By 1995, the
project had codified about 100,000
common-sense concepts and about
a million facts of knowledge relating
them. Even this massive amount of
data has not proven sufficient for use¬
ful applications.
In recent years, artificial intelli¬
gence technology has seen substantial
advances. One of the most astounding
examples is the outcome of a series
of “grand challenges” for autono¬
mous vehicles posed by the Defense
Advanced Research Projects Agency
(DARPA). Competitors were invited to
submit a computer-controlled vehi¬
cle that had to complete an obstacle
course without a human driver or
remote control. The first event, in
2004, was a disappointment, with
none of the entrants finishing the
route. In 2005, five vehicles com¬
pleted a grueling 2 1 2 km course in the
Mojave desert. Stanford’s Stanley came
in first, with an average speed of 30
km/h. In 2007, DARPA moved the com¬
petition to an “urban” environment, an
abandoned air force base. Vehicles
had to be able to
interact with each
other, following Cali¬
fornia traffic laws. As
Stanford’s Sebastian
Thrun explained: “In
the last Grand Chal¬
lenge, it didn’t really
matter whether an
obstacle was a rock
or a bush, because
either way you’d just
drive around it. The
current challenge is to
move from just sens¬
ing the environment
to understanding it.”
Winner of the 2007 DARPA Urban Challenge
120 Chapter 3 Decisions
CHAPTER SUMMARY
Use the if statement to implement a decision.
• The i f statement allows a program to carry out
different actions depending on the nature of the
data to be processed.
Implement comparisons of numbers and objects.
• Use relational operators (< <= > >= == !=) to compare numbers.
• Do not use the == operator to compare strings. Use the equal s method instead.
• The compareTo method compares strings in lexicographic order.
Implement complex decisions that require multiple if statements.
• Multiple i f statements can be combined to evaluate complex decisions.
• When using multiple i f statements, test general conditions after more specific
conditions.
Implement decisions whose branches require further decisions.
• When a decision statement is contained inside the branch of another decision
statement, the statements are nested.
• Nested decisions are required for problems that have two levels of decision
making.
for visualizing the control flow of a program.
• Flow charts are made up of elements for tasks,
input/output, and decisions.
• Each branch of a decision can contain tasks and further
decisions.
• Never point an arrow inside another branch.
Design test cases for your programs.
• Each branch of your program should be covered by a test case.
• It is a good idea to design test cases before implementing a program.
• Logging messages can be deactivated when testing is complete.
Condition
True
False
Draw flowcharts
Review Exercises 121
Use the Boolean data type to store and combine conditions that can be true or false.
• The Boolean type boolean has two values, false and true.
• Java has two Boolean operators that combine conditions: && {and) and 1 1 (or).
• To invert a condition, use the ! {not) operator.
• The && and 1 1 operators are computed using short-circuit evaluation: As soon as
the truth value is determined, no further conditions are evaluated.
• De Morgan’s law tells you how to negate && and 1 1 conditions.
Apply if statements to detect whether user input is valid.
• Call the hasNextlnt or hasNextDoubl e method to ensure that the
next input is a number.
STANDARD LIBRARY ITEMS INTRODUCED IN THIS CHAPTER
java. lang. String
equals
compareTo
java. util .Scanner
hasNextDouble
hasNextlnt
j ava .util .1 oggi ng . Level
INFO
OFF
java. util . logging . Logger
getClobal
i nfo
setLevel
REVIEW EXERCISES
. R3.1 What is the value of each variable after the i f statement?
a. int n = 1; int k = 2; int r = n;
if (k < n) { r = k; }
b. int n = 1; int k = 2; int r;
if(n<k){r = k; }
else { r = k + n; }
C. int n = 1; int k = 2; int r = k ;
if(r<k){n = r;}
else { k = n; }
d. int n = 1; int k = 2; int r = 3;
if(r<n + k){r = 2*n;}
else { k = 2 * r; }
■ ■ R3.2 Explain the difference between
s = 0;
if (x > 0) { s++; }
if (y > 0) { s++; }
and
s = 0;
if (x > 0) { s++; }
else if (y > 0) { s++; }
122 Chapter 3 Decisions
■ ■ R3.3 Find the errors in the following i f statements.
a. if x > 0 then System. out. print(x) ;
b. if (1 + x > Math.pow(x, Math.sqrt(2)) { y = y + x; }
c. if (x = 1) { y++; }
d. x = in.nextlntO ;
if (in.hasNextlntO)
{
sum = sum + x;
}
else
{
System. out. println("Bad input for x");
}
e. String letterCrade = "F";
if (grade >= 90) { letterCrade = "A"; }
if (grade >= 80) { letterGrade = "B"; }
if (grade >= 70) { letterCrade = "C"; }
if (grade >= 60) { letterCrade = "D"; }
■ R3.4 What do these code fragments print?
a. int n = 1;
int m = -1;
if (n < -m) { System. out. print(n) ; }
else { System. out. print(m) ; }
b. int n = 1;
int m = -1;
if (-n >= m) { System. out. print(n) ; }
else { System. out. print(m) ; }
C. double x = 0;
double y = 1;
if (Math.abs(x - y) < 1) { System. out. print(x) ; }
else { System. out. print(y) ; }
d. double x = Math.sqrt(2);
double y = 2;
if (x * x == y) { System. out. print(x); }
else { System. out. print(y) ; }
■ ■ R3.5 Suppose x and y are variables of type doubl e. Write a code fragment that sets y to x if x
is positive and to 0 otherwise.
■ ■ R3.6 Suppose x and y are variables of type doubl e. Write a code fragment that sets y to the
absolute value of x without calling the Math . abs function. Use an i f statement.
■ ■ R3.7 Explain why it is more difficult to compare floating-point numbers than integers.
Write Java code to test whether an integer n equals 10 and whether a floating-point
number x is approximately equal to 10.
. R3.8 It is easy to confuse the = and == operators. Write a test program containing the
statement
if (floor = 13)
What error message do you get? Write another test program containing the
statement
count == 0;
What does your compiler do when you compile the program?
Review Exercises
123
■ R3.9 Each square on a chess board can be described by a letter and number, such as g5 in
this example:
abcdefgh
The following pseudocode describes an algorithm that determines whether a square
with a given letter and number is dark (black) or light (white).
If the letter is an a, c, e, or g
If the number is odd
color * "black"
Else
color * "white"
Else
If the number is even
color * "black"
Else
color * "white"
Using the procedure in Programming Tip 3.5, trace this pseudocode with input g5.
R3.10 Give a set of four test cases for the algorithm of Exercise R3.9 that covers all
branches.
R3. 1 1 In a scheduling program, we want to check whether two appointments overlap. For
simplicity, appointments start at a full hour, and we use military time (with hours
0-24). The following pseudocode describes an algorithm that determines whether
the appointment with start time startl and end time endl overlaps with the appoint¬
ment with start time starts and end time end /.
If startl > start/
s » startl
Else
s » start/
If endl * end /
e = endl
Else
e = end /
If s < e
The appointments overlap.
Else
The appointments don't overlap.
Trace this algorithm with an appointment from 10-12 and one from 1 1-13, then with
an appointment from 10-1 1 and one from 12-13.
124 Chapter 3 Decisions
■ R3.12
■ R3.13
■ R3.14
.. R3.15
■ ■ R3.16
■ ■ R3.17
■ ■ R3.18
■ ■ R3.19
■ ■ R3.20
■ R3.21
■ ■ R3.22
. R3.23
■ ■ R3.24
Draw a flow chart for the algorithm in Exercise R3.1 1 .
Draw a flow chart for the algorithm in Exercise P3.17.
Draw a flow chart for the algorithm in Exercise P3.1 8.
Develop a set of test cases for the algorithm in Exercise R3.1 1.
Develop a set of test cases for the algorithm in Exercise P3.18.
Write pseudocode for a program that prompts the user for a month and day and
prints out whether it is one of the following four holidays:
• New Year’s Day (January 1)
• Independence Day (July 4)
• Veterans Day (November 11)
• Christmas Day (December 25)
Write pseudocode for a program that assigns letter grades for a quiz, according to the
following table:
Score Grade
90-100 A
80-89 B
70-79 C
60-69 D
< 60 F
Explain how the lexicographic ordering of strings in Java differs from the order¬
ing of words in a dictionary or telephone book. Hint: Consider strings such as IBM,
wiley.com, Century 21, and While-U-Wait.
Of the following pairs of strings, which comes first in lexicographic order?
a. "Tom", "jerry"
b. "Tom", "Tomato"
C. "church", "Churchill"
d. "car manufacturer", "carburetor"
e. "Harry" , "hai ry"
f. "Java", " Car"
g. "Tom", "Tom"
h. "Car", "Carl"
i. "car", "bar"
Explain the difference between an i f/el se i f /el se sequence and nested i f statements.
Give an example of each.
Give an example of an i f/el se i f/el se sequence where the order of the tests does not
matter. Give an example where the order of the tests matters.
Rewrite the condition in Section 3.3 to use < operators instead of >= operators. What
is the impact on the order of the comparisons?
Give a set of test cases for the tax program in Exercise P3.22. Manually compute the
expected results.
Review Exercises 125
R3.2 5 Make up a Java code example that shows the dangling else problem using the follow¬
ing statement: A student with a GPA of at least 1 .5, but less than 2, is on probation.
With less than 1 .5, the student is failing.
R3.26 Complete the following truth table by finding the truth values of the Boolean
expressions for all combinations of the Boolean inputs p, q, and r.
p
q
r
(p && q) || ! r
! (p && (q || ! r))
fal se
false
fal se
fal se
false
true
fal se
true
fal se
5 more combinations
R3.27 True or false? A && B is the same as B && A for any Boolean conditions A and B.
R3.28 The “advanced search” feature of many search engines allows you to use Boolean
operators for complex queries, such as “(cats OR dogs) AND NOT pets”. Contrast
these search operators with the Boolean operators in Java.
R3.29 Suppose the value of b is fal se and the value of x is 0. What is the value of each of the
following expressions?
a. b && x 0
b. b || x == 0
C. ! b && x == 0
d. !b || x == 0
e. b && x != 0
f. b 1 1 x != 0
g. !b && x != 0
h. !b || x != 0
R3.30 Simplify the following expressions. Here, b is a variable of type bool ean.
a. b == true
b. b == fal se
C. b != true
d. b != false
R3.31 Simplify the following statements. Here, b is a variable of type boolean and n is a vari¬
able of type int.
a. if (n == 0) { b = true; } else { b = false; }
(Hint: What is the value of n == 0?)
b. if (n == 0) { b = false; } else { b = true; }
C. b = false; if (n > 1) { if (n < 2) { b = true; } }
d. if (n < 1) { b = true; } else { b = n > 2; }
126 Chapter 3 Decisions
■ R3.32 What is wrong with the following program?
System. out. print("Enter the number of quarters: ") ;
int quarters = in . nextlnt() ;
if (in.hasNextlntO)
{
total = total + quarters * 0.25;
System. out. println ("Total : " + total);
}
else
{
System. out. println ("Input error.") ;
}
PROGRAMMING EXERCISES
■ P3. 1 Write a program that reads an integer and prints whether it is negative, zero, or
positive.
■ ■ P3.2 Write a program that reads a floating-point number and prints “zero” if the number
is zero. Otherwise, print “positive” or “negative”. Add “small” if the absolute value
of the number is less than 1, or “large” if it exceeds 1,000,000.
■ ■ P3.3 Write a program that reads an integer and prints how many digits the number has, by
checking whether the number is > 10, > 100, and so on. (Assume that all integers are
less than ten billion.) If the number is negative, first multiply it with -1 .
■ ■ P3.4 Write a program that reads three numbers and prints “all the same” if they are all the
same, “all different” if they are all different, and “neither” otherwise.
■ ■ P3.5 Write a program that reads three numbers and prints “increasing” if they are in
increasing order, “decreasing” if they are in decreasing order, and “neither” other¬
wise. Here, “increasing” means “strictly increasing”, with each value larger than its
predecessor. The sequence 3 4 4 would not be considered increasing.
■ ■ P3.6 Repeat Exercise P3.5, but before reading the numbers, ask the user whether increas¬
ing/decreasing should be “strict” or “lenient”. In lenient mode, the sequence 3 4 4 is
increasing and the sequence 4 4 4 is both increasing and decreasing.
■ ■ P3.7 Write a program that reads in three integers and prints “in order” if they are sorted in
ascending or descending order, or “not in order” otherwise. For example,
125 in order
152 not in order
521 in order
122 in order
■ ■ P3.8 Write a program that reads four integers and prints “two pairs” if the input consists
of two matching pairs (in some order) and “not two pairs” otherwise. For example,
1221 two pai rs
1223 not two pai rs
2222 two pai rs
Programming Exercises 127
■ P3.9 Write a program that reads a temperature value and the letter C for Celsius or F for
Fahrenheit. Print whether water is liquid, solid, or gaseous at the given temperature
at sea level.
P3.10 The boiling point of water drops by about one degree centigrade for every 300
meters (or 1,000 feet) of altitude. Improve the program of Exercise P3.9 to allow the
user to supply the altitude in meters or feet.
P3. 1 1 Add error handling to Exercise P3 .10. If the user does not enter a number when
expected, or provides an invalid unit for the altitude, print an error message and end
the program.
P3. 1 2 Write a program that translates a letter grade into a number grade. Letter grades are
A, B, C, D, and F, possibly followed by + or -. Their numeric values are 4, 3, 2, 1, and
0. There is no F+ or F-. A + increases the numeric value by 0.3, a - decreases it by 0.3.
However, an A+ has value 4.0.
Enter a letter grade: B-
The numeric value is 2.7.
P3. 1 3 Write a program that translates a number between 0 and 4 into the closest letter
grade. For example, the number 2.8 (which might have been the average of several
grades) would be converted to B-. Break ties in favor of the better grade; for example
2.85 should be a B.
P3. 1 4 Write a program that takes user input describing a playing card in the following
shorthand notation:
A Ace
2 ... 10 Card values
1 Jack
Q Queen
K King
D Diamonds
H Hearts
S Spades
C Clubs
Your program should print the full description of the card. For example,
Enter the card notation: QS
Queen of Spades
P3. 1 5 Write a program that reads in three floating-point numbers and prints the largest of
the three inputs. For example:
Please enter three numbers: 4 9 2.5
The largest number is 9.
P3. 1 6 Write a program that reads in three strings and sorts them lexicographically.
Enter three strings: Charlie Able Baker
Able
Baker
Charlie
128 Chapter B Decisions
■ ■ P3. 1 7 When two points in time are compared, each given as hours (in military time, rang¬
ing from 0 and 23) and minutes, the following pseudocode determines which comes
first.
If hourl < hour!
timel comes first.
Else if hourl and hourZ are the same
If minute 1 < miwuteZ
timel comes first.
Else if minute 1 and minuteZ are the same
timel and timeZ are the same.
Else
timeZ comes first.
Else
timeZ comes first.
Write a program that prompts the user for two points in time and prints the time that
comes first, then the other time.
■ ■ P3. 1 8 The following algorithm yields the season (Spring, Summer, Fall, or Winter) for a
given month and day.
If month is 1, Z, or $. season * "Winter"
Else if month is 4, 5, or 6, season * "Spring"
Else if month is 7, S, or 9, season s "Summer"
Else if month is 10, 1 1, or 1Z, season * "Fall"
If month is divisible by 9 and day >» Z1
If season is "Winter", season = "Spring"
Else if season is "Spring", season * "Summer"
Else if season is "Summer", season = "Fall"
Else season = "Winter"
Write a program that prompts the user for a month
and day and then prints the season, as determined
by this algorithm.
■ ■ P3. 1 9 Write a program that reads in two floating-point numbers and tests whether they are
the same up to two decimal places. Here are two sample runs.
Enter two floating-point numbers: 2.0 1.99998
They are the same up to two decimal places.
Enter two floating-point numbers: 2.0 1.98999
They are different.
■ ■■ P3.20
Write a program that prompts for the day and month of the user’s birthday and then
prints a horoscope. Make up fortunes for programmers, like this:
Please enter your birthday (month and day): 6 16
Gemini are experts at figuring out the behavior of complicated programs.
You feel where bugs are coming from and then stay one step ahead. Tonight,
your style wins approval from a tough critic.
Each fortune should contain the name of the astrological sign. (You will find the
names and date ranges of the signs at a distressingly large number of sites on the
Internet.)
Programming Exercises
129
■ ■ P3.21 The original U.S. income tax of 1913 was quite simple. The tax was
• 1 percent on the first $50,000.
• 2 percent on the amount over $50,000 up to $75,000.
• 3 percent on the amount over $75,000 up to $100,000.
• 4 percent on the amount over $100,000 up to $250,000.
• 5 percent on the amount over $250,000 up to $500,000.
• 6 percent on the amount over $500,000.
There was no separate schedule for single or married taxpayers. Write a program that
computes the income tax according to this schedule.
■ ■ P3.22 Write a program that computes taxes for the following schedule.
If your status is Single and
if the taxable income is over
but not over
the tax is
of the amount over
$0
$8,000
10%
$0
$8,000
$32,000
$800 + 15%
$8,000
$32,000
$4,400 + 25%
$32,000
If your status is Married and
if the taxable income is over
but not over
the tax is
of the amount over
$0
$16,000
10%
$0
$16,000
$64,000
$1,600 + 15%
$16,000
$64,000
$8,800 + 25%
$64,000
■ ■ P3.23 The TaxCalculator. java program uses a simplified version of the 2008 U.S. income tax
schedule. Look up the tax brackets and rates for the current year, for both single and
married filers, and implement a program that computes the actual income tax.
■ ■ P3.24 Unit conversion. Write a unit conversion program that asks the users from which
unit they want to convert (fl. oz, gal, oz, lb, in, ft, mi) and to which unit they want to
convert (ml, 1, g, kg, mm, cm, m, km). Reject incompatible conversions (such as gal
—* km). Ask for the value to be converted, then display the result:
Convert from? gal
Convert to? ml
Value? 2.5
2 . 5 gal = 9462 . 5 ml
■ P3.2 5 Write a program that prompts the user to provide a single character from the alpha¬
bet. Print Vowel or Consonant, depending on the user input. If the user input is
not a letter (between a and z or A and Z), or is a string of length > 1, print an error
message.
1 BO Chapter 3 Decisions
■ ■ ■ P3.26 Roman numbers. Write a program that converts a positive integer into the Roman
number system. The Roman number system has digits
I
1
V
5
X
10
L
50
C
100
D
500
M
1,000
Numbers are formed according to the following rules:
a. Only numbers up to 3,999 are represented.
b. As in the decimal system, the thousands, hundreds, tens, and ones are
expressed separately.
c. The numbers 1 to 9 are expressed as
I 1
II 2
III 3
IV 4
V 5
VI 6
VII 7
VIII 8
IX 9
As you can see, an I preceding a V or X is subtracted from the value, and you
can never have more than three I’s in a row.
d. Tens and hundreds are done the same way, except that the letters X, L, C and C,
D, M are used instead of I, V, X, respectively.
Your program should take an input, such as 1978, and convert it to Roman numerals,
MCMLXXVIII.
■ ■ P3.27 Write a program that asks the user to enter a month (1 for January, 2 for February,
and so on) and then prints the number of days in the month. For February, print “28
or 29 days”.
Enter a month: 5
30 days
Do not use a separate i f/el se branch for each month. Use Boolean operators.
■ ■ ■ P3.28 A year with 366 days is called a leap year. Leap years are necessary to keep the cal¬
endar synchronized with the sun because the earth revolves around the sun once
every 365.25 days. Actually, that figure is not entirely precise, and for all dates after
1582 the Gregorian correction applies. Usually years that are divisible by 4 are leap
years, for example 1996. However, years that are divisible by 100 (for example, 1900)
are not leap years, but years that are divisible by 400 are leap years (for example,
X* ‘ \M -J
MCMXXV1I
Programming Exercises 131
2000). Write a program that asks the user for a year and computes whether that year
is a leap year. Use a single i f statement and Boolean operators.
■ ■ ■ P3.29 French country names are feminine when they end with the letter e, masculine other¬
wise, except for the following which are masculine even though they end with e:
• le Belize
• le Cambodge
• le Mexique
• le Mozambique
• le Zaire
• le Zimbabwe
Write a program that reads the French name of a country and adds the article: le for
masculine or la for feminine, such as le Canada or la Belgique.
However, if the country name starts with a vowel, use 1’; for example, l’Afghanistan.
For the following plural country names, use les:
• les Etats-Unis
• les Pays-Bas
■ Business P3.30 Write a program to simulate a bank transaction. There are two bank accounts: check¬
ing and savings. First, ask for the initial balances of the bank accounts; reject nega¬
tive balances. Then ask for the transactions; options are deposit, withdrawal, and
transfer. Then ask for the account; options are checking and savings. Then ask for the
amount; reject transactions that overdraw an account. At the end, print the balances
of both accounts.
■ Business P3.31 Write a program that reads in the name and salary of an employee. Here the salary
will denote an hourly wage, such as $9.25. Then ask how many hours the employee
worked in the past week. Be sure to accept fractional hours. Compute the pay. Any
overtime work (over 40 hours per week) is paid at 150 percent of the regular wage.
Print a paycheck for the employee.
■ Business P3.32
When you use an automated teller machine (ATM) with your bank card, you need
to use a personal identification number (PIN) to access your account. If a user fails
more than three times when entering the PIN, the machine will block the card.
Assume that the user’s PIN is “1234” and write a program that asks the user for the
PIN no more than three times, and does the following:
• If the user enters the right number, print a message saying, “Your PIN is
correct”, and end the program.
• If the user enters a wrong number, print a message saying, “Your PIN is
incorrect” and, if you have asked for the PIN less than three times, ask for it
again.
• If the user enters a wrong number three times, print a message saying “Your
bank card is blocked” and end the program.
■ Business P3.33 Calculating the tip when you go to a restaurant is not difficult, but your restaurant
wants to suggest a tip according to the service diners receive. Write a program that
calculates a tip according to the diner’s satisfaction as follows:
• Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied,
2 = Satisfied, 3 = Dissatisfied.
1 32 Chapter 3 Decisions
• If the diner is totally satisfied, calculate a 20 percent tip.
• If the diner is satisfied, calculate a 15 percent tip.
• If the diner is dissatisfied, calculate a 1 0 percent tip.
• Report the satisfaction level and tip in dollars and cents.
■ Business P3.34 A supermarket awards coupons depending on how much a customer spends on
groceries. For example, if you spend $50, you will get a coupon worth eight percent
of that amount. The following table shows the percent used to calculate the coupon
awarded for different amounts spent. Write a program that calculates and prints the
value of the coupon a person can receive based on groceries purchased.
Here is a sample run:
Please enter the cost of your groceries: 14
You win a discount coupon of $ 1.12. (8% of your purchase)
Money Spent
Coupon Percentage
Less than $10
No coupon
From $10 to $60
8%
More than $60 to $150
10%
More than $150 to $210
12%
More than $210
14%
■ Science P3.35 Write a program that prompts the user for a wavelength value and prints a descrip¬
tion of the corresponding part of the electromagnetic spectrum, as given in the fol¬
lowing table.
Electromagnetic Spectrum
Type
Wavelength (m)
Frequency (Hz)
Radio Waves
> 10_1
< 3 x 109
Microwaves
O
1
o
o
1
3 x 109 to 3 x 1011
Infrared
7 x 10-7 to 10-3
3 x 1011 to4x 1014
Visible light
4 x 10-7 to 7 x 10-7
4 x 1014 to 7.5 xlO14
Ultraviolet
10“8 to 4 x 1 0~7
7.5 x 1014 to 3 x 1016
X-rays
o
1
o
o
1
oo
3 x 1016 to 3 x 1019
Gamma rays
< 10-11
>3 x 1019
■ Science P3.36 Repeat Exercise P3.35, modifying the program so that it prompts for the frequency
instead.
Programming Exercises IBB
Science P3.37 Repeat Exercise P3.35, modifying the program so that it first asks the user whether
the input will be a wavelength or a frequency.
Science P3.38 A minivan has two sliding doors. Each door can be
opened by either a dashboard switch, its inside handle,
or its outside handle. However, the inside handles do not
work if a child lock switch is activated. In order for the
sliding doors to open, the gear shift must be in park, and
the master unlock switch must be activated. (This book’s
author is the long-suffering owner of just such a vehicle.)
Your task is to simulate a portion of the control software for the vehicle. The input is
a sequence of values for the switches and the gear shift, in the following order:
• Dashboard switches for left and right sliding door, child lock, and master
unlock (0 for off or 1 for activated)
• Inside and outside handles on the left and right sliding doors (0 or 1)
• The gear shift setting (one of P N D 1 2 3 R).
A typical input would be 00010100 P.
Print “left door opens” and/or “right door opens” as appropriate. If neither door
opens, print “both doors stay closed”.
Science P3.39
Sound level L in units of decibel (dB) is determined by
L = 20 log10(p/p0)
where p is the sound pressure of the sound (in Pascals, abbreviated Pa), andp0 is a
reference sound pressure equal to 20 x 10-6 Pa (where L is 0 dB). The following table
gives descriptions for certain sound levels.
Threshold of pain
130 dB
Possible hearing damage
120 dB
Jack hammer at 1 m
100 dB
Traffic on a busy roadway at 10 m
90 dB
Normal conversation
60 dB
Calm library
30 dB
Light leaf rustling
0 dB
Write a program that reads a value and a unit, either dB or Pa, and then prints the
closest description from the list above.
Science P3.40
The electric circuit shown below is designed to measure the temperature of the gas in
a chamber.
1 34 Chapter 3 Decisions
The resistor R represents a temperature sensor enclosed in the chamber. The resis¬
tance R, in Q, is related to the temperature T, in °C, by the equation
R — Rq + kT
In this device, assume Rq = 100 £2 and k = 0.5. The voltmeter displays the value of the
voltage, Vm , across the sensor. This voltage V m indicates the temperature, T, of the
gas according to the equation
T = ° = Rs
k k k V — V k
s m
Suppose the voltmeter voltage is constrained to the range Vm;n =12 volts < Vm <
Vmax = 18 volts. Write a program that accepts a value of Vm and checks that it’s
between 12 and 18. The program should return the gas temperature in degrees
Celsius when Vm is between 12 and 18 and an error message when it isn’t.
■ ■■ Science P3.41
Crop damage due to frost is one of the many risks confronting farmers. The figure
below shows a simple alarm circuit designed to warn of frost. The alarm circuit uses
a device called a thermistor to sound a buzzer when the temperature drops below
freezing. Thermistors are semiconductor devices that exhibit a temperature depen¬
dent resistance described by the equation
R = RQe
fl
1'
[t
“tJ
where R is the resistance, in £2, at the temperature T, in °K, and Rq is the resistance,
in £2, at the temperature T0, in°K. /3 is a constant that depends on the material used to
make the thermistor.
The circuit is designed so that the alarm will sound when
R2 < R4
R + 7^2 R 3 4- R ^
The thermistor used in the alarm circuit has Rq = 33,192 Q at T0 = 40 °C, and
P = 3,310 °K. (Notice that has units of °K. The temperature in °K is obtained by
adding 273° to the temperature in °C.) The resistors i?2> and ^4 have a resistance
of 156.3 k£2 = 156,300 £2.
Write a Java program that prompts the user for a temperature in °F and prints a
message indicating whether or not the alarm will sound at that temperature.
Answers to Self-Check Questions 135
■ Science P3.42 A mass m = 2 kilograms is attached to the end of a rope of length r = 3 meters. The
mass is whirled around at high speed. The rope can withstand a maximum tension
of T = 60 Newtons. Write a program that accepts a rotation speed v and determines
whether such a speed will cause the rope to break. Hint: T = mv2 /r.
■ Science P3.43 A mass m is attached to the end of a rope of length r = 3 meters. The rope can only
be whirled around at speeds of 1 , 1 0, 20, or 40 meters per second. The rope can
withstand a maximum tension of T = 60 Newtons. Write a program where the user
enters the value of the mass m, and the program determines the greatest speed at
which it can be whirled without breaking the rope. Hint: T — m v2 / r.
■ ■ Science P3.44 The average person can jump off the ground
with a velocity of 7 mph without fear of leaving
the planet. However, if an astronaut jumps with
this velocity while standing on Halley’s Comet,
will the astronaut ever come back down? Create
a program that allows the user to input a launch
velocity (in mph) from the surface of Halley’s
Comet and determine whether a jumper will
return to the surface. If not, the program should
calculate how much more massive the comet
must be in order to return the jumper to the surface.
Hint: Escape velocity is vx
escape
= J 2
GM
R
, where G = 6.67 x 10 11Nm2/kg2 is
the gravitational constant, M = 1.3 x 1022kg is the mass of Halley’s comet, and
R — 1.153 x 106m is its radius.
ANSWERS TO SELF-CHECK QUESTIONS
1 . Change the i f statement to
if (floor > 14)
{
actual Floor = floor - 2;
}
2. 85.90.85.
3. The only difference is if original Price is 100.
The statement in Self Check 2 sets di scounted-
Pri ce to 90; this one sets it to 80.
4. 95.100.95.
5. if (fuelAmount < 0.10 * fuelCapacity)
{
System. out. println(" red") ;
}
else
{
System. out. println ("green") ;
}
6. (a) and (b) are both true, (c) is false.
7. floor <= IS
8. The values should be compared with ==, not =.
9. input. equals("Y")
10. str.equalsC") or str.length() == 0
11. if (scoreA > scoreB)
{
System. out. println("A won");
}
else if (scoreA < scoreB)
{
System. out. println("B won");
}
else
{
System. out. println("Came tied") ;
}
12. if (x > 0) { s = 1; }
else if (x < 0) { s = -1; }
else { s = 0; }
1 36 Chapter 3 Decisions
1 3. You could first set s to one of the three values:
s = 0;
if (x > 0) { s = 1; }
else if (x < 0) { s = -1; }
1 4. The if (price <= 100) can be omitted (leaving
just el se), making it clear that the el se branch
is the sole alternative.
1 5. No destruction of buildings.
1 6. Add a branch before the final el se:
else if (richter < 0)
{
System. out. println("Error: Negative input");
}
17. 3200.
1 8. No. Then the computation is 0.10 x 32000 +
0.25 x (32000 -32000).
1 9. No. Their individual tax is $5,200 each, and if
they married, they would pay $10,400. Actu¬
ally, taxpayers in higher tax brackets (which
our program does not model) may pay higher
taxes when they marry, a phenomenon known
as the marriage penalty.
20. Change else in line 41 to
else if (maritalStatus.equals("m"))
and add another branch after line 52:
else
{
System. out. println(
"Error: marital status should be s or m.");
}
2 1 . The higher tax rate is only applied on the
income in the higher bracket. Suppose you are
single and make $31,900. Should you try to
get a $200 raise? Absolutely: you get to keep
90 percent of the first $100 and 75 percent of
the next $100.
22.
Read temp
True
temp < 0? Print “Frozen”
False
23. The “True” arrow from the first decision
points into the “True” branch of the second
decision, creating spaghetti code.
24. Here is one solution. In Section 3.7, you will
see how you can combine the conditions for a
more elegant solution.
True
Input <0?
Status = Error
False
True „ £(T, „
Input >100?
Status = Error
False
Status = “OK”
25.
Read x
True
x < 0?
False
Print Vx Print “Error”
26.
Read temp
temp < 0?
True
Print “Ice”
False
temp > 100?
True
Print “Steam”
False
Print “Liquid”
Answers to Self-Check Questions 137
Test
Case
Expected
Output
Comment
1 1
1 1
Below 13th floor
14
13
Above 1 3th floor
13
?
The specification is not clear — See
Section 3.8 for a version of this
program with error handling
29. A boundary test case is a price of $128. A 16
percent discount should apply because the
problem statement states that the larger dis¬
count applies if the price is at least $128. Thus,
the expected output is $107.52.
Test
Case
Expected
Output
Comment
9
Most structures fall
7.5
Many buildings destroyed
6.5
Many buildings ...
5
Pamage to poorly...
3
No destruction...
8.0 Most structures fall Boundary case. In this
program, boundary cases
are not as significant
because the behavior of
an earthquake changes
gradually.
-1
The specification is not
clear — see Self Check
1 6 for a version of this
program with error
handling.
Test Case
Expected Output Comment
(0.5, 0.5)
inside
(4 .1)
outside
(0,2)
on the boundary Exactly on the boundary
(1.414, 1.414)
on the boundary Close to the boundary
(0, 1.9)
inside Not less than 1 mm
from the boundary
(0, 2.1)
outside Not less than 1 mm
from the boundary
32. x == 0 && y == 0
33. x == 0 1 1 y == 0
34. (x == 0 && y != 0) || (y == 0 && x != 0)
35. The same as the value of frozen.
36. You are guaranteed that there are no other
values. With strings or integers, you would
need to check that no values such as "maybe" or
-1 enter your calculations.
37. (a) Error: The floor must be between 1 and 20.
(b) Error: The floor must be between 1 and 20.
(c) 19 (d) Error: Not an integer.
38. floor ==13 || floor <= 0 | | floor > 20
39. Check for i n . hasNextDoubl e () , to make sure a
researcher didn’t supply an input such as oh
my. Check for wei ght <= 0, because any rat must
surely have a positive weight. We don’t know
how giant a rat could be, but the New Guinea
rats weighed no more than 2 kg. A regular
house rat {rattus rattus) weighs up to 0.2 kg, so
we’ll say that any weight > 10 kg was surely an
input error, perhaps confusing grams and kilo¬
grams. Thus, the checks are
if (in.hasNextDoubleO)
{
double weight = in.nextDoubleO ;
if (weight < 0)
{
System. out. print! n(
"Error: Weight cannot be negative.");
}
else if (weight > 10)
{
System. out. print! n(
"Error: Weight > 10 kg.");
}
else
{
Process valid weight.
}
}
else
}
System. out. print("Error: Not a number");
}
40. The second input fails, and the program termi¬
nates without printing anything.
CHAPTER
LOOPS
CHAPTER COALS
To implement whi 1 e, for, and do loops
To hand-trace the execution of a program
To become familiar with common
loop algorithms
To understand nested loops
To implement programs that read and process data sets
To use a computer for simulations
CHAPTER CONTENTS
4.1 THE WHILE LOOP 140
Syntax 4. 1: while Statement 141
Common Error 4.1 : Don’t Think “Are We
There Yet?” 1 44
Common Error 4.2: Infinite Loops 145
Common Error 4.3: Off-by-One Errors 145
Random Fact 4. 1: The First Bug 146
4.2 PROBLEM SOLVING:
HAND-TRACING 147
4.3 THE FOR LOOP 1 50
Syntax 4.2: for Statement 152
Programming Tip 4.1 : Use for Loops for Their
Intended Purpose Only 155
Programming Tip 4.2: Choose Loop Bounds That
Match Your Task 1 55
Programming Tip 4.3: Count Iterations 1 56
4.4 THE DO LOOP 1 56
Programming Tip 4.4: Flowcharts for Loops 1 57
4.5 APPLICATION: PROCESSING
SENTINEL VALUES 158
Special Topic 4.1 : The Loop-and-a-Half Problem
and the break Statement 1 60
Special Topic 4.2: Redirection of Input
and Output 1 61
Video Example 4.1 : Evaluating a Cell
Phone Plan o
4.6 PROBLEM SOLVING:
STORYBOARDS 1 62
4.7 COMMON LOOP ALGORITHMS 165
How To 4.1: Writing a Loop 169
Worked Example 4.1 : Credit Card Processing ©
4.8 NESTED LOOPS 1 72
Worked Example 4.2: Manipulating the Pixels
in an Image ©
4.9 APPLICATION: RANDOM NUMBERS
AND SIMULATIONS 176
Special Topic 4.3: Drawing Graphical Shapes 1 79
Video Example 4.2: Drawing a Spiral ©
Random Fact 4.2: Software Piracy 1 82
39
In a loop, a part of a program is repeated over and over,
until a specific goal is reached. Loops are important for
calculations that require repeated steps and for processing
input consisting of many data items. In this chapter, you will
learn about loop statements in Java, as well as techniques
for writing programs that process input and simulate
activities in the real world.
4.1 The while Loop
In this section, you will learn about loop statements that
repeatedly execute instructions until a goal has been
reached.
Recall the investment problem from Chapter 1. You
put $1 0,000 into a bank account that earns 5 percent inter¬
est per year. How many years does it take for the account
balance to be double the original investment?
In Chapter 1 we developed the following algorithm for
this problem:
Start with a year value of 0, a column for the interest, and a balance of *1 0,000.
year
interest
balance /
0
*10,000
Repeat the following steps while the balance is less than *20,000.
Add 1 to the year value.
Compute the interest as balance x 0.05 (i.e., 5 percent interest).
Add the interest to the balance.
Report the final year value as the answer.
You now know how to declare and update the variables in Java. What you don’t yet
know is how to carry out “Repeat steps while the balance is less than $20,000”.
Because the interest
earned also earns interest,
a bank balance grows
exponentially.
In a particle accelerator, subatomic particles
traverse a loop-shaped tunnel multiple times,
gaining the speed required for physical experiments.
Similarly, in computer science, statements in a
loop are executed while a condition is true.
140
4.1 The while Loop 141
A loop executes
instructions
repeatedly while a
condition is true.
Figure 1 Flowchart of awhile Loop
In Java, the while statement implements such a
repetition (see Syntax 4.1). It has the form
while ( condition )
{
statements
}
As long as the condition remains true, the statements
inside the while statement are executed. These state¬
ments are called the body of the while statement.
In our case, we want to increment the year coun¬
ter and add interest while the balance is less than the
target balance of $20,000:
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
}
balance < False
TARGET?
True
Increment
year
Calculate
i nterest
Add i nterest
to bal ance
A whi 1 e statement is an example of a loop. If you draw a flowchart, the flow of execu¬
tion loops again to the point where the condition is tested (see Figure 1).
Syntax 4.1 while Statement
Syntax while ( condition )
{
statements
}
This variable is declared outside the loop
and updated in the loop.
If the condition
never becomes false,
an infinite loop occurs.
, See page 145.
This variable is created
in each loop iteration.
double balance = 0;
Beware of "off-by-one"
errors in the loop condition.
See page 145.
while (balance < TARGET)
{
double interest = balance * RATE / 100;
balance = balance + interest;
}
Pon t put a semicolon here!
See page S6.
These statements
are executed while
the condition is true.
lining up braces
is a good idea.
See page 36.
Braces are not required if the body contains
a single statement, but it's good to always use them.
A See page 36.
142
Chapter 4 Loops
When you declare a variable inside the loop body, the variable is created for each
iteration of the loop and removed after the end of each iteration. For example, con¬
sider the i nterest variable in this loop:
while (balance < TARGET)
{ A new i nterest variable
year++ ; is created in each iteration.
double interest = balance * RATE / 100;
balance = balance + interest;
} // interest no longer declared here
In contrast, the balance and years variables were declared outside the loop body. That
way, the same variable is used for all iterations of the loop.
o
Check the loop condition
balance = 10000
year = 0
The condition is true
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
Execute the statements in the loop
balance = 10500
year = 1
interest = 500
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
Check the loop condition again
balance = 10500
year = 1
The condition is still true
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
Figure 2
Execution of the
Doubleinvestment
Loop
After 15 iterations
The condition is
while (balance < TARGET)
no longer true
balance = 20789.28
{
year++;
double interest = balance
* RATE / 100;
year = 15
balance = balance + interest;
}
Execute the statement following the loop
while (balance < TARGET)
balance = 20789.28
{
year++;
year = 15
double interest = balance * RATE / 100;
balance = balance + interest;
}
System . out . pri ntl n(year) ;
4.1 The while Loop 143
Here is the program that solves the investment problem. Figure 2 illustrates the pro¬
gram’s execution.
section_l /Doublelnvestment.java
| /**
2 This program computes the time required to double an investment.
3 */
4 public class Doubleinvestment
5 {
6 public static void main(String[] args)
7 {
8 final double RATE = 5;
9 final double INITIALJ3ALANCE = 10000;
10 final double TARGET = 2 * INITIAL_BALANCE;
1 1
12 double balance = INITIAL_BALANCE;
13 int year = 0;
14
15 // Count the years required for the investment to double
16
17 while (balance < TARGET)
18 {
19 year++;
20 double interest = balance * RATE / 100;
21 balance = balance + interest;
22 }
23
24 System. out. println( The investment doubled after "
25 + year + " years . ") ;
26 }
27 }
Program Run
The investment doubled after 15 years.
1 . How many years does it take for the investment to triple? Modify the program
and run it.
2. If the interest rate is 10 percent per year, how many years does it take for the
investment to double? Modify the program and run it.
3. Modify the program so that the balance after each year is printed. How did you
do that?
4. Suppose we change the program so that the condition of the whi 1 e loop is
while (balance <= TARGET)
What is the effect on the program? Why?
5. What does the following loop print?
int n = 1;
while (n < 100)
{
n = 2 * n;
System. out. print(n + " ");
}
Practice It
Now you can try these exercises at the end of the chapter: R4.1, R4.5, P4.14.
144
Chapter 4 Loops
Common Error 4. 1
-
Table 1 while Loop Examples
Loop
Output
Explanation
i m 0; sum = 0;
l l
When sum is 10, the loop condition is
while (sum < 10)
2 3
false, and the loop ends.
{
3 6
i++; sum = sum + i ;
4 10
Print i and sum;
}
i = 0; sum = 0;
1 -1
Because sum never reaches 10, this is an
while (sum < 10)
2 -3
“infinite loop” (see Common Error 4.2
{
3 -6
on page 145).
i++; sum = sum - i ;
4 -10
Print i and sum;
}
i = 0; sum = 0;
(No output)
The statement sum < 0 is false when the
while (sum < 0)
condition is first checked, and the loop
{
is never executed.
i++; sum = sum - i ;
Print i and sum;
}
i = 0; sum = 0;
(No output)
The programmer probably thought,
while (sum >= 10)
“Stop when the sum is at least 10.”
{
However, the loop condition controls
i++; sum = sum + i ;
when the loop is executed, not when it
Print i and sum;
ends (see Common Error 4. 1 on
}
page 144).
i = 0; sum = 0;
(No output, program
Note the semicolon before the {.
while (sum < 10) ;
does not terminate)
This loop has an empty body. It runs
{
forever, checking whether sum < 0 and
i++; sum = sum + i ;
doing nothing in the body.
Print i and sum;
}
Don’t Think “Are We There Yet?”
When doing something repetitive, most of us want to know when
we are done. For example, you may think, “I want to get at least
$20,000,” and set the loop condition to
balance >= TARGET
But the while loop thinks the opposite: How long am I allowed to
keep going? The correct loop condition is
while (balance < TARGET)
In other words: “Keep at it while the balance is less than the target.”
When writing a loop condition, don’t ask, “Are we there yet?"
The condition determines how long the loop will keep going.
4.1 The while Loop 145
Common Error 4.2
Common Error 4.3
f.
Infinite Loops
A very annoying loop error is an infinite loop: a loop that
runs forever and can be stopped only by killing the program
or restarting the computer. If there are output statements
in the program, then reams and reams of output flash by on
the screen. Otherwise, the program just sits there and hangs,
seeming to do nothing. On some systems, you can kill a hang¬
ing program by hitting Ctrl + C. On others, you can close the
window in which the program runs.
A common reason for infinite loops is forgetting to update
the variable that controls the loop:
int year = 1;
while (year <= 20)
{
double interest = balance * RATE / 100;
balance = balance + interest;
}
Here the programmer forgot to add a year++ command in the loop. As a result, the year always
stays at 1, and the loop never comes to an end.
Another common reason for an infinite loop is accidentally incrementing a counter that
should be decremented (or vice versa). Consider this example:
int year = 20;
while (year > 0)
{
double interest = balance * RATE / 100;
balance = balance + interest;
year++;
}
The year variable really should have been decremented, not incremented. This is a common
error because incrementing counters is so much more common than decrementing that your
fingers may type the ++ on autopilot. As a consequence, year is always larger than 0, and the
loop never ends. (Actually, year may eventually exceed the largest representable positive inte¬
ger and wrap around to a negative number. Then the loop ends — of course, with a completely
wrong result.)
Like this hamster who can’t
stop running in the treadmill,
an infinite loop never ends.
OfF-by-One Errors
Consider our computation of the number of years that are required to double an investment:
int year = 0;
while (balance < TARGET)
{
year++;
balance = balance * (1 + RATE / 100);
}
System. out. println("The investment doubled after "
+ year + " years.") ;
Should year start at 0 or at 1 ? Should you test for bal ance < TARGET or for bal ance <= TARGET ? It is
easy to be off by one in these expressions.
146 Chapter 4 Loops
Some people try to solve off-by-one errors by randomly inserting +1 or -1 until the pro¬
gram seems to work— a terrible strategy. It can take a long time to compile and test all the vari¬
ous possibilities. Expending a small amount of mental effort is a real time saver.
Fortunately, off-by-one errors are easy to avoid, simply by
thinking through a couple of test cases and using the information
from the test cases to come up with a rationale for your decisions.
Should year start at 0 or at 1 ? Look at a scenario with simple val¬
ues: an initial balance of $100 and an interest rate of 50 percent. After
year 1, the balance is $150, and after year 2 it is $225, or over $200. So
the investment doubled after 2 years. The loop executed two times,
incrementing year each time. Hence year must start at 0, not at 1 .
An off-by-one error is
a common error
when programming
loops. Think through
simple test cases
to avoid this type
of error.
year
balance /
0
noo
1
nso
l
VZ5
_
In other words, the bal ance variable denotes the balance after the end of the year. At the outset,
the bal ance variable contains the balance after year 0 and not after year 1 .
Next, should you use a < or <= comparison in the test? This is harder to figure out, because
it is rare for the balance to be exactly twice the initial balance. There is one case when this
happens, namely when the interest is 100 percent. The loop executes once. Now year is 1, and
balance is exactly equal to 2 * INITIAL_BALANCE. Has the investment doubled after one year? It
has. Therefore, the loop should not execute again. If the test condition is balance < TARGET, the
loop stops, as it should. If the test condition had been balance <= TARGET, the loop would have
executed once more.
In other words, you keep adding interest while the balance has not yet doubled.
RandomFact4.1 The First Bug
According to legend,
the first bug was
found in the Mark II, a huge electrome¬
chanical computer at Harvard Univer¬
sity. It really was caused by a bug — a
moth was trapped in a relay switch.
Actually, from the note that the
operator left in the log book next to
the moth (see the photo), it appears as
if the term “bug” had already been in
active use at the time.
The pioneering computer scientist
Maurice Wilkes wrote, “Somehow, at
the Moore School and afterwards, one
had always assumed there would be
no particular difficulty in getting pro¬
grams right. I can remember the exact
instant in time at which it dawned on
me that a great part of my future life
would be spent finding mistakes in my
own programs.”
t t 0 * Itxp-ci, (Sin*
l< ' ■ r j • tecT.
lS4S'
Mrit ■*<-+•* <H Ca
/?</• &*L*a*Ji JlO*-** .
\JV|otk) l r> r?. \at *
bucj |i«in^ -^oclv\T-
The First Bug
4.2 Problem Solving: Hand-Tracing 147
4.2 Problem Solving: Hand-Tracing
Hand-tracing is a
simulation of code
execution in which
you step through
instructions and
track the values of
the variables.
In Programming Tip 3.5, you learned about the method of hand-tracing. When you
hand-trace code or pseudocode, you write the names of the variables on a sheet of
paper, mentally execute each step of the code and update the variables.
It is best to have the code written or printed on a sheet of paper. Use a marker,
such as a paper clip, to mark the current line. Whenever a variable changes, cross out
the old value and write the new value below. When a program produces output, also
write down the output in another column.
Consider this example. What value is displayed?
int n = 1729;
int sum = 0;
while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System . out . pri ntl n (sum) ;
There are three variables: n, sum, and di gi t.
n
sum
digit /
\
The first two variables are initialized with 1 729 and 0 before the loop is entered.
int n = 1729;
< c ~ i int sum = 0;
while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System . out . pri ntl n (sum) ;
n
sum
digit /
1729
0
_
Because n is greater than zero, enter the loop. The variable di gi t is set to 9 (the remain¬
der of dividing 1729 by 10). The variable sum is set to 0 + 9 = 9.
int n = 1729;
int sum = 0;
while (n > 0)
{
int digit = n % 10;
f <■ > sum = sum + digit;
n = n / 10;
}
System . out . pri ntl n (sum) ;
H
sum
digit /
1729
#
9
9
_
148 Chapter 4 Loops
Finally, n becomes 172. (Recall that the remainder in the division 1729 / 10 is dis¬
carded because both arguments are integers.)
Cross out the old values and write the new ones under the old ones.
int n = 1729;
int sum = 0;
while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
< r~ ) n = n / 10;
}
System . out . pri ntl n (sum) ;
Now check the loop condition again.
int n = 1729;
int sum = 0;
< <■ > while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System . out . pri ntl n (sum) ;
n
sum
digit /
im
X
\n
9
9
_
Because n is still greater than zero, repeat
the loop. Now di gi t becomes 2, sum is set
to 9 + 2 = 1 1 , and n is set to 1 7.
Repeat the loop once again, setting di gi t
to 7, sum to 1 1 + 7 = 1 8, and n to 1 .
n
sum
digit /
vm
X
m
y
y
vt
K
r
i
IS
7
_
Enter the loop for one last time. Now
digit is set to 1, sum to 19, and n becomes
H
sum
digit /
ym
y
y
y
vt
K
y
X
u
T
0
19
1
_
zero.
4.2 Problem Solving: Hand-Tracing 149
Tracing a Loop
Hand-tracing can
help you understand
how an unfamiliar
algorithm works.
Hand-tracing can
show errors in code
or pseudocode.
int n = 1729;
int sum = 0;
( t ) while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System . out . pri nti n (sum) ;
Because n equals zero,
this condition is not true.
The condition n > 0 is now false. Continue with the statement after the loop.
int n = 1729;
int sum = 0;
while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
( <■ > System. out. println(sum);
n
sum
digit
output /
im
X
m
X
X
Yt
H
X
X
U
r
0
19
i
19
_
This statement is an output statement. The value that is output is the value of sum,
which is 19.
Of course, you can get the same answer by just running the code. However, hand¬
tracing can give you an insight that you would not get if you simply ran the code.
Consider again what happens in each iteration:
• We extract the last digit of n.
• We add that digit to sum.
• We strip the digit off n.
In other words, the loop forms the sum of the digits in n. You now know what the
loop does for any value of n, not just the one in the example. (Why would anyone
want to form the sum of the digits? Operations of this kind are useful for checking
the validity of credit card numbers and other forms of ID numbers — see Exercise
P4.32.)
Hand-tracing does not just help you understand code that works correctly. It is
a powerful technique for finding errors in your code. When a program behaves in a
way that you don’t expect, get out a sheet of paper and track the values of the vari¬
ables as you mentally step through the code.
You don’t need a working program to do hand-tracing. You can hand-trace
pseudocode. In fact, it is an excellent idea to hand-trace your pseudocode before you
go to the trouble of translating it into actual code, to confirm that it works correctly.
6. Hand-trace the following code, showing the value of n and the output.
int n = 5;
while (n >= 0)
{
n— ;
System . out . pri nt (n) ;
150 Chapter 4 Loops
7. Hand-trace the following code, showing the value of n and the output. What
potential error do you notice?
int n = 1;
while (n <= 3)
{
System. out. print(n + ", ");
n++;
}
8. Hand-trace the following code, assuming that a is 2 and n is 4. Then explain what
the code does for arbitrary values of a and n .
int r = 1;
int i = 1;
while (i <= n)
{
r = r * a;
i++;
}
9. Trace the following code. What error do you observe?
int n = 1;
while (n != 50)
{
System . out . pri ntl n (n) ;
n = n + 10;
}
1 0. The following pseudocode is intended to count the number of digits in the
number n:
count * 1
temp * n
while (temp > 1 0)
Increment count.
Pivide temp by 10.0.
Trace the pseudocode for n = 123 and n = 100. What error do you find?
Practice It Now you can try these exercises at the end of the chapter: R4.3, R4.6.
4.3 The for Loop
The for loop is
used when a
value runs from a
starting point to an
ending point with a
constant increment
or decrement.
It often happens that you want to execute a sequence of statements a given number
of times. You can use a while loop that is controlled by a counter, as in the following
example:
int counter = 1; // Initialize the counter
while (counter <= 10) // Check the counter
{
System. out. println(counter) ;
counter++; // Update the counter
}
Because this loop type is so common, there is a special form for it, called the for loop
(see Syntax 4.2).
4.3 The for Loop 151
The for Loop
for (int counter = 1; counter <= 10; counter++)
{
System. out. println (counter) ;
}
Some people call this loop count-controlled. In con¬
trast, the while loop of the preceding section can be
called an event-controlled loop because it executes
until an event occurs; namely that the balance
reaches the target. Another commonly used term
for a count-controlled loop is definite. You know
from the outset that the loop body will be executed
a definite number of times; ten times in our example.
In contrast, you do not know how many iterations
it takes to accumulate a target balance. Such a loop is
called indefinite.
The for loop neatly groups the initialization, con¬
dition, and update expressions together. However, it
is important to realize that these expressions are not
executed together (see Figure 3).
You can visualize the for loop as
an orderly sequence of steps.
• The initialization is executed once, before the loop is entered. Q
• The condition is checked before each iteration. GO
• The update is executed after each iteration. Q
Figure 3
Execution of a
for Loop
Initialize counter
for (int counter = 1; counter <= 10;
{
System. out . pri ntl n (counter) ;
}
counter++)
counter = 1
T Check condition
for (int counter = 1; counter <= 10;
{
System. out .pri ntl n (counter) ;
}
counter++)
counter = 1
^ Execute loop body
for (int counter = 1; counter <= 10;
{
System . out . pri ntl n (counter) ;
}
counter++)
counter = 1
€ Update counter
for (int counter = 1; counter <= 10;
{
System . out .pri ntl n (counter) ;
}
counter++)
counter = 2
Check condition again
for (int counter = 1; counter <= 10;
{
System . out . pri ntl n (counter) ;
}
counter++)
counter = 2
152 Chapter 4 Loops
Syntax 4.2 for Statement
Syntax
for ( initialization ; condition ; update )
{
statements
}
These three
expressions should be related.
See page 155.
This initialization
happens once
before the loop starts.
The variable i is
defined only in this for loop.
See page 155.
for (int
{
sum =
}
The condition is
checked before
each iteration.
\ /
i =5; i <=10; i++)
This update is
executed after
each iteration.
This loop executes 6 times.
£ See page 156.
A for loop can count down instead of up:
for (int counter = 10; counter >= 0; counter--) . . .
The increment or decrement need not be in steps of 1 :
for (int counter = 0; counter <= 10; counter = counter + 2) . . .
See Table 2 for additional variations.
So far, we have always declared the counter variable in the loop initialization:
for (int counter = 1; counter <= 10; counter++)
{
}
// counter no longer declared here
Table 2 for Loop Examples
Loop
Values of i
Comment
for (i = 0; i <= 5; i++)
012345
Note that the loop is executed 6 times. (See
Programming Tip 4.3 on page 156.)
for (i = 5; i >= 0; i— )
543210
Use i -- for decreasing values.
for (i =0; i <9; i = i +2)
02468
Use i = i + 2 for a step size of 2.
for (i = 0; i != 9; i = i + 2)
0246 8 10 12 14...
(infinite loop)
You can use < or <= instead of != to avoid
this problem.
for (i = 1; i <= 20; i = i * 2)
1 248 16
You can specify any rule for modifying i ,
such as doubling it in every step.
for (i = 0; i < str.lengthO ; i++)
012... until the last valid
index of the string str
In the loop body, use the expression
str.charAt(i) to get the ith character.
4.3 The for Loop 153
Such a variable is declared for all iterations of the loop, but you cannot use it after the
loop. If you declare the counter variable before the loop, you can continue to use it
after the loop:
int counter;
for (counter = 1; counter <= 10; counter++)
{
}
// counter still declared here
Here is a typical use of the for loop. We want to print the balance of our savings
account over a period of years, as shown in this table:
Year Balance
1 10500.00
2 11025.00
3 11576.25
4 12155.06
5 12762.82
The for loop pattern applies because the variable
year starts at 1 and then moves in constant incre¬
ments until it reaches the target:
for (int year = 1; year <= nyears; year++)
{
Update balance.
Print year and balance.
}
Following is the complete program. Figure 4
shows the corresponding flowchart.
Figure 4 Flowchart of a for Loop
section_3/lnvestmentTable.java
1 import java. util .Scanner;
2
3 /**
4 This program prints a table showing the growth of an investment.
5 */
6 public class InvestmentTable
7 {
8 public static void main(String[] args)
9 {
10 final double RATE = 5;
11 final double INITIAL JALANCE = 10000;
year = 1
False
year s nyears ?
True
Update balance;
Print year and
balance
year++
154 Chapter 4 Loops
Practice It
12 double balance = INITIAL_BALANCE;
13
14 System. out. print( ; Inter number of years: );
15 Scanner in = new Scanner(System.in) ;
16 int nyears = in.nextlnt();
17
18 // Print the table of balances for each year
19
20 for (int year = 1; year <= nyears; year++)
21 {
22 double interest = balance * RATE / 100;
23 balance = balance + interest;
24 System. out. printf("%4d %10.2f\n' , year, balance);
25 }
26 }
27 }
Program Run
Enter number of years: 10
1 10500.00
2 11025.00
3 11576.25
4 12155.06
5 12762.82
6 13400.96
7 14071.00
8 14774.55
9 15513.28
10 16288.95
Another common use of the for loop is to traverse all characters of a string:
for (int i = 0; i < str.lengthO; i++)
{
char ch = str.charAt(i) ;
Process ch
}
Note that the counter variable i starts at 0, and the loop is terminated when i reaches
the length of the string. For example, if str has length 5, i takes on the values 0, 1, 2, 3,
and 4. These are the valid positions in the string.
1 1 . Write the for loop of the InvestmentTable. java program as a whi le loop.
1 2. How many numbers does this loop print?
for (int n = 10; n >= 0; n--)
{
System . out . pri ntl n (n) ;
}
1 3. Write a for loop that prints all even numbers between 10 and 20 (inclusive).
1 4. Write a for loop that computes the sum of the integers from 1 to n.
1 5. How would you modify the for loop of the InvestmentTabie. java program to
print all balances until the investment has doubled?
Now you can try these exercises at the end of the chapter: R4.4, R4.10, P4.8, P4.13.
4.3 The for Loop 155
Programming Tip 4.1
$
Programming Tip 4.2
4
Use for Loops for Their Intended Purpose Only
A for loop is an idiom for a loop of a particular form. A value runs from the start to the end,
with a constant increment or decrement.
The compiler won’t check whether the initialization, condition, and update expressions are
related. For example, the following loop is legal:
// Confusing— unrelated expressions
for (System. out. print("Inputs: "); in.hasNextDouble!) ; sum = sum + x)
{
x = in.nextDoubleO ;
}
However, programmers reading such a for loop will be confused because it does not match
their expectations. Use a whi 1 e loop for iterations that do not follow the for idiom.
You should also be careful not to update the loop counter in the body of a for loop. Con¬
sider the following example:
for (int counter = 1; counter <= 100; counter++)
{
if (counter % 10 == 0) // Skip values that are divisible by 10
{
counter++; // Bad style — you should not update the counter in a for loop
}
System. out. println(counter) ;
}
Updating the counter inside a for loop is confusing because the counter is updated again at the
end of the loop iteration. In some loop iterations, counter is incremented once, in others twice.
This goes against the intuition of a programmer who sees a for loop.
If you find yourself in this situation, you can either change from a for loop to a whi 1 e loop,
or implement the “skipping” behavior in another way. For example:
for (int counter = 1; counter <= 100; counter++)
{
if (counter % 10 ! = 0) // Skip values that are divisible by 10
{
System. out . print! n (counter) ;
I
I
Choose Loop Bounds That Match Your Task
Suppose you want to print line numbers that go from 1 to 10. Of course, you will use a loop:
for (int i = 1; i <=10; i++)
The values for i are bounded by the relation 1 < i < 10. Because there are s on both bounds, the
bounds are called symmetric.
When traversing the characters in a string, it is more natural to use the bounds
for (int i = 0; i < str.length() ; i++)
In this loop, i traverses all valid positions in the string. You can access the i th character as str .
charAt (i ) . The values for i are bounded by 0 < i < st r . 1 ength () , with a s to the left and a < to the
right. That is appropriate, because str. length!) is not a valid position. Such bounds are called
asymmetric.
In this case, it is not a good idea to use symmetric bounds:
for (int i = 0; i <= str. length!) - 1; i++) // Use < instead
The asymmetric form is easier to understand.
156 Chapter 4 Loops
Programming Tip 4.B
a
Count Iterations
Finding the correct lower and upper bounds for an iteration can be confusing. Should you
start at 0 or at 1 ? Should you use <= b or < b as a termination condition?
Counting the number of iterations is a very useful device for better understanding a loop.
Counting is easier for loops with asymmetric bounds. The loop
for (int i = a; i < b; i++)
is executed b - a times. For example, the loop traversing the characters in a string,
for (int i = 0; i < str.length(); i++)
runs str.lengthO times. That makes perfect sense, because there are str.length() characters in
a string.
The loop with symmetric bounds,
for (int i = a; i <= b; i++)
is executed b - a + 1 times. That “+1” is the source of many programming errors.
For example,
for (int i =0; i <=10; i++)
runs 1 1 times. Maybe that is what you want; if not, start at 1 or use < 10.
One way to visualize this “+1” error is
by looking at a fence. Each section has one
fence post to the left, and there is a final post
on the right of the last section. Forgetting to
count the last value is often called a “fence
post error”.
How many posts do you need for a fence
with four sections? It is easy to be “off by one"
with problems such as this one.
4.4 The do Loop
The do loop is
appropriate when
the loop body
must be executed
at least once.
ONLINE EXAMPLE
O A program to
illustrate the use of
the do loop for input
validation.
Sometimes you want to execute the body of a loop at least once and perform the loop
test after the body is executed. The do loop serves that purpose:
do
{
statements
}
while ( condition );
The body of the do loop is executed first, then the condition is tested.
Some people call such a loop a post-test loop because the condition is tested after
completing the loop body. In contrast, while and for loops ar e pre-test loops. In those
loop types, the condition is tested before entering the loop body.
A typical example for a do loop is input validation. Suppose you ask a user to enter
a value < 100. If the user doesn’t pay attention and enters a larger value, you ask
again, until the value is correct. Of course, you cannot test the value until the user has
entered it. This is a perfect fit for the do loop (see Figure 5):
4.4 The do Loop 157
<8>
Practice It
Programming Tip 4.4
4
Figure 5 Flowchart of a do Loop
int value;
do
{
System. out. print("Enter an integer < 100:
value = in . nextlnt() ;
}
while (value >= 100);
1 6. Suppose that we want to check for inputs that are
at least 0 and at most 100. Modify the do loop for
this check.
1 7. Rewrite the input check do loop using a while loop.
What is the disadvantage of your solution?
18. Suppose Java didn’t have a do loop. Could you
rewrite any do loop as a whi 1 e loop ?
1 9. Write a do loop that reads integers and computes False
their sum. Stop when reading the value 0.
20. Write a do loop that reads integers and computes their sum. Stop when reading a
zero or the same value twice in a row. For example, if the input is 1 2 3 4 4, then
the sum is 14 and the loop stops.
Now you can try these exercises at the end of the chapter: R4.9, R4.16, R4.17.
Prompt user
to enter
a value <100
Copy the input
to val ue
True
val i ip > i nn?
Flowcharts for Loops
In Section 3.5, you learned how to use flowcharts to visualize the flow of control in a program.
There are two types of loops that you can include in a flowchart; they correspond to a while
loop and a do loop in Java. They differ in the placement of the condition— either before or after
the loop body.
Condition? ‘ Loop body
True
Loop body True
Condition?
False
As described in Section 3.5, you want to avoid “spaghetti code” in your flowcharts. For loops,
that means that you never want to have an arrow that points inside a loop body
158 Chapter 4 Loops
4.5 Application: Processing Sentinel Values
A sentinel value
denotes the end of a
data set, but it is not
part of the data.
In this section, you will learn how to write loops that read and process a sequence of
input values.
Whenever you read a sequence of inputs, you
need to have some method of indicating the end
of the sequence. Sometimes you are lucky and no
input value can be zero. Then you can prompt the
user to keep entering numbers, or 0 to finish the
sequence. If zero is allowed but negative numbers
are not, you can use -1 to indicate termination.
Such a value, which is not an actual input,
but serves as a signal for termination, is called a
sentinel.
Let’s put this technique to work in a program
that computes the average of a set of salary values.
In our sample program, we will use -1 as a sentinel.
An employee would surely not work for a negative
salary, but there may be volunteers who work for
free.
Inside the loop, we read an input. If the input is
not -1 , we process it. In order to compute the aver¬
age, we need the total sum of all salaries, and the
number of inputs.
salary = in.nextDouble();
if (salary != -1)
{
sum = sum + salary;
count++;
}
We stay in the loop while the sentinel value is not detected.
while (salary != -1)
{
In the military, a sentinel guards
a border or passage, in computer
science, a sentinel value denotes
the end of an input sequence or the
border between input sequences.
}
There is just one problem: When the loop is entered for the first time, no data value
has been read. We must make sure to initialize salary with some value other than the
sentinel:
double salary = 0;
// Any value other than -1 will do
After the loop has finished, we compute and print the average. Here is the complete
program:
section_5/SentinelDemo.java
1 import java. util .Scanner;
2
3 /**
4 This program prints the average of salary values that are terminated with a sentinel.
5 V
4.5 Application: Processing Sentinel Values 159
You can use a
Boolean variable to
control a loop. Set
the variable before
entering the loop,
then set it to the
opposite to leave
the loop.
6
public class SentinelDemo
7
{
8
public static void main(String[] args)
9
{
10
double sum = 0;
1 1
int count = 0;
12
double salary = 0;
13
System. out. print( Enter salaries, -1 to finish: );
14
Scanner in = new Scanner(System.in) ;
15
16
// Process data until the sentinel is entered
17
18
while (salary != 1)
19
{
20
salary = in.nextDoubleO ;
21
if (salary != 1)
22
{
23
sum = sum + salary;
24
count++;
25
}
26
}
27
28
// Compute and print the average
29
30
if (count > 0)
31
{
32
double average = sum / count;
33
System. out. println( ’Average salary: + average);
34
}
35
else
36
{
37
System. out. println(”No data');
38
}
39
}
40
}
Program Run
Enter
salaries, -1 to finish: 10 10 40 -1
Average salary: 20
Some programmers don’t like the “trick” of initializing the input variable with a value
other than the sentinel. Another approach is to use a Boolean variable:
System. out. print("Enter salaries, -1 to finish: ") ;
boolean done = false;
while (Idone)
{
value = in.nextDouble() ;
if (value == -1)
{
done = true;
}
el se
{
Process value.
}
}
Special Topic 4. 1 on page 1 60 shows an alternative mechanism for leaving such a loop.
160 Chapter 4 Loops
Now consider the case in which any number (positive, negative, or zero) can be
an acceptable input. In such a situation, you must use a sentinel that is not a number
(such as the letter Q). As you have seen in Section 3.8, the condition
in.hasNextDoubleO
is false if the next input is not a floating-point number. Therefore, you can read and
process a set of inputs with the following loop:
System. out. print("Enter values, Q to quit: ");
while (in.hasNextDoubleO)
{
value = in.nextDouble() ;
Process value.
}
21 . What does the Sentinel Demo, java program print when the user immediately types
-1 when prompted for a value?
22. Why does the Sentinel Demo, java program have two checks of the form
salary != -1
23. What would happen if the declaration of the salary variable in Sentinel Demo, java
was changed to
double salary = -1;
24. In the last example of this section, we prompt the user “Enter values, Q to quit.”
What happens when the user enters a different letter?
25. What is wrong with the following loop for reading a sequence of values?
System. out. print("Enter values, Q to quit: ");
do
{
double value = in.nextDoubleO ;
sum = sum + value;
count++;
}
while (in.hasNextDoubleO);
Practice It Now you can try these exercises at the end of the chapter: R4.13, P4.27, P4.28.
The Loop-and-a-Half Problem and the break Statement
Consider again this loop for processing inputs until a sentinel value has been reached:
boolean done = false;
while (Idone)
{
double value = in.nextDoubleO;
if (value == -1)
{
done = true;
}
el se
{
Process value.
}
}
4.5 Application: Processing Sentinel Values 161
The actual test for loop termination is in the middle of the loop, not at the top. This is called a
loop and a half because one must go halfway into the loop before knowing whether one needs
to terminate.
As an alternative, you can use the break reserved word.
while (true)
{
double value = in.nextDoubleC) ;
if (value == -1) { break; }
Process value.
}
The break statement breaks out of the enclosing loop, independent of the loop condition.
When the break statement is encountered, the loop is terminated, and the statement following
the loop is executed.
In the loop-and-a-half case, break statements can be beneficial. But it is difficult to lay down
clear rules as to when they are safe and when they should be avoided. We do not use the break
statement in this book.
Redirection of Input and Output
Consider the Sentinel Demo program that computes the average
value of an input sequence. If you use such a program, then it is
quite likely that you already have the values in a file, and it seems
a shame that you have to type them all in again. The command
line interface of your operating system provides a way to link a
file to the input of a program, as if all the characters in the file had
actually been typed by a user. If you type
java SentinelDemo < numbers.txt
the program is executed, but it no longer expects input from the keyboard. All input com¬
mands get their input from the file numbers.txt. This process is called input redirection.
Input redirection is an excellent tool for testing programs. When you develop a program
and fix its bugs, it is boring to keep entering the same input every time you run the program.
Spend a few minutes putting the inputs into a file, and use redirection.
You can also redirect output. In this program, that is not terribly useful. If you run
Use input redirection to
read input from a file.
Use output redirection to
capture program output
in a file.
java SentinelDemo < numbers.txt > output.txt
the file output . txt contains the input prompts and the output, such as
Enter salaries, -1 to finish: Enter salaries, -1 to finish:
Enter salaries, -1 to finish: Enter salaries, -1 to finish:
Average salary: 15
However, redirecting output is obviously useful for programs that produce lots of output.
You can format or print the file containing the output.
VIDEO EXAMPLE 4.1
Evaluating a Cell Phone Plan
fWILEYO
rPLUS
In this Video Example, you will learn how to design a
program that computes the cost of a cell phone plan
from actual usage data.
© Available online in WileyPLUS and at www.wiley.com/college/horstmann.
162 Chapter 4 Loops
4.6 Problem Solving: Storyboards
A storyboard consists
of annotated
sketches for each
step in an action
sequence.
Developing a
storyboard helps you
understand the
inputs and outputs
that are required for
a program.
When you design a program that interacts with a user, you need to make a plan for
that interaction. What information does the user provide, and in which order? What
information will your program display, and in which format? What should happen
when there is an error? When does the program quit?
This planning is similar to the development of a movie or a computer game, where
storyboards are used to plan action sequences. A storyboard is made up of panels that
show a sketch of each step. Annotations explain what is happening and note any spe¬
cial situations. Storyboards are also used to develop software — see Figure 6.
Making a storyboard is very helpful when you begin designing a program. You
need to ask yourself which information you need in order to compute the answers
that the program user wants. You need to decide how to present those answers. These
are important considerations that you want to settle before you design an algorithm
for computing the answers.
Let’s look at a simple example. We want to write a program that helps users with
questions such as “How many tablespoons are in a pint?” or “How many inches are
30 centimeters?”
What information does the user provide?
• The quantity and unit to convert from
• The unit to convert to
What if there is more than one quantity? A user may have a whole table of centimeter
values that should be converted into inches.
What if the user enters units that our program doesn’t know how to handle, such
as angstrom?
What if the user asks for impossible conversions, such as inches to gallons?
Figure 6
Storyboard for the
Design of a Web
Application
4.6 Problem Solving: Storyboards 163
Let’s get started with a storyboard panel. It is a good idea to write the user inputs in
a different color. (Underline them if you don’t have a color pen handy.)
Converting a Sequence of Values
What unit do you want to convert from? cm
What unit do you want to convert to? in
Enter values, terminated by zero - Allows conversion of multiple values
30
30 cm * 11.81 in — —
j Oq Format makes clear what got converted
100 cm = 39.37 in
0
What unit do you want to convert from?
The storyboard shows how we deal with a potential confusion. A user who wants to
know how many inches are 30 centimeters may not read the first prompt carefully
and specify inches. But then the output is “30 in = 76.2 cm”, alerting the user to the
problem.
The storyboard also raises an issue. How is the user supposed to know that “cm”
and “in” are valid units? Would “centimeter” and “inches” also work? What happens
when the user enters a wrong unit? Let’s make another storyboard to demonstrate
error handling.
Handling Unknown Units (needs improvement)
What unit do you want to convert from? cm
What unit do you want to convert to? inches
Sorry, unknown unit.
What unit do you want to convert to? inch
Sorry, unknown unit.
What unit do you want to convert to? grrr
To eliminate frustration, it is better to list the units that the user can supply.
From unit (in, ft, mi, mm, cm, m, km, oz, lb, g, kg, tsp, tbsp, pint, gal): cm
To unit: in
No need to list the units again
We switched to a shorter prompt to make room for all the unit names. Exercise R4.21
explores a different alternative.
There is another issue that we haven’t addressed yet. How does the user quit the
program? The first storyboard suggests that the program will go on forever.
We can ask the user after seeing the sentinel that terminates an input sequence.
164 Chapter 4 Loops
Exiting the Program
From unit (in, ft, mi, mm, cm, m, km, oz, lb, g, kg, tsp, tbsp, pint, gal): cm
To unit: in
Enter values, terminated by zero
30
30 cm * 1 1.81 in
_ ___ — Sentinel triggers the prompt to exit
More conversions (y, n)? n
(Program exits)
As you can see from this case study, a storyboard is essential for developing a work¬
ing program. You need to know the flow of the user interaction in order to structure
your program.
26. Provide a storyboard panel for a program that reads a number of test scores and
prints the average score. The program only needs to process one set of scores.
Don’t worry about error handling.
27. Google has a simple interface for converting units. You just type the question,
and you get the answer.
Google [
How many inches in 30 cm
Search
Agvanc^ Sgagti
Web ffluhow options... Kesuits 1 - 10 of about 4,180.000 tor How many incnes in 30 cm. (0.24 seconds)
30 centimeters = 11.811 0236 inches
More about calculator.
Make storyboards for an equivalent interface in a Java program. Show a scenario
in which all goes well, and show the handling of two kinds of errors.
28. Consider a modification of the program in Self Check 26. Suppose we want to
drop the lowest score before computing the average. Provide a storyboard for
the situation in which a user only provides one score.
29. What is the problem with implementing the following storyboard in Java?
Computing Multiple Averages
Enter scores: 90 80 90 100 80
The average is 88
Enter scores: 100 70 70 100 80
The average is 88
Enter scores: 1
(Program exits)
1 is used as a sentinel to exit the program
30. Produce a storyboard for a program that compares the growth of a $10,000
investment for a given number of years under two interest rates.
Practice It Now you can try these exercises at the end of the chapter: R4.21, R4.22, R4.23.
4.7 Common Loop Algorithms 165
4.7 Common Loop Algorithms
In the following sections, we discuss some of the most common algorithms that are
implemented as loops. You can use them as starting points for your loop designs.
To compute an
average, keep a
total and a count
of all values.
4.7.1 Sum and Average Value
Computing the sum of a number of inputs is a very common task. Keep a running
total, a variable to which you add each input value. Of course, the total should be
initialized with 0.
double total = 0;
while (in.hasNextDoubleO)
{
double input = in.nextDoubleO ;
total = total + input;
}
Note that the total variable is declared outside the loop. We want the loop to update
a single variable. The i nput variable is declared inside the loop. A separate variable is
created for each input and removed at the end of each loop iteration.
To compute an average, count how many values you have, and divide by the count.
Be sure to check that the count is not zero.
double total = 0;
int count = 0;
while (in.hasNextDoubleO)
{
double input = in.nextDoubleO;
total = total + input;
count++;
}
double average = 0;
if (count > 0)
{
average = total / count;
}
To count values that
fulfill a condition,
check all values and
increment a counter
for each match.
4.7.2 Counting Matches
You often want to know how many values fulfill a particular condition. For example,
you may want to count how many spaces are in a string. Keep a counter, a variable
that is initialized with 0 and incremented whenever there is a match.
int spaces = 0;
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i) ;
if (ch = ' ')
{
spaces++;
}
}
For example, if str is "My Fai r Lady", spaces is incremented twice (when i is 2 and 7).
166 Chapter 4 Loops
Note that the spaces variable is declared outside the loop. We want the loop to
update a single variable. The ch variable is declared inside the loop. A separate variable
is created for each iteration and removed at the end of each loop iteration.
This loop can also be used for scanning inputs. The following loop reads text, a
word at a time, and counts the number of words with at most three letters:
int shortWords = 0;
while (in.hasNextO)
{
String input = in.nextO;
if (input. length() <= 3)
{
shortWords++;
}
}
In a loop that counts matches,
a counter is incremented
whenever a match is found.
mwm
Mjttf III
4.7.3 Finding the First Match
If your goal is to find
a match, exit the loop
when the match
is found.
When you count the values that fulfill a condition, you need to look at all values.
However, if your task is to find a match, then you can stop as soon as the condition is
fulfilled.
Here is a loop that finds the first space in a string. Because we do not visit all ele¬
ments in the string, a while loop is a better choice than a for loop:
boolean found = false;
char ch = ;
int position = 0;
while (Ifound && position < str.lengthO)
{
ch = str.charAt(position) ;
if (ch == ' ') { found = true; }
else { position++; }
}
If a match was found, then found is true, ch is
the first matching character, and position is
the index of the first match. If the loop did
not find a match, then found remains false
after the end of the loop.
Note that the variable ch is declared out¬
side the while loop because you may want to
use the input after the loop has finished. If it
had been declared inside the loop body, you
would not be able to use it outside the loop.
When searching, you look at items until a
match is found.
4.7 Common Loop Algorithms 167
4.7.4 Prompting Until a Match is Found
In the preceding example, we searched a string for a character that matches a condi¬
tion. You can apply the same process to user input. Suppose you are asking a user to
enter a positive value < 100. Keep asking until the user provides a correct input:
boolean valid = false;
double input = 0;
while C ! val id)
{
System. out. print("Pl ease enter a positive value < 100: ");
input = in.nextDouble() ;
if (0 < input && input < 100) { valid = true; }
else { System. out. println("Invalid input."); }
}
Note that the variable input is declared outside the while loop because you will want to
use the input after the loop has finished.
4.7.5 Maximum and Minimum
To find the largest
value, update the
largest value seen so
far whenever you see
a larger one.
To compute the largest value in a sequence, keep a variable that stores the largest ele¬
ment that you have encountered, and update it when you find a larger one.
double largest = in.nextDouble() ;
while (in.hasNextDoubleO)
{
double input = in.nextDouble() ;
if (input > largest)
{
largest = input;
}
}
This algorithm requires that there is at least one input.
To compute the smallest value, simply reverse the comparison:
double smallest = in.nextDouble() ;
while (in.hasNextDoubleO)
{
double input = in.nextDouble() ;
if (input < smallest)
{
smallest = input;
}
}
To find the height of the tallest bus rider ,
remember the largest value so far, and
update it whenever you see a taller one.
168 Chapter 4 Loops
To compare adjacent
inputs, store the
preceding input in
a variable.
ONLINE EXAMPLE
A program using
common loop
algorithms.
4.7.6 Comparing Adjacent Values
When processing a sequence of values in a loop, you sometimes need to compare a
value with the value that just preceded it. For example, suppose you want to check
whether a sequence of inputs contains adjacent duplicates such as 1 7 2 9 9 4 9.
Now you face a challenge. Consider the typical loop for reading a value:
double input;
while (in.hasNextDoubleO)
{
input = in.nextDouble() ;
}
How can you compare the current input
with the preceding one? At any time, input
contains the current input, overwriting the
previous one.
The answer is to store the previous input,
like this:
*
double input = 0;
while (in.hasNextDoubleO)
{
double previous = input;
input = in.nextDoubleO ;
if (input == previous)
{
System. out. println("Duplicate input") ;
}
}
One problem remains. When the loop is entered for the first time, i nput has not yet
been read. You can solve this problem with an initial input operation outside the loop:
double input = in.nextDoubleO;
while (in.hasNextDoubleO)
{
double previous = input;
input = in.nextDoubleO;
if (input == previous)
{
System. out. println("Duplicate input") ;
}
}
When comparing adjacent values, store
the previous value in a variable.
31 . What total is computed when no user input is provided in the algorithm in
Section 4.7.1?
32. How do you compute the total of all positive inputs?
33. What are the values of posi ti on and ch when no match is found in the algorithm
in Section 4.7.3?
34. What is wrong with the following loop for finding the position of the first space
in a string?
boolean found = false;
for (int position = 0; Ifound && position < str.length(); position++)
{
4.7 Common Loop Algorithms 169
char ch = str.charAt(position) ;
if (ch == 1 ') { found = true; }
}
35. How do you find the position of the last space in a string?
36. What happens with the algorithm in Section 4.7.5 when no input is provided at
all? How can you overcome that problem?
Practice It Now you can try these exercises at the end of the chapter: P4.5, P4.9, P4.10.
HOW TO 4.1
Writing a Loop
This How To walks you through the process of implementing a
loop statement. We will illustrate the steps with the following
example problem:
Read twelve temperature values (one for each month), and dis¬
play the number of the month with the highest temperature. For
example, according to http://worldclimate.com, the average maxi¬
mum temperatures for Death Valley are (in order by month, in
degrees Celsius):
18.2 22.6 26.4 31.1 36.6 42.2 45.7 44.5 40.2 33.1 24.2 17.6
In this case, the month with the highest temperature (45.7 degrees
Celsius) is July, and the program should display 7.
Step 1 Decide what work must be done inside the loop.
Every loop needs to do some kind of repetitive work, such as
• Reading another item.
• Updating a value (such as a bank balance or total).
• Incrementing a counter.
If you can’t figure out what needs to go inside the loop, start by writing down the steps that
you would take if you solved the problem by hand. For example, with the temperature reading
problem, you might write
Read first value.
Read second value.
If second value is higher than the first, set highest temperature to that value, highest month to l.
Read next value.
If value is higher than the first and second, set highest temperature to that value, highest month to 3.
Read next value.
If value is higher than the highest temperature seen so far, set highest temperature to that value,
highest month to 4.
Now look at these steps and reduce them to a set of uniform actions that can be placed into the
loop body. The first action is easy:
Read next value.
The next action is trickier. In our description, we used tests “higher than the first”, "higher
than the first and second”, “higher than the highest temperature seen so far”. We need to settle
on one test that works for all iterations. The last formulation is the most general.
170 Chapter 4 Loops
Similarly, we must find a general way of setting the highest month. We need a variable that
stores the current month, running from 1 to 12. Then we can formulate the second loop action:
If value is higher than the highest temperature, set highest temperature to that value,
highest month to current month.
Altogether our loop is
Repeat
Read next value.
If value is higher than the highest temperature,
set highest temperature to that value,
set highest month to current month.
Increment current month.
Step 2 Specify the loop condition.
What goal do you want to reach in your loop? Typical examples are
• Has a counter reached its final value?
• Have you read the last input value ?
• Has a value reached a given threshold ?
In our example, we simply want the current month to reach 12.
Step 3 Determine the loop type.
We distinguish between two major loop types. A count-controlled loop is executed a defi¬
nite number of times. In an event-controlled loop, the number of iterations is not known in
advance— the loop is executed until some event happens.
Count-controlled loops can be implemented as for statements. For other loops, consider
the loop condition. Do you need to complete one iteration of the loop body before you can
tell when to terminate the loop ? In that case, choose a do loop. Otherwise, use a whi 1 e loop.
Sometimes, the condition for terminating a loop changes in the middle of the loop body. In
that case, you can use a Boolean variable that specifies when you are ready to leave the loop.
Follow this pattern:
boolean done = false;
while (!done)
I
Po some work.
If all work has been completed
{
done = true;
}
el se
{
Po more work.
}
}
Such a variable is called a flag.
In summary,
• If you know in advance how many times a loop is repeated, use a for loop.
• If the loop body must be executed at least once, use a do loop.
• Otherwise, use a while loop.
In our example, we read 12 temperature values. Therefore, we choose a for loop.
Step 4 Set up variables for entering the loop for the first time.
List all variables that are used and updated in the loop, and determine how to initialize them.
Commonly, counters are initialized with 0 or 1, totals with 0.
4.7 Common Loop Algorithms 171
In our example, the variables are
current month
highest value
highest month
We need to be careful how we set up the highest temperature value. We can’t simply set it to
0. After all, our program needs to work with temperature values from Antarctica, all of which
may be negative.
A good option is to set the highest temperature value to the first input value. Of course,
then we need to remember to read in only 1 1 more values, with the current month starting at 2.
We also need to initialize the highest month with 1. After all, in an Australian city, we may
never find a month that is warmer than January.
Step 5 Process the result after the loop has finished.
In many cases, the desired result is simply a variable that was updated in the loop body. For
example, in our temperature program, the result is the highest month. Sometimes, the loop
computes values that contribute to the final result. For example, suppose you are asked to
average the temperatures. Then the loop should compute the sum, not the average. After the
loop has completed, you are ready to compute the average: divide the sum by the number of
inputs.
Here is our complete loop.
Read first value; store as highest value,
highest month * 1
For current month from l to 1 1
Read next value.
If value is higher than the highest value
Set highest value to that value.
Set highest month to current month.
Step 6 Trace the loop with typical examples.
Hand trace your loop code, as described in Section 4.2. Choose example values that are not too
complex— executing the loop 3-5 times is enough to check for the most common errors. Pay
special attention when entering the loop for the first and last time.
Sometimes, you want to make a slight modification to make tracing feasible. For example,
when hand-tracing the investment doubling problem, use an interest rate of 20 percent rather
than 5 percent. When hand-tracing the temperature loop, use 4 data values, not 12.
Let’s say the data are 22.6 36.6 44.5 24.2. Here is the walkthrough:
current month
current value
highest month
highestvalue /
y
ux
*
£65
X
£65 \
*
445
3
44.5
4
Ul
[
The trace demonstrates that highest month and highest value are properly set.
Step 7 Implement the loop in Java.
Here’s the loop for our example. Exercise P4.4 asks you to complete the program.
double highestValue;
highestValue = i n . nextDoubleO ;
int highestMonth = 1;
172 Chapter 4 Loops
for (int currentMonth = 2; currentMonth <= 12; currentMonth++)
{
double nextValue = in.nextDoubleO ;
if (nextValue > highestVal ue)
{
highestValue = nextValue;
highestMonth = currentMonth;
}
}
System . out . pri ntl n(hi ghestMonth) ;
WORKED EXAMPLE 4.1
Credit Card Processing
This Worked Example uses a loop to remove spaces from a
credit card number.
4.8 Nested Loops
When the body of a
loop contains
another loop, the
loops are nested. A
typical use of nested
loops is printing a
table with rows
and columns.
In Section 3.4, you saw how to nest two if statements. Similarly, complex iterations
sometimes require a nested loop: a loop inside another loop statement. When pro¬
cessing tables, nested loops occur naturally. An outer loop iterates over all rows of the
table. An inner loop deals with the columns in the current row.
In this section you will see how to print a table. For simplicity, we will simply print
the powers of x, xn, as in the table at right.
Here is the pseudocode for printing the table:
Print table header.
For x from 1 to 1 0
Print table row.
Print new line.
How do you print a table row? You need to print a
value for each exponent. This requires a second loop.
For n from 1 to 4
Print xM.
This loop must be placed inside the preceding loop. We say that the inner loop is
nested inside the outer loop.
X1
X2
X3
X4
1
1
1
1
2
4
8
16
3
9
27
81
10
100
1000
10000
The hour and minute displays in a digital clock are an
example of nested loops. The hours loop 12 times, and
for each hour, the minutes loop 60 times.
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
4.8 Nested Loops 1 73
Figure 7
Flowchart of a Nested Loop
False
is 10 ?
True
Print new line
This loop is nested
in the outer loop.
There are 10 rows in the outer loop. For each x, the program prints four columns
in the inner loop (see Figure 7). Thus, a total of 10 x 4 = 40 values are printed.
Following is the complete program. Note that we also use loops to print the table
header. However, those loops are not nested.
section_8/PowerTable.java
1 7**
2 This program prints a table of powers of x.
3 V
4 public class PowerTable
5 {
6
public static void main(String[] args)
7
{
8
final int NMAX = 4;
9
final double XMAX = 10;
10
1 1
// Print table header
12
13
for (int n = 1; n <= NMAX;
n++)
14
{
15
System . out . pri ntf ("%10d'
' i n) ;
16
}
17
System . out . pri ntl n () ;
174 Chapter 4 Loops
18 for (int n = 1; n <= NMAX; n++)
19 {
20 System. out. printf("%10s , "x );
21 }
22 System, out. printlnQ;
23
24 // Print table body
25
26 for (double x = 1; x <= XMAX; x++)
27 {
28 // Print table row
29
30 for (int n = 1; n <= NMAX; n++)
31 {
32 System. out. printf( '%10. Of , Math.pow(x, n) ) ;
33 }
34 System. out. printlnO ;
35 }
36 }
37 }
Program Run
1
2
3
4
X
X
X
X
1
1
1
1
2
4
8
16
S
9
27
81
4
16
64
256
5
25
125
625
6
36
216
1296
7
49
343
2401
8
64
512
4096
9
81
729
6561
10
100
1000
10000
33 37.
38.
39.
40.
Why is there a statement System. out . printlnO ; in the outer loop but not in the
inner loop?
How would you change the program to display all powers from x° to x5?
If you make the change in Self Check 38, how many values are displayed?
What do the following nested loops display?
for (int i =0; i < S; i++)
{
for (int j = 0; j < 4; j++)
{
System. out. print(i + j);
}
System . out . pri ntl n () ;
}
4 1 . Write nested loops that make the following pattern of brackets:
[][][][]
[][][][]
[][][][]
4.8 Nested Loops 1 75
Practice It Now you can try these exercises at the end of the chapter: R4.27, P4.19, P4.21.
Table 3 Nested Loop Examples
Nested Loops
Output
Explanation
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 4; j++) { Print "*" }
System. out. printlnO ;
}
****
****
****
Prints 3 rows of 4
asterisks each.
for (i =1; i <= 4; i++)
{
for (j = 1; j <= 3; j++) { Print "*" }
System. out. printlnO I
}
***
***
***
***
Prints 4 rows of 3
asterisks each.
for (i =1; i <= 4; i++)
{
for (j = 1; j <= i; j++) { Print "*" }
System. out. printlnO I
}
*
***
****
Prints 4 rows of
lengths 1, 2, 3, and 4.
for (i = 1; i <= 3; i++)
{
for (j si; j <= 5; j++)
{
if (j % 2 == 0) { Print }
else { Print }
}
System. out .pri ntl n() ;
}
Prints asterisks in
even columns,
dashes in odd
columns.
for (i = 1; i <= 3; i++)
{
for (j =1; j <= 5; j++)
{
if (i % 2 == j % 2) { Print }
else { Print " " }
}
System. out .pri ntl n() ;
}
* * *
* *
* * *
Prints a
checkerboard
pattern.
WORKED EXAMPLE 4.2
Manipulating the Pixels in an Image
This Worked Example shows how to use nested loops for
manipulating the pixels in an image. The outer loop tra¬
verses the rows of the image, and the inner loop accesses
each pixel of a row.
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
176 Chapter 4 Loops
4.9 Application: Random Numbers
and Simulations
. . A simulation program uses the computer to simulate an activity in the real world (or
In a simulation, you . . r ° . r ' . v
use the computer to an imaginary one). Simulations are commonly used for predicting climate change,
simulate an activity. analyzing traffic, picking stocks, and many other applications in science and busi¬
ness. In many simulations, one or more loops are used to modify the state of a system
and observe the changes. You will see examples in the following sections.
4.9.1 Generating Random Numbers
Many events in the real world are difficult to predict with absolute precision, yet we
can sometimes know the average behavior quite well. For example, a store may know
from experience that a customer arrives every five minutes. Of course, that is an aver¬
age-customers don’t arrive in five minute intervals. To accurately model customer
traffic, you want to take that random fluctuation into account. Now, how can you
run such a simulation in the computer?
v „ , The Java library has a random number generator , which produces numbers that
You can introduce J J o 7 -t
randomness by appear to be completely random. Calling Math, random () yields a random floating-point
calling the random number that is > 0 and < 1. Call Math. random() again, and you get a different number,
number generator. The following program calls Math . random() ten times.
section_9_l /RandomDemo.java
1 /**
2 This program prints ten random numbers between 0 and 1.
3 */
4 public class RandomDemo
5 {
6 public static void main(String[] args)
7 {
8 for (int i =1; i <= 10; i++)
9 {
10 double r = Math . randomO ;
11 System. out. pri ntl n (r) ;
12 }
13 }
14 }
Program Run
0.6513550469421886
0.920193662882893
0.6904776061289993
0.8862828776788884
0.7730177555323139
0.3020238718668635
0.0028504531690907164
0.9099983981705169
0.1151636530517488
0.1592258808929058
4.9 Application: Random Numbers and Simulations 1 77
Actually, the numbers are not completely random. They are drawn from sequences
of numbers that don’t repeat for a long time. These sequences are actually computed
from fairly simple formulas; they just behave like random numbers (see Exercise
P4.25). For that reason, they are often called pseudorandom numbers.
4.9.2 Simulating Die Tosses
In actual applications, you need to transform the output from
the random number generator into different ranges. For exam¬
ple, to simulate the throw of a die, you need random integers
between 1 and 6.
Here is the general recipe for computing random integers
between two bounds a and b. As you know from Program¬
ming Tip 4.3 on page 156, there are b - a + 1 values between a and
b, including the bounds themselves. First compute
(int) (Math . randomO * (b - a + 1))
to obtain a random integer between 0 and b - a, then add a, yielding a random value
between a and b:
int r = (int) (Math . randomO * (b - a + 1)) + a;
Here is a program that simulates the throw of a pair of dice:
section_9_2/Dice.java
1 /**
2 This program simulates tosses of a pair of dice.
3 */
4 public class Dice
5 {
6 public static void main(String[] args)
7 {
8 for (int i =1; i <=10; i++)
9 {
10 // Generate two random numbers between 1 and 6
1 1
12 int dl = (int) (Math. randomO * 6) + 1;
13 int d2 = (int) (Math. randomO * 6) + 1;
14 System. out. println(dl + + d2);
15 }
16 System, out. printlnO;
17 }
18 }
Program Run
5 1
2 1
1 2
5 1
1 2
6 4
4 4
6 1
6 3
5 2
178 Chapter 4 Loops
4.9.3 The Monte Carlo Method
The Monte Carlo method is
an ingenious method for find¬
ing approximate solutions to
problems that cannot be pre¬
cisely solved. (The method is
named after the famous casino in
Monte Carlo.) Here is a typical
example. It is difficult to com¬
pute the number it, but you can
approximate it quite well with
the following simulation.
Simulate shooting a dart into a square surrounding a circle of radius 1 . That is easy:
generate random x and y coordinates between -1 and 1.
If the generated point lies inside the circle, we count
it as a hit. That is the case when x2 + y2 < 1 . Because our
shots are entirely random, we expect that the ratio of hits
/ tries is approximately equal to the ratio of the areas of
the circle and the square, that is, it / 4. Therefore, our
estimate for jr is 4 x hits / tries. This method yields an
estimate for it, using nothing but simple arithmetic.
To generate a random floating-point value between -1
and 1, you compute:
doubl e r = Math . randomO ; // 0 s r < 1
double x = -1 + 2 * r; //-lsx < 1
As r ranges from 0 (inclusive) to 1 (exclusive), x ranges from -1 + 2 x 0 = -1 (inclusive)
to -1 + 2 x 1 = 1 (exclusive). In our application, it does not matter that x never reaches
1 . The points that fulfill the equation x = 1 lie on a line with area 0.
Here is the program that carries out the simulation:
section_9_3/MonteCarlo.java
1 /**
2 This program computes an estimate of pi by simulating dart throws onto a square.
3 */
4 public class MonteCarlo
5 {
6 public static void main(String[] args)
7 {
8 final int TRIES = 10000;
9
10 int hits = 0;
11 for (int i = 1; i <= TRIES; i++)
12 {
13 // Generate two random numbers between -1 and 1
14
15 double r = Math . randomO ;
16 double x = -1 + 2 * r; // Between -1 and 1
17 r = Math. randomO ;
18 double y = -1 + 2 * r;
19
4.9 Application: Random Numbers and Simulations 1 79
20 // Check whether the point lies in the unit circle
21
22 if (x * x + y * y <= 1) { hits++; }
23 }
24
25 /*
26 The ratio hits / tries is approximately the same as the ratio
2 7 circle area / square area = pi / 4
28 */
29
30 double pi Estimate = 4.0 * hits / TRIES;
31 System. out. println("Estimate for pi + piEstimate);
32 }
33 }
Program Run
Estimate for pi: 3.1504
42. How do you simulate a coin toss with the Math . randomO method?
43. How do you simulate the picking of a random playing card?
44. Why does the loop body in Dice, java call Math. randomO twice?
45. In many games, you throw a pair of dice to get a value between 2 and 12. What is
wrong with this simulated throw of a pair of dice?
int sum = (int) (Math . randomO * 11) + 2;
46. How do you generate a random floating-point number > 0 and <100?
Practice It Now you can try these exercises at the end of the chapter: R4.28, P4.7, P4.24.
Drawing Graphical Shapes
In Java, it is easy to produce simple drawings such as the
one in Figure 8. By writing programs that draw such pat¬
terns, you can practice programming loops. For now, we
give you a program outline into which you place your
drawing code. The program outline also contains the
necessary code for displaying a window containing your
drawing. You need not look at that code now. It will be
discussed in detail in Chapter 10.
Your drawing instructions go inside the draw method:
public class TwoRowsOfSquares
{
public static void draw(Graphics g)
{
drawing instructions
}
- - *
Figure 8 Two Rows of Squares
}
When the window is shown, the draw method is called, and your drawing instructions will be
executed.
180 Chapter 4 Loops
The draw method receives an object of type Graphics. The Graphics object has methods for
drawing shapes. It also remembers the color that is used for drawing operations. You can think
of the Graphics object as the equivalent of System. out for drawing shapes instead of printing
values.
Table 4 shows useful methods of the Graphi cs class.
Table 4 Graphics Methods
Method
Result
Notes
g.drawRect(x, y, width, height)
(x , y) is the top left corner.
g.drawOval (x, y, width, height)
Q
(x , y) is the top left corner
of the box that bounds the
ellipse. To draw a circle, use
the same value for width
and height.
g.fil!Rect(x, y, width, height)
The rectangle is filled in.
g.fiVIOval (x, y, width, height)
The oval is filled in.
g.drawLine(xl, yl, x2, y2)
(xl, yl)and(x2, y2) are
the endpoints.
g. drawStri ngC'Message" , x, y)
Message
Basepoint Baseline
(x, y) is the basepoint.
g.setColor(coior)
From now on,
Use Color .RED, Color. GREEN,
draw or fill methods
Col or . BLUE, and so on. (See
will use this color.
Table 10.1 for a complete
list of predefined colors.)
The program below draws the squares shown in Figure 8. When you want to produce your
own drawings, make a copy of this program and modify it. Replace the drawing tasks in the
draw method. Rename the class (for example, Spi rai instead of TwoRowsOf Squares).
special_topic_3/TwoRowsOfSquares.java
1 import java. awt. Color;
2 import java. awt. Graphics;
3 import javax. swing.] Frame;
4 import javax. swing. JComponent;
5
6 /**
7 This program draws two rows of squares.
8 */
9 public class TwoRowsOfSquares
10 {
4.9 Application: Random Numbers and Simulations 181
1 1
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public static void draw(Graphics g)
{
final int width = 20;
g.setColor(Color.BLUE) ;
// Top row. Note that the top left corner of the drawing has coordinates (0, 0)
int x = 0;
int y = 0;
for (int i =0; i <10; i++)
{
g.fillRect(x, y, width, width);
x = x + 2 * width;
}
// Second row, offset from the first one
x = width;
y = width;
for (int i =0; i <10; i++)
{
g.fillRect(x, y, width, width);
x = x + 2 * width;
}
public static void main(String[] args)
{
// Do not look at the code in the main method
// Your code will go into the draw method above
JFrame frame = new )Frame();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
frame . setSi ze(FRAME_WIDTH , FRAMEJiEIGHT) ;
frame . setDefaul tCl oseOpe rati on ( J F rame . EXIT_0l'LCL0SE) ;
IComponent component = new IComponentO
{
public void paintComponent(Graphics graph)
{
draw(graph) ;
}
};
frame.add(component) ;
frame.setVisible(true) ;
VIDEO EXAMPLE 4.2
Drawing a Spiral
/wiLEYO
rPLUS
In this Video Example, you will see how to develop a program
that draws a spiral.
© Available online in WileyPLUS and at www.wiley.com/college/horstmann.
182 Chapter 4 Loops
Random Fact 4. 2 Software Pi racy
As you read this, you
will have written a few
computer programs and experienced
firsthand how much effort it takes to
write even the humblest of programs.
Writing a real software product, such
as a financial application or a computer
game, takes a lot of time and money.
Few people, and fewer companies, are
going to spend that kind of time and
money if they don’t have a reasonable
chance to make more money from their
effort. (Actually, some companies give
away their software in the hope that
users will upgrade to more elaborate
paid versions. Other companies give
away the software that enables users to
read and use files but sell the software
needed to create those files. Finally,
there are individuals who donate their
time, out of enthusiasm, and produce
programs that you can copy freely.)
When selling software, a company
must rely on the honesty of its cus¬
tomers. It is an easy matter for an
unscrupulous person to make copies
of computer programs without paying
for them. In most countries that is ille¬
gal. Most governments provide legal
protection, such as copyright laws and
patents, to encourage the develop¬
ment of new products. Countries that
tolerate widespread piracy have found
that they have an ample cheap supply
of foreign software, but no local man¬
ufacturers willing to design good soft¬
ware for their own citizens, such as
word processors in the local script or
financial programs adapted to the local
tax laws.
When a mass market for software
first appeared, vendors were enraged
by the money they lost through piracy.
They tried to fight back by various
schemes to ensure that only the legiti¬
mate owner could use the software,
such as dongles — devices that must
be attached to a printer port before
the software will run. Legitimate users
hated these measures. They paid for
the software, but they had to suffer
through inconveniences, such as hav¬
ing multiple dongles stick out from
their computer. In the United States,
market pressures forced most vendors
to give up on these copy protection
schemes, but they are still common¬
place in other parts of the world.
Because it is so easy and inexpen¬
sive to pirate software, and the chance
of being found out is minimal, you
have to make a moral choice for your¬
self. If a package that you would really
like to have is too expensive for your
budget, do you steal it, or do you stay
honest and get by with a more afford¬
able product?
Of course, piracy
is not limited to
software. The same
issues arise for other
digital products as
well. You may have
had the opportunity
to obtain copies of
songs or movies
without payment. Or you may have
been frustrated by a copy protec¬
tion device on your music player that
made it difficult for you to listen to
songs that you paid for. Admittedly,
it can be difficult to have a lot of sym¬
pathy for a musical ensemble whose
publisher charges a lot of money for
what seems to have been very little
effort on their part, at least when
compared to the effort that goes into
designing and implementing a soft¬
ware package. Nevertheless, it seems
only fair that artists and authors
receive some compensation for their
efforts. Flow to pay artists, authors,
and programmers fairly, without
burdening honest customers, is an
unsolved problem at the time of this
writing, and many computer scientists
are engaged in research in this area.
CHAPTER SUMMARY
Explain the flow of execution in a loop.
• A loop executes instructions repeatedly while a
condition is true.
• An off-by-one error is a common error when
programming loops. Think through simple test
cases to avoid this type of error.
Use the technique of hand-tracing to analyze the behavior of a program.
• Hand-tracing is a simulation of code execution in which you step
through instructions and track the values of the variables.
• Hand-tracing can help you understand how an unfamiliar algo¬
rithm works.
• Hand-tracing can show errors in code or pseudocode.
Chapter Summary 183
Use for loops for implementing count-controlled loops.
• The for loop is used when a value runs from a starting point to an ending point
with a constant increment or decrement.
Choose between the while loop and the do loop.
• The do loop is appropriate when the loop body must be executed at least once.
Implement loops that read sequences of input data.
• A sentinel value denotes the end of a data set, but it is not part of
the data.
• You can use a Boolean variable to control a loop. Set the variable
to true before entering the loop, then set it to false to leave the
loop.
• Use input redirection to read input from a file. Use output
redirection to capture program output in a file.
Use the technique of storyboarding for planning user interactions.
• A storyboard consists of annotated sketches for each step in an action sequence.
• Developing a storyboard helps you understand the inputs and outputs that are
required for a program.
Know the most common loop algorithms.
• To compute an average, keep a total and a count of all values.
• To count values that fulfill a condition, check all values and increment a counter
for each match.
• If your goal is to find a match, exit the loop when the match is found.
• To find the largest value, update the largest value seen so far whenever you see a
larger one.
• To compare adjacent inputs, store the preceding input in a variable.
Use nested loops to implement multiple levels of iteration.
• When the body of a loop contains another loop, the loops are nested. A typical
use of nested loops is printing a table with rows and columns.
Apply loops to the implementation of simulations.
• In a simulation, you use the computer to simulate an activity.
• You can introduce randomness by calling the random number
generator.
184 Chapter 4 Loops
STANDARD LIBRARY ITEMS INTRODUCED IN THIS CHAPTER
java.awt.Color java. Tang. Math
java. awt. Graphics random
drawLi ne
drawOval
drawRect
drawStri ng
setColor
REVIEW EXERCISES
■ R4.1 Write a whi 1 e loop that prints
a. All squares less than n. For example, if n is 100, print 0 1 4 9 16 25 36 49 64 81.
b. All positive numbers that are divisible by 10 and less than n. For example, if n is
100, print 10 20 30 40 50 60 70 80 90
c. All powers of two less than n. For example, if n is 100, print 1 2 4 8 16 32 64.
■ ■ R4.2 Write a loop that computes
a. The sum of all even numbers between 2 and 100 (inclusive).
b. The sum of all squares between 1 and 100 (inclusive).
c. The sum of all odd numbers between a and b (inclusive).
d. The sum of all odd digits of n. (For example, if n is 32677, the sum would
be 3 + 7 + 7= 17.)
■ R4.3 Provide trace tables for these loops.
a. int i = 0; int j = 10; int n = 0;
while (i < j) { i++; j--; n++; }
b. int i = 0; int j = 0; int n = 0;
while (i < 10) { i++; n = n + i + j; j++; }
C. int i = 10; int j = 0; int n = 0;
while (i > 0) { i — ; j++; n = n + i - j; }
d. int i = 0; int j = 10; int n = 0;
while (i !=j){i=i+2;j=j-2; n++; }
■ R4.4 What do these loops print?
a. for (int i = 1; i < 10; i++) { System. out. pri nt (i + " "); }
b. for (int i = 1; i < 10; i += 2) { System. out. pri nt(i + " "); }
C. for (int i = 10; i > 1; i--) { System. out. print(i + " "); }
d. for (int i = 0; i < 10; i++) { System. out. print(i + " "); }
e. for (int i = 1; i < 10; i = i * 2) { System. out. print(i + " "); }
f. for (int i = 1; i < 10; i++) { if (i % 2 == 0) { System. out. print(i + " "); } }
■ R4.5 What is an infinite loop? On your computer, how can you terminate a program that
executes an infinite loop?
■ R4.6 Write a program trace for the pseudocode in Exercise P4.6, assuming the input val¬
ues are 4 7-2-5 0.
Review Exercises 185
• R4.7 What is an “off-by-one” error? Give an example from your own programming
experience.
. R4.8 What is a sentinel value? Give a simple rule when it is appropriate to use a numeric
sentinel value.
■ R4.9 Which loop statements does Java support? Give simple rules for when to use each
loop type.
R4. 1 0 How many iterations do the following loops carry out? Assume that i is not
changed in the loop body.
a. for (int i =1; i <=10; i++) . . .
b. for (int i =0; i <10; i++) . . .
C. for (int i = 10; i > 0; i--) . . .
d. for (int i = -10; i <=10; i++) . . .
e. for (int i =10; i >= 0; i++) . . .
f. for (int i = -10; i <= 10; i = i + 2) . . .
g. for (int i = -10; i <= 10; i = i + 3) . . .
R4. 1 1 Write pseudocode for a program that prints a calendar such as the following:
Su M T W Th F Sa
12 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
R4. 1 2 Write pseudocode for a program that prints a Celsius/Fahrenheit conversion table
such as the following:
Celsius | Fahrenheit
0 1
32
10 1
50
20 |
68
100 1
212
R4. 1 3 Write pseudocode for a program that reads a student record, consisting of the stu¬
dent’s first and last name, followed by a sequence of test scores and a sentinel of -1 .
The program should print the student’s average score. Then provide a trace table for
this sample input:
Harry Morgan 94 71 86 95 -1
R4. 1 4 Write pseudocode for a program that reads a sequence of student records and prints
the total score for each student. Each record has the student’s first and last name,
followed by a sequence of test scores and a sentinel of -1 . The sequence is terminated
by the word END. Here is a sample sequence:
Harry Morgan 94 71 86 95 -1
Sally Lin 99 98 100 95 90 -1
END
Provide a trace table for this sample input.
186 Chapter 4 Loops
■ R4.1 5 Rewrite the following for loop into a while loop.
int s = 0;
for (int i =1; i <=10; i++)
{
s = s + i ;
}
■ R4. 1 6 Rewrite the following do loop into a whi 1 e loop.
int n = in.nextlntO;
double x = 0;
double s;
do
{
s = 1.0 / (1 + n * n) ;
n++;
x = x + s ;
}
while (s > 0.01) ;
■ R4. 1 7 Provide trace tables of the following loops.
a. int s = 1;
int n = 1;
while (s < 10) { s = s + n; }
n++;
b. int s = 1;
for (int n = 1; n < 5; n++) { s = s + n; }
C. int s = 1;
int n = 1;
do
{
s = s + n;
n++;
}
while (s < 10 * n);
■ R4. 1 8 What do the following loops print? Work out the answer by tracing the code, not by
using the computer.
a. int s = 1;
for (int n = 1; n <= 5; n++)
{
s = s + n;
System. out. print(s + " ");
}
b. int s = 1;
for (int n = 1; s <= 10; System. out. print(s + " "))
{
n = n + 2 ;
s = s + n;
}
C. int s = 1;
int n;
for (n = 1; n <= 5; n++)
{
s = s + n;
n++;
}
System. out. print(s + " " + n) ;
Review Exercises 187
R4. 1 9 What do the following program segments print? Find the answers by tracing the
code, not by using the computer.
a. int n = 1;
for (int i = 2; i <5; i++) { n = n + i; }
System. out. print(n) ;
b. int i ;
double n = 1 / 2;
for (i = 2; i <= 5; i++) { n = n + 1.0 / i; }
System. out. print(i) ;
C. double x = 1;
double y = 1;
int i = 0;
do
{
y = y / 2;
x = x + y;
i++;
}
while (x < 1.8) ;
System. out. print(i) ;
d. double x = 1;
double y = 1;
int i = 0;
while (y >= 1. 5)
{
x = x / 2;
y = x + y;
i++;
}
System. out. print(i) ;
R4.20 Give an example of a for loop where symmetric bounds are more natural. Give an
example of a for loop where asymmetric bounds are more natural.
R4.2 1 Add a storyboard panel for the conversion program in Section 4.6 on page 1 62 that
shows a scenario where a user enters incompatible units.
R4.22 In Section 4.6, we decided to show users a list of all valid units in the prompt. If the
program supports many more units, this approach is unworkable. Give a storyboard
panel that illustrates an alternate approach: If the user enters an unknown unit, a list
of all known units is shown.
R4.23 Change the storyboards in Section 4.6 to support a menu that asks users whether
they want to convert units, see program help, or quit the program. The menu should
be displayed at the beginning of the program, when a sequence of values has been
converted, and when an error is displayed.
R4.24 Draw a flow chart for a program that carries out unit conversions as described in
Section 4.6.
R4.2 5 In Section 4.7.5, the code for finding the largest and smallest input initializes the
1 argest and smal 1 est variables with an input value. Why can’t you initialize them
with zero?
R4.26 What are nested loops? Give an example where a nested loop is typically used.
188 Chapter 4 Loops
■ ■ R4.27 The nested loops
for (int i =1; i <= height; i++)
{
for (int j = 1; j <= width; j++) { System. out. print("*") ; }
System . out . pri nti n () ;
}
display a rectangle of a given width and height, such as
****
****
Write a single for loop that displays the same rectangle.
■ ■ R4.28 Suppose you design an educational game to teach children how to read a clock. How
do you generate random values for the hours and minutes?
■ ■ ■ R4.29 In a travel simulation, Harry will visit one of his friends that are located in three
states. He has ten friends in California, three in Nevada, and two in Utah. How do
you produce a random number between 1 and 3, denoting the destination state, with
a probability that is proportional to the number of friends in each state?
PROGRAMMING EXERCISES
■ P4. 1 Write programs with loops that compute
a. The sum of all even numbers between 2 and 100 (inclusive).
b. The sum of all squares between 1 and 100 (inclusive).
c. All powers of 2 from 2° up to 220.
d. The sum of all odd numbers between a and b (inclusive), where a and b are
inputs.
e. The sum of all odd digits of an input. (For example, if the input is 32677, the
sum would be 3 + 7 + 7 = 1 7.)
■ ■ P4.2 Write programs that read a sequence of integer inputs and print
a. The smallest and largest of the inputs.
b. The number of even and odd inputs.
c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print
1 8 10 19.
d. All adjacent duplicates. For example, if the input is 133455666 2, the
program should print 3 5 6.
■ ■ P4.3 Write programs that read a line of input as a string and print
a. Only the uppercase letters in the string.
b. Every second letter of the string.
c. The string, with all vowels replaced by an underscore.
d. The number of vowels in the string.
e. The positions of all vowels in the string.
■ ■ P4.4 Complete the program in How To 4.1 on page 169. Your program should read twelve
temperature values and print the month with the highest temperature.
Programming Exercises 189
P4.5 Write a program that reads a set of floating-point values. Ask the user to enter the
values, then print
• the average of the values.
• the smallest of the values.
• the largest of the values.
• the range, that is the difference between the smallest and largest.
Of course, you may only prompt for the values once.
P4.6 Translate the following pseudocode for finding the minimum value from a set of
inputs into a Java program.
Set a Boolean variable "first” to true.
While another value has been read successfully
If first is true
Set the minimum to the value.
Set first to false.
Else if the value is less than the minimum
Set the minimum to the value.
Print the minimum.
P4.7 Translate the following pseudocode for randomly permuting the characters in a
string into a Java program.
Read a word.
| Repeat word.lengthl) times
Pick a random position i in the word, but not the last position.
Pick a random position j > i in the word.
Swap the letters at positions j and i.
Print the word.
To swap the letters, construct substrings as follows:
first i middle j last
Then replace the string with
first + word.charAt(j) + middle + word.charAt(i) + last
■ P4.8 Write a program that reads a word and prints each character of the word on a sepa¬
rate line. For example, if the user provides the input "Harry", the program prints
H
a
r
r
y
■ P4.9 Write a program that reads a word and prints the word in reverse. For example, if the
user provides the input "Harry", the program prints
yrraH
P4. 1 0 Write a program that reads a word and prints the number of vowels in the word. For
this exercise, assume that a e i o u y are vowels. For example, if the user provides the
input "Harry", the program prints 2 vowels.
190 Chapter 4 Loops
■ ■ ■ P4. 11 Write a program that reads a word and prints the number of syllables in the word.
For this exercise, assume that syllables are determined as follows: Each sequence of
adjacent vowels a e i o u y, except for the last e in a word, is a syllable. However, if
that algorithm yields a count of 0, change it to 1 . For example,
Word Syllables
Harry 2
hai ry 2
hare 1
the 1
■ ■ ■ P4. 1 2 Write a program that reads a word and prints all substrings, sorted by length. For
example, if the user provides the input "rum", the program prints
r
u
m
ru
um
rum
■ P4. 1 3 Write a program that prints all powers of 2 from 2° up to 220.
■ ■ P4. 1 4 Write a program that reads a number and prints all of its binary digits: Print the
remainder number % 2, then replace the number with number / 2. Keep going until the
number is 0. For example, if the user provides the input 13, the output should be
1
0
1
1
■ ■ P4. 1 5 Mean and standard deviation. Write a program that reads a set of floating-point data
values. Choose an appropriate mechanism for prompting for the end of the data set.
When all values have been read, print out the count of the values, the average, and
the standard deviation. The average of a data set {x^, . . ., x„j is x = Xx- jn, where
X = Xj + . . . + xn is the sum of the input values. The standard deviation is
5 =
l'Zixi-xf
However, this formula is not suitable for the task. By the time the program has
computed x , the individual xz are long gone. Until you know how to save these
values, use the numerically less stable formula
s
You can compute this quantity by keeping track of the count, the sum, and the sum
of squares as you process the input values.
Programming Exercises 191
■ ■ P4. 1 6 The Fibonacci numbers are defined by the sequence
/l=l
fl = 1
fn - fn—1 + fr.
n- 2
Reformulate that as
foldl = 1;
fold2 = 1;
fnew = foldl + fold2;
Fibonacci numbers describe the
growth of a rabbit population.
After that, discard fol d2, which is no longer needed, and set fol d2 to fol dl and fol dl to
fnew. Repeat an appropriate number of times.
Implement a program that prompts the user for an integer n and prints the nth
Fibonacci number, using the above algorithm.
■ ■ ■ P4. 1 7 Factoring of integers. Write a program that asks the user for an integer and then
prints out all its factors. For example, when the user enters 150, the program should
print
2
3
5
5
■ ■ ■ P4. 1 8 Prime numbers. Write a program that prompts the user for an integer and then prints
out all prime numbers up to that integer. For example, when the user enters 20, the
program should print
2
3
5
7
11
13
17
19
Recall that a number is a prime number if it is not divisible by any number except 1
and itself.
■ P4. 1 9 Write a program that prints a multiplication table, like this:
123456789 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
10 20 30 40 50 60 70 80 90 100
■ ■ P4.20 Write a program that reads an integer and displays, using asterisks, a filled and hol¬
low square, placed next to each other. For example if the side length is 5, the program
should display
***** *****
***** * *
***** * *
***** * *
***** ***
192 Chapter 4 Loops
■ ■ P4.2 1 Write a program that reads an integer and displays, using asterisks, a filled diamond
of the given side length. For example, if the side length is 4, the program should dis-
play
*
*******
***
*
■ ■ ■ P4.22 The game ofNim. This is a well-known game with a number of variants. The fol¬
lowing variant has an interesting winning strategy. Two players alternately take
marbles from a pile. In each move, a player chooses how many marbles to take. The
player must take at least one but at most half of the marbles. Then the other player
takes a turn. The player who takes the last marble loses.
Write a program in which the computer plays against a human opponent. Generate a
random integer between 10 and 100 to denote the initial size of the pile. Generate a
random integer between 0 and 1 to decide whether the computer or the human takes
the first turn. Generate a random integer between 0 and 1 to decide whether the
computer plays smart or stupid. In stupid mode the computer simply takes a random
legal value (between 1 and n/2) from the pile whenever it has a turn. In smart mode
the computer takes off enough marbles to make the size of the pile a power of two
minus 1 —that is, 3, 7, 15, 31, or 63. That is always a legal move, except when the size
of the pile is currently one less than a power of two. In that case, the computer makes
a random legal move.
You will note that the computer cannot be beaten in smart mode when it has the first
move, unless the pile size happens to be 15, 31, or 63. Of course, a human player who
has the first turn and knows the winning strategy can win against the computer.
■ ■ P4.23 The Drunkard’s Walk. A drunkard in a grid of streets randomly picks one of four
directions and stumbles to the next intersection, then again randomly picks one of
four directions, and so on. You might think that on average the drunkard doesn’t
move very far because the choices cancel each other out, but that is actually not the
case.
Represent locations as integer pairs (x, y). Implement the drunkard’s walk over 1 00
intersections, starting at (0, 0), and print the ending location.
■ ■ P4.24 The Monty Hall Paradox. Marilyn vos Savant described the following problem
(loosely based on a game show hosted by Monty Hall) in a popular magazine: “Sup¬
pose you’re on a game show, and you’re given the choice of three doors: Behind one
door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who
knows what’s behind the doors, opens another door, say No. 3, which has a goat.
He then says to you, “Do you want to pick door No. 2?” Is it to your advantage to
switch your choice?”
Ms. vos Savant proved that it is to your advantage, but many of her readers, includ¬
ing some mathematics professors, disagreed, arguing that the probability would not
change because another door was opened.
Your task is to simulate this game show. In each iteration, randomly pick a door
number between 1 and 3 for placing the car. Randomly have the player pick a door.
Randomly have the game show host pick a door having a goat (but not the door that
Programming Exercises 193
the player picked). Increment a counter for strategy 1 if the player wins by switching
to the host’s choice, and increment a counter for strategy 2 if the player wins by
sticking with the original choice. Run 1,000 iterations and print both counters.
■ P4.2 5 A simple random generator is obtained by the formula
rnew = (a ■ rold + b)%m
and then setting r0y to rnew. If m is chosen as 232, then you can compute
blew = * ' rold + b
because the truncation of an overflowing result to the i nt type is equivalent to
computing the remainder.
Write a program that asks the user to enter a seed value for r0]j. (Such a value is often
called a seed). Then print the first 100 random integers generated by this formula,
usings = 32310901 and b = 1729.
■ ■ P4.26 The Buffon Needle Experiment. The following experiment was devised by Comte
Georges-Louis Leclerc de Buffon (1707-1788), a French naturalist. A needle of
length 1 inch is dropped onto paper that is ruled with lines 2 inches apart. If the
needle drops onto a line, we count it as a hit. (See Figure 9.) Buffon discovered that
the quotient tries /hits approximates n.
/
Figure 9
The Buffon Needle Experiment _
For the Buffon needle experiment, you must generate two random numbers: one to
describe the starting position and one to describe the angle of the needle with the
x-axis. Then you need to test whether the needle touches a grid line.
Generate the lower point of the needle. Its x-coordinate is irrelevant, and you may
assume itsy-coordinatej[ow to be any random number between 0 and 2. The angle a
between the needle and the x-axis can be any value between 0 degrees and 1 80
degrees (jt radians). The upper end of the needle has y-coordinate
Jhigh = JW + skm
The needle is a hit if Thigh is at least 2, as shown in Figure 10. Stop after 10,000 tries
and print the quotient tries/ hits. (This program is not suitable for computing the
value of Jt. You need jt in the computation of the angle.)
34iigh _
2
31ow
Figure 10
A Hit in the Buffon Needle Experiment
o
194 Chapter 4 Loops
■ ■ Business P4.27 Currency conversion. Write a program
that first asks the user to type today’s
price for one dollar in Japanese yen,
then reads U.S. dollar values and
converts each to yen. Use 0 as a sentinel.
■ ■ Business P4.28 Write a program that first asks the user
to type in today’s price of one dollar
in Japanese yen, then reads U.S. dollar
values and converts each to Japanese
yen. Use 0 as the sentinel value to denote the end of dollar inputs. Then the program
reads a sequence of yen amounts and converts them to dollars. The second sequence
is terminated by another zero value.
U CANADA
CAD
CHINA
CNY
■ euro
EUR
fl JAPAN
JPY
^ SINGAPORE
SGD
* HONGKONG
HKD
_ - "
■ ■ Business P4.29 Your company has shares of stock it would like to sell when their value exceeds a
certain target price. Write a program that reads the target price and then reads the
current stock price until it is at least the target price. Your program should use a
Scanner to read a sequence of doubl e values from standard input. Once the minimum
is reached, the program should report that the stock price exceeds the target price.
■ ■ Business P4.30 Write an application to pre-sell a limited number of cinema tickets. Each buyer can
buy as many as 4 tickets. No more than 100 tickets can be sold. Implement a pro¬
gram called TicketSeHer that prompts the user for the desired number of tickets and
then displays the number of remaining tickets. Repeat until all tickets have been
sold, and then display the total number of buyers.
■ ■ Business P4.3I You need to control the number of people who can be in an oyster bar at the same
time. Groups of people can always leave the bar, but a group cannot enter the bar
if they would make the number of people in the bar exceed the maximum of 100
occupants. Write a program that reads the sizes of the groups that arrive or depart.
Use negative numbers for departures. After each input, display the current number
of occupants. As soon as the bar holds the maximum number of people, report that
the bar is full and exit the program.
■ ■ ■ Business P4.32 Credit Card Number Check. The last digit of a credit card number is the check
digit, which protects against transcription errors such as an error in a single digit or
switching two digits. The following method is used to verify actual credit card num¬
bers but, for simplicity, we will describe it for numbers with 8 digits instead of 16:
• Starting from the rightmost digit, form the sum of every other digit. For
example, if the credit card number is 4358 9795, then you form the sum
5 + 7+8 + 3=23.
• Double each of the digits that were not included in the preceding step. Add all
digits of the resulting numbers. For example, with the number given above,
doubling the digits, starting with the next-to-last one, yields 18 18 10 8. Adding
all digits in these values yields 1 + 8 + 1 + 8 + 1 + 0 + 8 = 27.
• Add the sums of the two preceding steps. If the last digit of the result is 0, the
number is valid. In our case, 23 + 27 = 50, so the number is valid.
Write a program that implements this algorithm. The user should supply an 8-digit
number, and you should print out whether the number is valid or not. If it is not
valid, you should print the value of the check digit that would make it valid.
Programming Exercises 195
Science P4.33 In a predator-prey simulation, you compute the populations of predators and prey,
using the following equations:
PreJn+ 1 = Preyn x (l + A- Bx predn )
Predn+1 = predn X (l -C + Dx preyn
Here, A is the rate at which prey birth exceeds natural
death, B is the rate of predation, C is the rate at which
predator deaths exceed births without food, and D repre¬
sents predator increase in the presence of food.
Write a program that prompts users for these rates, the
initial population sizes, and the number of periods. Then
print the populations for the given number of periods. As
inputs, try A = 0.1, B = C = 0.01, and-D = 0.00002 with
initial prey and predator populations of 1,000 and 20.
Science P4.34 Projectile flight. Suppose a cannonball is propelled straight into the air with a starting
velocity vq. Any calculus book will state that the position of the ball after t seconds is
s(t) = -fgt2 + vQt, where g = 9.81 m/s2 is the gravitational force of the earth. No
calculus textbook ever mentions why someone would want to carry out such an
obviously dangerous experiment, so we will do it in the safety of the computer.
In fact, we will confirm the theorem
from calculus by a simulation. In our
simulation, we will consider how the
ball moves in very short time intervals
At. In a short time interval the velocity v
is nearly constant, and we can compute
the distance the ball moves as As = v At.
In our program, we will simply set
const double DELTA_T = 0.01;
and update the position by
s = s + v * DELTA_T ;
The velocity changes constantly —in fact, it is reduced by the gravitational force of
the earth. In a short time interval, Av = -gAt, we must keep the velocity updated as
v = v - g * DELTA_T ;
In the next iteration the new velocity is used to update the distance.
Now run the simulation until the cannonball falls back to the earth. Get the initial
velocity as an input (100 m/s is a good value). Update the position and velocity 100
times per second, but print out the position only every full second. Also printout the
values from the exact formula s(t) = -fgt2 + v^t for comparison.
Note: You may wonder whether there is a benefit to this simulation when an exact
formula is available. Well, the formula from the calculus book is not exact. Actually,
the gravitational force diminishes the farther the cannonball is away from the surface
of the earth. This complicates the algebra sufficiently that it is not possible to give an
exact formula for the actual motion, but the computer simulation can simply be
extended to apply a variable gravitational force. For cannonballs, the calculus-book
formula is actually good enough, but computers are necessary to compute accurate
trajectories for higher- flying objects such as ballistic missiles.
196 Chapter 4 Loops
■ ■ ■ Science P4.35 A simple model for the hull of a ship is given by
I, _ B
f 2x )2
fzf
M - y
l -
[tJJ
1 -
[t )
where B is the beam, L is the length, and T is the draft. (Note: There are two values of
y for each x and z because the hull is symmetric from starboard to port.)
The cross-sectional area at a point x is called the “section” in nauti¬
cal parlance. To compute it, let z go from 0 to —T in n increments,
each of size T jn. For each value of z, compute the value for y.
Then sum the areas of trapezoidal strips. At right are the strips
where n = 4.
Write a program that reads in values for B, L, T, x, and n and then
prints out the cross-sectional area at x.
■ Science P4.36 Radioactive decay of radioactive materials can be mod¬
eled by the equation A = Aoe_i^og2^, where A is the
amount of the material at time t, Aq is the amount at
time 0, and h is the half-life.
Technetium-99 is a radioisotope that is used in imaging
of the brain. It has a half-life of 6 hours. Your program
should display the relative amount A / A0 in a patient
body every hour for 24 hours after receiving a dose.
■ ■■ Science P4.37
The photo at left shows an electric device called a “transformer”. Transformers are
often constructed by wrapping coils of wire around a ferrite core. The figure below
illustrates a situation that occurs in various audio devices such as cell phones and
music players. In this circuit, a transformer is used to connect a speaker to the output
of an audio amplifier.
Programming Exercises 197
The symbol used to represent the transformer is intended to suggest two coils of
wire. The parameter n of the transformer is called the “turns ratio” of the trans¬
former. (The number of times that a wire is wrapped around the core to form a coil is
called the number of turns in the coil. The turns ratio is literally the ratio of the
number of turns in the two coils of wire.)
When designing the circuit, we are concerned primarily with the value of the power
delivered to the speakers— that power causes the speakers to produce the sounds we
want to hear. Suppose we were to connect the speakers directly to the amplifier
without using the transformer. Some fraction of the power available from the
amplifier would get to the speakers. The rest of the available power would be lost in
the amplifier itself. The transformer is added to the circuit to increase the fraction of
the amplifier power that is delivered to the speakers.
The power, Ps, delivered to the speakers is calculated using the formula
/ \2
nV,
Ps = Rs 2 - —
V*o + *,,
Write a program that models the circuit shown and varies the turns ratio from 0.01 to
2 in 0.01 increments, then determines the value of the turns ratio that maximizes the
power delivered to the speakers.
Graphics P4.38 Write a program to plot the following face.
Graphics P4.39 Write a graphical application that displays a checkerboard with 64 squares, alternat¬
ing white and black.
Graphics P4.40 Write a graphical application that draws a spiral, such as the following:
p
Graphics P4.41 It is easy and fun to draw graphs of curves with the Java graphics library. Simply
draw 100 line segments joining the points (x,/(x)) and (x + d,f(x + d)), where x
ranges from xmin to xmax and d = (xmax - x^J/lOO.
Draw the curve /(x) = 0.00005x3 - 0.03x2 + 4x + 200, where x ranges from 0 to
400 in this fashion.
Graphics P4.42 Draw a picture of the “four-leaved rose” whose equation in polar coordinates is
r = cos(20) . Let 6 go from 0 to 2jt in 1 00 steps. Each time, compute r and then
compute the (x,y) coordinates from the polar coordinates by using the formula
x = r • cos (0), y = r ■ sin(0)
198 Chapter 4 Loops
ANSWERS TO SELF-CHECK QUESTIONS
1 . 23 years.
2. 7 years.
3. Add a statement
System. out. print! n (balance) ;
as the last statement in the while loop.
4. The program prints the same output. This is
because the balance after 14 years is slightly
below $20,000, and after 15 years, it is slightly
above $20,000.
5. 2 4 8 16 32 64 128
Note that the value 128 is printed even though
it is larger than 100.
6. n output
5
4 4
4 3
2 2
1 1
6 0
-1 -1
7. n output
4 1,
2 1, 2,
5 1, 2, 3,
4
There is a comma after the last value. Usually,
commas are between values only.
8. a n r i
2 4 11
2 2
4 4
8 4
16 5
The code computes a11.
9. n output
4 1
H 11
21 21
41 31
41 41
41 51
64 61
This is an infinite loop, n is never equal to 50.
10. count temp
1 \Z3
l 1 1.3
3 1 13
This yields the correct answer. The number
123 has 3 digits.
count temp
1 100
l 10.0
This yields the wrong answer. The number 100
also has 3 digits. The loop condition should
have been
while (temp >= 10)
11. int year = 1;
while (year <= nyears)
{
double interest = balance * RATE / 100;
balance = balance + interest;
System . out . pri ntf ("%4d %10 . 2f\n" ,
year, balance);
year++;
}
12. 11 numbers: 109 8 765432 1 0
13. for (int i = 10; i <= 20; i = i + 2)
{
System.out.println(i) ;
}
14. int sum = 0;
for (int i =1; i <= n; i++)
{
sum = sum + i ;
}
1 5. for (int year = 1;
balance <= 2 * INITIAL_BALANCE; year++)
However, it is best not to use a for loop in this
case because the loop condition does not relate
to the year variable. A while loop would be a
better choice.
1 6. do
{
System. out. pri nt(
"Enter a value between 0 and 100: ") ;
value = in.nextlntO ;
}
while (value < 0 | | value > 100);
1 7. int value = 100;
while (value >= 100)
{
System. out. print("Enter a value < 100: ");
value = in.nextlntO ;
}
Answers to Self-Check Questions 199
Here, the variable val ue had to be initialized
with an artificial value to ensure that the loop
is entered at least once.
1 8. Yes. The do loop
do { body } while ( condition );
is equivalent to this while loop:
boolean fi rst = true;
while (first || condition )
{
body,
first = false;
}
19. i nt x;
int sum = 0;
do
{
x = in . nextlntO ;
sum = sum + x;
}
while (x != 0);
20. i nt x = 0;
int previous;
do
{
previous = x;
x = in . nextlntO I
sum = sum + x;
}
while (x != 0 && previous != x);
21 . No data
22. The first check ends the loop after the sentinel
has been read. The second check ensures that
the sentinel is not processed as an input value.
23. The whi 1 e loop would never be entered. The
user would never be prompted for input.
Because count stays 0, the program would then
print "No data".
24. The nextDouble method also returns false.
A more accurate prompt would have been:
“Enter values, a key other than a digit to quit.”
But that might be more confusing to the pro¬
gram user who would need now ponder which
key to choose.
25. If the user doesn’t provide any numeric input,
the first call to i n . nextDoubl e () will fail.
26. Computing the average
Enter scores, Q to quit: 90 80 90 100 80 Q
The average is 88
(Program exits)
27. Simple conversion
^ Only one value can be converted
Your conversion question: How many in are 90 cm
90 cm = 1 1.81 in
(Program exits) — _ - — Rlm Pr°9ram again for another question
Unknown unit
Your conversion question: How many inches are 30 cm?
Unknown unit: inches
Known units are in, ft, mi, mm, cm, m, km, oz, lb, g, kg, tsp, tbsp, pint, gal
(Program exits)
Program doesn’t understand question syntax
Your conversion question: What is an angstrom?
Please formulate your question as "How many (unit) are (value) (unit)?”
(Program exits)
28. One score is not enough
Enter scores, Q to quit: 90 Cl
Error: At least two scores are required.
(Program exits)
29. It would not be possible to implement this
interface using the Java features we have cov¬
ered up to this point. There is no way for the
program to know when the first set of inputs
ends. (When you read numbers with val ue =
i n. nextDoubl e(), it is your choice whether to put
them on a single line or multiple lines.)
30. Comparing two interest rates
First interest rate in percent: 5
Second interest rate in percent: 1 0
Years: 3
Year 5£ 102
0 10000.00 10000.00
1 10500.00 11000.00
Z 1 10Z5.00 1Z100.00
3 1 1576.Z5 15510.00
4 1Z155.06 14641.00
5 1Z76Z.8Z 16105.10
31. The total is zero.
32. double total = 0;
while (in . hasNextDoubleO)
{
double input = in. nextDoubl e();
if (input > 0) { total = total + input; }
}
33. position is str . length() and ch is unchanged
from its initial value, ' ? ' . Note that ch must
This row clarifies that 1 means
the end of the first year
200 Chapter 4 Loops
be initialized with some value — otherwise the
compiler will complain about a possibly unini¬
tialized variable.
34. The loop will stop when a match is found, but
you cannot access the match because neither
posi ti on nor ch are defined outside the loop.
35. Start the loop at the end of string:
boolean found = false;
int i = str.lengthO - 1;
while (! found && i >= 0)
{
char ch = str.charAt(i) ;
if (ch == ' ') { found = true; }
else { i — ; }
}
36. The initial call to i n . nextDoubl e () fails, termi¬
nating the program. One solution is to do all
input in the loop and introduce a Boolean vari¬
able that checks whether the loop is entered for
the first time.
double input = 0;
boolean fi rst = true;
while (in . hasNextDoubleO)
{
double previous = input;
input = in.nextDoubleO ;
if (first) { first = false; }
else if (input == previous)
{
System . out . pri ntl n("Dupl i cate i nput") ;
}
}
37. All values in the inner loop should be dis¬
played on the same line.
38. Change lines 13, 18, and 30 to for (int n = 0;
n <= NMAX; n++). Change NMAXto 5.
39. 60: The outer loop is executed 10 times, and
the inner loop 6 times.
40. 0123
1234
2345
41. for (int i =1; i <= 3; i++)
{
for (int j = 1; j <= 4; j++)
{
System. out . pri nt(" [] ") ;
}
System. out. pri ntln() ;
}
42. Compute (int) (Math. random() * 2), and use 0
for heads, 1 for tails, or the other way around.
43. Compute (int) (Math. random() * 4) and asso¬
ciate the numbers 0 ... 3 with the four suits.
Then compute (int) (Math. random() * 13) and
associate the numbers 0 ... 12 with Jack, Ace, 2
... 10, Queen, and King.
44. We need to call it once for each die. If we
printed the same value twice, the die tosses
would not be independent.
45. The call will produce a value between 2 and
12, but all values have the same probability.
When throwing a pair of dice, the number 7 is
six times as likely as the number 2. The correct
formula is
int sum = (int) (Math. random() * 6) + (int)
(Math. random() * 6) + 2;
46. Math . random() * 100.0
CHAPTER
5
METHODS
CHAPTER COALS
To be able to implement methods
To become familiar with the concept of
parameter passing
To develop strategies for decomposing
complex tasks into simpler ones
To be able to determine the scope of a variable
To learn how to think recursively (optional)
CHAPTER CONTENTS
5.1 METHODS AS BLACK BOXES 202
5.2 IMPLEMENTING METHODS 204
Syntax 5.1 : Static Method Declaration 205
Programming Tip 5.1 : Method Comments 207
5.3 PARAMETER PASSING 207
Programming Tip 5.2: Do Not Modify Parameter
Variables 209
Common Error 5.1 : Trying to Modify
Arguments 209
5.4 RETURN VALUES 210
Common Error 5.2: Missing Return Value 21 2
How To 5. 1: Implementing a Method 212
Worked Example 5.1 : Generating Random
Passwords o
5.5 METHODS WITHOUT
RETURN VALUES 214
5.7 PROBLEM SOLVING: STEPWISE
REFINEMENT 218
Programming Tip 5.3: Keep Methods Short 223
Programming Tip 5.4: Tracing Methods 223
Programming Tip 5.5: Stubs 224
Worked Example 5.2: Calculating a
Course Grade ©
5.8 VARIABLE SCOPE 225
Video Example 5.1 : Debugging ©
5.9 RECURSIVE METHODS
(OPTIONAL) 228
How To 5.2: Thinking Recursively 231
Random Fact 5.1 : The Explosive Growth of
Personal Computers 232
Video Example 5.2: Fully Justified Text ©
5.6 PROBLEM SOLVING: REUSABLE
METHODS 215
A method packages a computation consisting of multiple
steps into a form that can be easily understood and reused.
(The person in the image to the left is in the middle of
executing the method “make espresso”.)
In this chapter, you will learn how to design and implement
your own methods. Using the process of stepwise refine¬
ment, you will be able to break up complex tasks into sets
of cooperating methods.
5.1 Methods as Black Boxes
A method is a
named sequence
of instructions.
A method is a sequence of instructions with a name. You have already encountered
several methods. For example, the Math . pow method, which was introduced in Chapter
2, contains instructions to compute a power xy. Moreover, every Java program has a
method called mai n.
You call a method in order to execute its instructions. For example, consider the
following program fragment:
public static void main(String[] args)
{
double result = Math.pow(2, 3);
}
By using the expression Math.pow(2, 3), main calls the Math. pow method, asking it to
compute 2? . The instructions of the Math. pow method execute and compute the result.
The Math . pow method returns its result back to mai n, and the mai n method resumes exe¬
cution (see Figure 1).
mai n
Pass 2 and 3 to
Math . pow
Use result
Math . pow
Compute 23
Pass result
to caller
Figure 1 Execution Flow During a Method Call
202
5.1 Methods as Black Boxes 203
Figure 2
The Math.pow Method
as a Black Box
Arguments
2, 3
Return value
8
Arguments are
supplied when a
method is called.
The return value is
the result that the
method computes.
When another method calls the Math.pow method, it provides “inputs”, such as the
values 2 and 3 in the call Math.pow(2, 3). These values are called the arguments of the
method call. Note that they are not necessarily inputs provided by a human user.
They are simply the values for which we want the method to compute a result. The
“output” that the Math . pow method computes is called the return value.
Methods can receive multiple arguments, but they return only one value. It is also
possible to have methods with no arguments. An example is the Math, random method
that requires no argument to produce a random number.
The return value of a method is returned to the calling method, where it is pro¬
cessed according to the statement containing the method call. For example, suppose
your program contains a statement
double result = Math.pow(2, 3);
When the Math.pow method returns its result, the return value is stored in the
variable result.
Do not confuse returning a value with producing program output. If you want
the return value to be printed, you need to add a statement such as System. out.
print(result).
At this point, you may wonder how the Math.pow method performs its job. For
example, how does Math.pow compute that 2? is 8? By multiplying 2x2x2? With
logarithms? Fortunately, as a user of the method, you don’t need to know how the
method is implemented. You just need to know the specification of the method: If you
provide arguments x and y, the method returns x-v. Engineers use the term black box
for a device with a given specification but unknown implementation. You can think
of Math . pow as a black box, as shown in Figure 2.
When you design your own methods, you will want to make them appear as black
boxes to other programmers. Those programmers want to use your methods without
knowing what goes on inside. Even if you are the only person working on a program,
making each method into a black box pays off: there are fewer details that you need to
keep in mind.
Although a thermostat is usually white, you
can think of it as a "black box”. The input is the
desired temperature, and the output is a signal
to the heater or air conditioner.
204 Chapter 5 Methods
1 . Consider the method call Math . pow(3 , 2) . What are the arguments and return
values?
2. What is the return value of the method call Math. pow(Math . pow(2 , 2), 2)?
3. The Math, ceil method in the Java standard library is described as follows: The
method receives a single argument a of type double and returns the smallest double
value > a that is an integer. What is the return value of Math . cei 1(2.3)?
4. It is possible to determine the answer to Self Check 3 without knowing how the
Math . cei 1 method is implemented. Use an engineering term to describe this
aspect of the Math . cei 1 method.
Practice It Now you can try these exercises at the end of the chapter: R5.3, R5.6.
5.2 Implementing Methods
In this section, you will learn how to implement a
method from a given specification. We will use a very
simple example: a method to compute the volume of a
cube with a given side length.
The cubeVol ume method uses a given side
length to compute the volume of a cube.
When declaring a
method, you provide
a name for the
method, a variable
for each argument,
and a type for
the result.
When writing this method, you need to
• Pick a name for the method (cubeVol ume).
• Declare a variable for each argument (double sideLength). These variables are called
the parameter variables.
• Specify the type of the return value (doubl e).
• Add the publi c stati c modifiers. We will discuss the meanings of these modifiers
in Chapter 8. For now, you should simply add them to your methods.
Put all this information together to form the first line of the method’s declaration:
public static double cubeVol ume(double sideLength)
This line is called the header of the method. Next, specify the body of the method.
The body contains the variable declarations and statements that are executed when
the method is called.
The volume of a cube of side length s is s x s x s. However, for greater clarity, our
parameter variable has been called si deLength, not s, so we need to compute si deLength
• sideLength * sideLength.
We will store this value in a variable called vol ume:
double volume = sideLength * sideLength * sideLength;
In order to return the result of the method, use the return statement:
return volume;
5.2 Implementing Methods 205
Syntax 5.
The body of a method is enclosed in braces. Here is the complete method:
public static double cubeVolume(double sideLength)
{
double volume = sideLength * sideLength * sideLength;
return volume;
}
Let’s put this method to use. We’ll supply a main method that calls the cubeVolume
method twice.
public static void main(String[] args)
{
double resultl = cubeVolume(2) ;
double result2 = cubeVolume(lO) ;
System. out. println ("A cube with side length 2 has volume " + resultl);
System. out. println("A cube with side length 10 has volume " + result2);
}
When the method is called with different arguments, the method returns different
results. Consider the call cubeVolume (2). The argument 2 corresponds to the sideLength
parameter variable. Therefore, in this call, sideLength is 2. The method computes
Static Method Declaration
Syntax public static returnType metbodName(parameterType parameterName, . . . )
{
method body
}
Method body, ^
executed when
method is called.
Type of return value
Name of method
/
Type of parameter variable
/Name of parameter variable
public static double cubeVolume(double sideLength)
{
double volume = sideLength * sideLength * sideLength;
return volume;
}
return statement
exits method and
returns result.
206 Chapter 5 Methods
sideLength * sideLength * sideLength, or 2 * 2 * 2. When the method is called with a dif¬
ferent argument, say 10, then the method computes 10 * 10 * 10.
Now we combine both methods into a test program. Note that both methods are
contained in the same class. Also note the comment that describes the behavior of the
cubeVolume method. (Programming Tip 5.1 describes the format of the comment.)
section_2/Cubes.java
1 /**
2 This program computes the volumes of two cubes.
3 V
4 public class Cubes
5 {
6
7
8
9
10
1 1
12
13
14
15
16
17
18
19
20
21
22
23
24 }
Program Run
A cube with side length 2 has volume 8
A cube with side length 10 has volume 1000
public static void main(String[] args)
{
double resultl = cubeVolume(2) ;
double result2 = cubeVolume(lO) ;
System. out. println("A cube with side length 2 has volume " + resultl);
System. out. println ("A cube with side length 10 has volume " + result2);
}
/**
Computes the volume of a cube.
©param sideLength he side length of the cube
©return the volume
V
public static double cubeVolume(double sideLength)
{
double volume = sideLength * sideLength * sideLength;
return volume;
5. What is the value of cubeVolume (3)?
6. What is the value of cubeVolume (cubeVol ume(2)) ?
7. Provide an alternate implementation of the body of the cubeVol ume method by
calling the Math . pow method.
8. Declare a method squareArea that computes the area of a square of a given side
length.
9. Consider this method:
public static int mystery (int x, int y)
{
double result = (x + y) / (y - x) ;
return result;
}
What is the result of the call myste ry (2 , 3) ?
Practice It
Now you can try these exercises at the end of the chapter: R5.1, R5.2, P5.5, P5.22.
5.B Parameter Passing 207
Method Comments
Whenever you write a method, you should comment its behavior. Comments are for human
readers, not compilers. The Java language provides a standard layout for method comments,
called the javadoc convention, as shown here:
/**
Computes the volume of a cube.
@param sideLength the side length of the cube
©return the volume
V
public static double cubeVolume(double sideLength)
{
double volume = sideLength * sideLength * sideLength;
return volume;
}
Method comments
explain the purpose
of the method, the
meaning of the
parameter variables
and return value, as
well as any special
requirements.
Comments are enclosed in /** and */ delimiters. The first line of the comment describes the
purpose of the method. Each ©param clause describes a parameter variable and the ©return
clause describes the return value.
Note that the method comment does not document the implementation ( how the method
carries out its work) but rather the design ( what the method does). The comment allows other
programmers to use the method as a “black box”.
5.3 Parameter Passing
Parameter variables
hold the arguments
supplied in the
method call.
In this section, we examine the mechanism of parameter passing more closely. When
a method is called, variables are created for receiving the method’s arguments. These
variables are called parameter variables. (Another commonly used term is formal
parameters.) The values that are supplied to the method when it is called are the
arguments of the call. (These values are also commonly called the actual param¬
eters.) Each parameter variable is initialized with the corresponding argument.
Consider the method call illustrated in Figure 3:
double resultl = cubeVolume(2) ;
A recipe for a fruit pie may say to use any kind of fruit.
Here, “fruit" is an example of a parameter variable.
Apples and cherries are examples of arguments.
pie(fruit)
208 Chapter 5 Methods
T*
Parameter Passing
(jpl Method call
double resultl = cubeVol ume(2) ;
resultl =
sideLength =
@ Initializing method parameter variable
resultl =
double resultl = cubeVol ume(2) ;
sideLength =
2
About to return to the caller
resultl =
sideLenath =
1
double volume = sideLength * sideLength * sideLength;
return volume;
volume =
8
After method call
resultl =
8
double resultl = cubeVol ume(2) ;
Figure 3 Parameter Passing
• The parameter variable sideLength of the cubeVol ume method is created when the
method is called. Q
• The parameter variable is initialized with the value of the argument that was
passed in the call. In our case, sideLength is set to 2. Q
• The method computes the expression sideLength * sideLength * sideLength, which
has the value 8. That value is stored in the variable vol ume. Q
• The method returns. All of its variables are removed. The return value is trans¬
ferred to the caller, that is, the method calling the cubeVol ume method. The caller
puts the return value in the resultl variable. Q
Now consider what happens in a subsequent call, cubeVolume(lO). A new parameter
variable is created. (Recall that the previous parameter variable was removed when
the first call to cubeVolume returned.) It is initialized with 10, and the process repeats.
After the second method call is complete, its variables are again removed.
1 0. What does this program print? Use a diagram like Figure 3 to find the answer,
public static double mystery(i nt x, int y)
{
double z = x + y;
z = z / 2.0;
return z;
}
public static void main(String[] args)
{
int a = 5;
int b = 7;
5.B Parameter Passing 209
System . out . pri ntl n (mystery (a , b) ) ;
}
1 1 . What does this program print? Use a diagram like Figure 3 to find the answer,
public static int mystery (int x)
{
int y = x * x;
return y;
}
public static void main(String[] args)
{
int a = 4;
System. out. println(mystery(a + 1));
}
1 2. What does this program print? Use a diagram like Figure 3 to find the answer,
public static int mystery (int n)
{
n++;
n++;
return n;
}
public static void main(String[] args)
{
int a = 5;
System . out . pri ntl n (mystery (a)) ;
}
Practice It Now you can try these exercises at the end of the chapter: R5.5, R5.14, P5.8.
Do Not Modify Parameter Variables
In Java, a parameter variable is just like any other variable. You can modify the values of the
parameter variables in the body of a method. For example,
public static int totalCents(i nt dollars, int cents)
{
cents = dollars * 100 + cents; // Modifies parameter variable
return cents;
}
However, many programmers find this practice confusing (see Common Error 5.1). To avoid
the confusion, simply introduce a separate variable:
public static int totalCents(i nt dollars, int cents)
{
int result = dollars * 100 + cents;
return result;
}
Common Error 5.1
- f\
Trying to Modify Arguments
The following method contains a common error: trying to modify an argument.
public static int addTax(double price, double rate)
{
double tax = price * rate / 100;
price = price + tax; // Has no effect outside the method
210 Chapter 5 Methods
return tax;
}
Now consider this call:
double total = 10;
addTax(total , 7.5); // Does not modify total
When the addTax method is called, price is set to 10. Then price is changed to 10.75. When the
method returns, all of its parameter variables are removed. Any values that have been assigned
to them are simply forgotten. Note that total is not changed. In Java, a method can never
change the contents of a variable that was passed as an argument.
5.4 Return Values
The return statement
terminates a method
call and yields the
method result.
You use the return statement to specify the result of a method. In the preceding exam¬
ples, each return statement returned a variable. However, the return statement can
return the value of any expression. Instead of saving the return value in a variable and
returning the variable, it is often possible to eliminate the variable and return a more
complex expression:
public static double cubeVolumefdouble sideLength)
{
return sideLength * sideLength * sideLength;
}
When the return statement is processed, the method exits immediately. Some
programmers find this behavior convenient for handling exceptional cases at the
beginning of the method:
public static double cubeVolumefdouble sideLength)
{
if (sideLength < 0) { return 0; }
// Handle the regular case
}
If the method is called with a negative value for sideLength, then the method returns 0
and the remainder of the method is not executed. (See Figure 4.)
True
sideLength<0? return 0
False
volume =
si deLength x
si deLength x
si deLength
return volume
Figure 4 A return Statement Exits a Method Immediately
5.4 Return Values 211
ONLINE EXAMPLE
© A program showing a
method with multiple
return statements.
Every branch of a method needs to return a value. Consider the following incor¬
rect method:
public static double cubeVolume(double sideLength)
{
if (sideLength >= 0)
{
return sideLength * sideLength * sideLength;
} // Error— no return value if sideLength < 0
}
The compiler reports this as an error. A correct implementation is:
public static double cubeVolume(double sideLength)
{
if (sideLength >= 0)
{
return sideLength * sideLength * sideLength;
}
el se
{
return 0;
}
}
Many programmers dislike the use of multiple return statements in a method. You
can avoid multiple returns by storing the method result in a variable that you return
in the last statement of the method. For example:
public static double cubeVolume(double sideLength)
{
double volume;
if (sideLength >= 0)
{
volume = sideLength * sideLength * sideLength;
}
el se
{
volume = 0;
}
return volume;
}
1 3. Suppose we change the body of the cubeVol ume method to
if (sideLength <= 0) { return 0; }
return sideLength * sideLength * sideLength;
How does this method differ from the one described in this section?
14. What does this method do?
public static boolean mystery (int n)
{
if (n % 2 == 0) { return true };
else { return false; }
}
1 5. Implement the mystery method of Self Check 14 with a single return statement.
Practice It
Now you can try these exercises at the end of the chapter: R5.13, P5.20.
212 Chapter 5 Methods
Missing Return Value
It is a compile-time error if some branches of a method return a value and others do not. Con¬
sider this example:
public static int signCdouble number)
{
if (number < 0) { return -1; }
if (number > 0) { return 1; }
// Error: missing return value if number equals 0
}
This method computes the sign of a number: -1 for negative numbers and +1 for positive num¬
bers. If the argument is zero, however, no value is returned. The remedy is to add a statement
return 0; to the end of the method.
HOW TO 5. 1
Implementing a Method
A method is a computation that can be used multiple
times with different arguments, either in the same pro¬
gram or in different programs. Whenever a computa¬
tion is needed more than once, turn it into a method.
To illustrate this process, suppose that you are help¬
ing archaeologists who research Egyptian pyramids.
You have taken on the task of writing a method that
determines the volume of a pyramid, given its height
and base length.
Step 1 Describe what the method should do.
Provide a simple English description, such as “Compute the volume of a pyramid whose base
is a square.”
Step 2 Determine the method’s “inputs”.
Make a list of all the parameters that can vary. It is common for begin- Tum com pUtati0ns
ners to implement methods that are overly specific. For example, you that can be reused
may know that the great pyramid of Giza, the largest of the Egyptian into methods,
pyramids, has a height of 146 meters and a base length of 230 meters.
You should not use these numbers in your calculation, even if the original problem only asked
about the great pyramid. It is just as easy— and far more useful— to write a method that com¬
putes the volume of any pyramid.
In our case, the parameters are the pyramid’s height and base length. At this point, we have
enough information to document the method:
/**
Computes the volume of a pyramid whose base is a square.
@param height the height of the pyramid
@param baseLength the length of one side of the pyramid’s base
©return the volume of the pyramid
5.4 Return Values 213
Step 3 Determine the types of the parameter variables and the return value.
The height and base length can both be floating-point numbers. Therefore, we will choose the
type double for both parameter variables. The computed volume is also a floating-point num¬
ber, yielding a return type of doubl e. Therefore, the method will be declared as
public static double pyramidVolume(double height, double baseLength)
Step 4 Write pseudocode for obtaining the desired result.
In most cases, a method needs to carry out several steps to find the desired answer. You may
need to use mathematical formulas, branches, or loops. Express your method in pseudocode.
An Internet search yields the fact that the volume of a pyramid is computed as
volume = 1/3 x height x base area
Because the base is a square, we have
base area * base length x base length
Using these two equations, we can compute the volume from the arguments.
Step 5 Implement the method body.
In our example, the method body is quite simple. Note the use of the return statement to
return the result.
public static double pyramidVolume(double height, double baseLength)
{
double baseArea = baseLength * baseLength;
return height * baseArea / 3;
I
Step 6 Test your method.
ONLINE EXAMPLE
© The program for
calculating a
pyramid’s volume.
After implementing a method, you should test it in isolation. Such a test is called a unit test.
Work out test cases by hand, and make sure that the method produces the correct results.
For example, for a pyramid with height 9 and base length 10, we expect the area to be 1/3 x 9 x
100 = 300. If the height is 0, we expect an area of 0.
public static void main(String[] args)
{
System. out. printlnC'Volume: " + pyramidVolume(9, 10));
System. out. println("Expected: 300") ;
System. out. printlnC'Volume: " + pyramidVolumefO, 10));
System. out. println("Expected: 0") ;
I
The output confirms that the method worked as expected:
Volume: 300
Expected: 300
Volume: 0
Expected: 0
WORKED EXAMPLE 5.1
Generating Random Passwords
This Worked Example creates a method that generates
passwords of a given length with at least one digit and
one special character.
Enter your current password: £
Enter your new password: £
Retype your new password: £
© Available online in WileyPLUS and at www.wiley.com/college/horstmann.
214 Chapter 5 Methods
5.5 Methods Without Return Values
Use a return type of
voi d to indicate that a
method does not
return a value.
Sometimes, you need to carry out a
sequence of instructions that does
not yield a value. If that instruction
sequence occurs multiple times, you
will want to package it into a method.
In Java, you use the return type void to
indicate the absence of a return value.
Here is a typical example: Your task
is to print a string in a box, like this:
IHello!
A voi d method returns no value, but it can
produce output.
However, different strings can be substituted for Hello. A method for this task can be
declared as follows:
public static void boxStri ng(String contents)
Now you develop the body of the method in the usual way, by formulating a general
method for solving the task.
Print a line that contains the - character n * l times, where n is the length of the string.
Print a line containing the contents, surrounded with a ! to the left and right.
Print another line containing the - character n * l times.
Here is the method implementation:
/**
Prints a string in a box.
@param contents the string to enclose in a box
V
public static void boxStri ng(String contents)
{
int n = contents. length() ;
for (int i = 0; i < n + 2; i++) { System. out. print("-"); }
System . out . pri ntl n () ;
System. out. println("!" + contents + "!");
for (int i = 0; i < n + 2; i++) { System. out. print("-"); }
System . out . pri ntl n () ;
}
ONLINE EXAMPLE
© A complete program
demonstrating the
boxString method.
Note that this method doesn’t compute any value. It performs some actions and then
returns to the caller.
Because there is no return value, you cannot use boxString in an expression. You
can call
boxStri ng ("Hell o") ;
but not
result = boxStringC'Hello") ; // Error: boxStri ng doesn’t return a result.
If you want to return from a void method before reaching the end, you use a return
statement without a value. For example,
public static void boxStri ng(String contents)
{
5.6 Problem Solving: Reusable Methods 215
int n = contents. length() ;
if (n == 0)
{
return; // Return immediately
}
}
1 6. How do you generate the following printout, using the boxSt ring method ?
IHello!
IWorld!
1 7. What is wrong with the following statement?
System. out . pri nt (boxSt ri ng ("Hell o")) ;
1 8. Implement a method shout that prints a line consisting of a string followed by
three exclamation marks. For example, shout ("Hell o") should print Hello! !! . The
method should not return a value.
1 9. How would you modify the boxSt ri ng method to leave a space around the string
that is being boxed, like this:
! Hello !
20. The boxSt ri ng method contains the code for printing a line of - characters twice.
Place that code into a separate method pri ntLi ne, and use that method to simplify
boxString. What is the code of both methods?
Practice It Now you can try these exercises at the end of the chapter: R5.4, P5.25.
5.6 Problem Solving: Reusable Methods
...... . , You have used many methods from the standard Java library. These methods have
code or pseudocode been provided as a part of the Java platform so that programmers need not recre-
by defining a method. ate them. Of course, the Java library doesn’t cover every conceivable need. You will
often be able to save yourself time by designing your own methods that can be used
for multiple problems.
When you write nearly identical code or pseudocode multiple times, either in the
same program or in separate programs, consider introducing a method. Here is a typ¬
ical example of code replication:
int hours;
do
{
System. out. print("Enter a value between 0 and 23: ");
hours = in.nextlntO;
}
while (hours < 0 || hours > 23);
216 Chapter 5 Methods
Design your methods
to be reusable.
Supply parameter
variables for the
values that can vary
when the method
is reused.
int minutes;
do
{
System. out. print("Enter a value between 0 and 59: ");
minutes = in.nextlnt();
}
while (minutes < 0 || minutes > 59);
This program segment reads two variables, making sure that each of them is within a
certain range. It is easy to extract the common behavior into a method:
/**
Prompts a user to enter a value up to a given maximum until the user
provides a valid input.
©param high the largest allowable input
©return the value provided by the user (between 0 and high, inclusive)
V
public static int readIntUpTo(int high)
{
int input;
Scanner in = new Scanner(System.in) ;
do
{
System. out. print("Enter a value between 0 and " + high + ": ");
input = in.nextlntO ;
}
while (input < 0 || input > high);
return input;
}
Then use this method twice:
int hours = readIntUpTo(23) ;
int minutes = readIntllpTo(59) ;
We have now removed the replication of the loop — it only occurs once, inside the
method.
Note that the method can be reused in other programs that need to read integer
values. However, we should consider the possibility that the smallest value need not
always be zero.
Here is a better alternative:
/**
Prompts a user to enter a value within a given range until the user
provides a valid input.
©param low the smallest allowable input
©param high the largest allowable input
©return the value provided by the user (between low and high, inclusive)
V
public static int readIntBetween(int low, int high)
{
int input;
Scanner in = new Scanner(System.in) ;
do
{
System. out. print("Enter a value between " + low + " and " + high + ": ");
input = in.nextlntO I
}
while (input < low || input > high);
return input;
}
5.6 Problem Solving: Reusable Methods
217
When carrying oat the same task
multiple times, use a method.
ONLINE EXAMPLE
© A complete program
demonstrating the
readlntBetween
method.
In our program, we call
int hours = readlntBetween (0, 23);
Another program can call
int month = readlntBetween (1, 12);
In general, you will want to provide parameter variables for the values that vary when
a method is reused.
2 1 . Consider the following statements:
int totaiPennies = (int) Math. round (100 * total) % 100;
int taxPennies = (int) Math. round(100 * (total * taxRate)) % 100;
Introduce a method to reduce code duplication.
22. Consider this method that prints a page number on the left or right side of a
page:
if (page % 2 == 0) { System. out. println(page) ; }
else { System. out. println(" " + page); }
Introduce a method with return type bool ean to make the condition in the i f
statement easier to understand.
23. Consider the following method that computes compound interest for an
account with an initial balance of $10,000 and an interest rate of 5 percent:
public static double balance(int years) { return 10000 * Math.pow(1.05, years); }
How can you make this method more reusable?
24. The comment explains what the following loop does. Use a method instead.
// Counts the number of spaces
int spaces = 0;
for (int i = 0; i < input. length() ; i++)
{
if (input. charAt(i) == ' ') { spaces++; }
}
25. In Self Check 24, you were asked to implement a method that counts spaces.
How can you generalize it so that it can count any character? Why would you
want to do this?
Practice It Now you can try these exercises at the end of the chapter: R5.7, P5.21.
218 Chapter 5 Methods
5.7 Problem Solving: Stepwise Refinement
Use the process of
stepwise refinement
to decompose
complex tasks into
simpler ones.
One of the most powerful strategies for
problem solving is the process of stepwise
refinement. To solve a difficult task, break
it down into simpler tasks. Then keep break¬
ing down the simpler tasks into even simpler
ones, until you are left with tasks that you
know how to solve.
Now apply this process to a problem of
everyday life. You get up in the morning and
simply must get coffee. How do you get cof¬
fee? You see whether you can get someone
else, such as your mother or mate, to bring
you some. If that fails, you must make coffee.
A production process is broken down
into sequences of assembly steps.
Get
coffee
Yes Can you No
ask someone
Make
coffee
Ask for
coffee
Yes
Do you
have instant
No
coffee?
Make
Brew
instant
coffee
coffee
Figure 5
Flowchart of
Coffee-Making
Solution
Yes , D°y°u No
nave a micro-
wave?
Fill cup
with water
Put cup
in micro-
wave
Heat
3 min.
Fill kettle
with water
Bring to
a boil
Boil
water
Mix water
and instant
coffee
Add water
to coffee
maker
Add coffee
beans to
grinder
Grind
60 sec.
Add coffee
beans to
filter
Add filter
to coffee
maker
Grind
coffee
beans
Turn coffee
maker on
5.7 Problem Solving: Stepwise Refinement 219
When you discover
that you need a
method, write a
description of the
parameter variables
and return values.
A method may
require simpler
methods to carry
out its work.
How do you make coffee? If there is instant coffee available, you can make instant coffee.
How do you make instant coffee? Simply boil water and mix the boiling water with the
instant coffee. How do you boil water? If there is a microwave, then you fill a cup
with water, place it in the microwave and heat it for three minutes. Otherwise, you fill
a kettle with water and heat it on the stove until the water comes to a boil. On the
other hand, if you don’t have instant coffee, you must brew coffee. How do you brew
coffee? You add water to the coffee maker, put in a filter, grind coffee, put the coffee in
the filter, and turn the coffee maker on. How do you grind coffee? You add coffee
beans to the coffee grinder and push the button for 60 seconds.
Figure 5 shows a flowchart view of the coffee-making solution. Refinements are
shown as expanding boxes. In Java, you implement a refinement as a method. For
example, a method brewCoffee would call grindCoffee, and brewCoffee would be called
from a method makeCoffee.
Let us apply the process of stepwise refine¬
ment to a programming problem. When print¬
ing a check, it is customary to write the check
amount both as a number (“$274.15”) and as a
text string (“two hundred seventy four dollars
and 15 cents”). Doing so reduces the recipient’s
temptation to add a few digits in front of the
amount.
For a human, this isn’t particularly difficult,
but how can a computer do this? There is no
built-in method that turns 274 into "two hundred seventy four". We need to program
this method. Here is the description of the method we want to write:
/**
Turns a number into its English name.
©param number a positive integer < 1,000
©return the name of number (e.g., “two hundred seventy four”)
V
public static String intName(int number)
How can this method do its j ob ? Consider a simple case first. If the number is between
1 and 9, we need to compute "one" ... "nine". In fact, we need the same computation
again for the hundreds (two hundred). Any time you need something more than once, it
is a good idea to turn that into a method. Rather than writing the entire method, write
only the comment:
/**
Turns a digit into its English name.
©param digit an integer between 1 and 9
©return the name of digit (“one” . . . “nine”)
*/
public static String digitName(int digit)
Numbers between 10 and 19 are special cases. Let’s have a separate method teenName
that converts them into strings "eleven", "twelve", "thi rteen", and so on:
/**
Turns a number between 10 and 19 into its English name.
©param number an integer between 10 and 19
©return the name of the number (“ten” . . . “nineteen”)
*/
public static String teenName(int number)
220 Chapter 5 Methods
Next, suppose that the number is between 20 and 99. The name of such a number has
two parts, such as "seventy four". We need a way of producing the first part, "twenty",
"thi rty", and so on. Again, we will put that computation into a separate method:
/**
Gives the name of the tens part of a number between 20 and 99.
©param number an integer between 20 and 99
©return the name of the tens part of the number (“twenty” . . . “ninety”)
V
public static String tensName(int number)
Now let us write the pseudocode for the intName method. If the number is between
100 and 999, then we show a digit and the word "hundred" (such as "two hundred").
We then remove the hundreds, for example reducing 274 to 74. Next, suppose the
remaining part is at least 20 and at most 99. If the number is evenly divisible by 10,
we use tensName, and we are done. Otherwise, we print the tens with tensName (such as
"seventy") and remove the tens, reducing 74 to 4. In a separate branch, we deal with
numbers that are at between 10 and 19. Finally, we print any remaining single digit
(such as "four").
part * number (The part that still needs to be converted)
name * "" (The name of the number)
If part >* 1 00
name * name of hundreds in part + " hundred"
Remove hundreds from part.
If part >= 20
Append tensName(part) to name.
Remove tens from part.
Else if part >= 1 0
Append teenName(part) to name,
part * 0
If (part > 0)
Append digitblame(part) to name.
iff
#EE
Tracing a Method
Translating the pseudocode into Java is straightforward. The result is shown in the
source listing at the end of this section.
Note how we rely on helper methods to do much of the detail work. Using the
process of stepwise refinement, we now need to consider these helper methods.
Let’s start with the digitName method. This method is so simple to implement that
pseudocode is not really required. Simply use an if statement with nine branches:
public static String digitName(int digit)
{
if (digit == 1) { return "one" };
if (digit == 2) { return "two" };
}
The teenName and tensName methods are similar.
5.7 Problem Solving: Stepwise Refinement 221
This concludes the process of stepwise refinement. Here is the complete program:
section_7/liitegerNameJava
1 import java. util .Scanner;
2
3 /**
4 This program turns an integer into its English name.
5 */
6 public class IntegerName
7 {
8 public static void main(String[] args)
9 {
10 Scanner in = new Scanner(System.in) ;
11 System. out. print("Please enter a positive integer < 1000: ");
12 int input = in.nextlntO ;
1 3 System. out . println(i ntName (input)) ;
14 }
15
1 6 /**
1 7 Turns a number into its English name.
18 ©param number a positive integer < 1,000
1 9 ©return the name of the number (e.g. “two hundred seventy four”)
20 */
21 public static String intName(int number)
22 {
23 int part = number; // The part that still needs to be converted
24 String name = ; // The name of the number
25
26 if (part >= 100)
27 {
28 name = digitName(part / 100) + hundred”;
29 part = part % 100;
30 }
31
32 if (part >= 20)
33 {
34 name = name + + tensName(part) ;
35 part = part % 10;
36 }
37 else if (part >= 10)
38 {
39 name = name + + teenName(part) ;
40 part = 0;
41 }
42
43 if (part > 0)
44 {
45 name = name + + digitName(part) ;
46 }
47
48 return name;
49 }
50
51 /**
52 Turns a digit into its English name.
53 ©param digit an integer between 1 and 9
54 ©return the name of digit (“one” . . . “nine”)
55 V
222 Chapter 5 Methods
56 public static String digitName(int digit)
57 {
58
if
(digit ==
1)
{
return
"one"; }
59
if
(digit ==
2)
{
return
"two"; }
60
if
(digit ==
3)
{
return
"three"; }
61
if
(digit ==
4)
{
return
"four ; }
62
if
(digit ==
5)
{
return
"five ; }
63
if
(digit ==
6)
{
return
"six"; }
64
if
(digit ==
7)
{
return
"seven"; }
65
if
(digit ==
8)
{
return
"eight"; }
66
if
(digit ==
9)
{
return
"nine ; }
67
return
68 }
69
70 /**
71 Turns a number between 10 and 19 into its English name.
@param number an integer between 10 and 19
©return the name of the given number (“ten” . . . “nineteen”)
74 V
75
public
: static
Stri ng
teenName(int number)
76
{
77
if
(number
==
10)
{
return
"ten"; }
78
if
(number
==
11)
{
return
"eleven"; }
79
if
(number
==
12)
{
return
"twelve"; }
80
if
(number
==
13)
{
return
"thi rteen" ;
}
81
if
(number
==
14)
{
return
"fourteen" ;
}
82
if
(number
==
15)
{
return
"fi fteen";
}
83
if
(number
==
16)
{
return
"sixteen" ;
}
84
if
(number
==
17)
{
return
"seventeen"
; }
85
if
(number
==
18)
{
return
"eighteen" ;
}
86
if
(number
==
19)
{
return
"nineteen";
}
87
return "";
88
}
89
90 /**
91 Gives the name of the tens part of a number between 20 and 99.
92 ©param number an integer between 20 and 99
©return the name of the tens part of the number (“twenty” . . . “ninety”)
94 */
95 public static String tensName(int number)
96 {
97 if (number >= 90) { return ’ninety"; }
98 if (number >= 80) { return "eighty"; }
99 if (number >= 70) { return "seventy"; }
100 if (number >= 60) { return "sixty ; }
101 if (number >= 50) { return "fifty ; }
102 if (number >= 40) { return "forty ; }
103 if (number >= SO) { return ’thirty"; }
104 if (number >= 20) { return "twenty"; }
105 return
106 }
107 }
Program Run
Please enter a positive integer < 1000: 729
seven hundred twenty nine
5.7 Problem Solving: Stepwise Refinement 223
30.
Explain how you can improve the i ntName method so that it can handle argu¬
ments up to 9999.
Why does line 40 set part = 0?
What happens when you call i ntName (0) ? How can you change the i ntName
method to handle this case correctly?
Trace the method call i ntName (72), as described in Programming Tip 5.4.
Use the process of stepwise refinement to break down the task of printing the
following table into simpler tasks.
+ - + - +
i 1 i
4 i * i 1
l 1
l 1
2 1
8 1
20 1
8000 1
+ - + - +
Practice It Now you can try these exercises at the end of the chapter: R5.12, P5.1 1, P5.24.
Keep Methods Short
There is a certain cost for writing a method. You need to design, code, and test the method.
The method needs to be documented. You need to spend some effort to make the method
reusable rather than tied to a specific context. To avoid this cost, it is always tempting just to
stuff more and more code in one place rather than going through the trouble of breaking up
the code into separate methods. It is quite common to see inexperienced programmers pro¬
duce methods that are several hundred lines long.
As a rule of thumb, a method that is so long that its code will not fit on a single screen in
your development environment should probably be broken up.
Programming Tip 5.4
4
Tracing Methods
When you design a complex method, it is a good idea to carry out a manual walkthrough
before entrusting your program to the computer.
Take an index card, or some other piece of paper, and write down the method call that you
want to study. Write the name of the method and the names and values of the parameter vari¬
ables, like this:
Then write the names and initial values of the method variables. Write them in a table, because
you will update them as you walk through the code.
224
Chapter 5 Methods
We enter the test part >= 100. part / 100 is 4 and part % 100 is 16. digitName(4) is easily seen to
be "four". (Had digitName been complicated, you would have started another sheet of paper to
figure out that method call. It is quite common to accumulate several sheets in this way.)
Now name has changed to name + " " + digitName(part / 100) + " hundred", that is "four hun¬
dred", and part has changed to part % 100, or 16.
Now you enter the branch part >= 10. teenName(16) is sixteen, so the variables now have the
values
Now it becomes clear why you need to set part to 0 in line 40. Otherwise, you would enter the
next branch and the result would be "four hundred sixteen six". Tracing the code is an effective
way to understand the subtle aspects of a method.
Stubs
When writing a larger program, it is not always
feasible to implement and test all methods at once.
You often need to test a method that calls another,
but the other method hasn’t yet been imple¬
mented. Then you can temporarily replace the
missing method with a stub. A stub is a method
that returns a simple value that is sufficient for
testing another method. Here are examples of
stub methods:
/**
Turns a digit into its English name.
@param digit an integer between 1 and 9
©return the name of digit (“one” . . . nine”)
V
public static String digitName(int digit)
{
return "mumble";
}
Stubs are incomplete methods that can
be used for testing.
Gives the name of the tens part of a number between 20 and 99.
©param number an integer between 20 and 99
©return the tens name of the number (“twenty” . . . “ninety”)
5.8 Variable Scope 225
V
public static String tensName(int number)
{
return "mumblety";
}
If you combine these stubs with the intName method and test it with an argument of 274, you
will get a result of "mumble hundred mumblety mumble", which indicates that the basic logic of the
i ntName method is working correctly.
WORKED EXAMPLE 5.2
Calculating a Course Grade
This Worked Example uses stepwise refinement to solve the
problem of converting a set of letter grades into an average
grade for a course.
5.8 Variable Scope
As your programs get larger and contain more variables, you may encounter prob¬
lems where you cannot access a variable that is defined in a different part of your pro¬
gram, or where two variable definitions conflict with each other. In order to resolve
these problems, you need to be familiar with the concept of variable scope.
The scope of a variable is the part of the program in which you can access it. For
example, the scope of a method’s parameter variable is the entire method. In the fol¬
lowing code segment, the scope of the parameter variable sideLength is the entire
cubeVol ume method but not the mai n method.
public static void main(String[] args)
{
System. out . pri ntl n(cubeVol ume (10)) ;
}
public static double cubeVolume(double sideLength)
{
return sideLength * sideLength * sideLength;
}
A variable that is defined within a method is called a local variable. When a local
variable is declared in a block, its scope ranges from its declaration until the end of
the block. For example, in the code segment below, the scope of the square variable is
highlighted.
public static void main(String[] args)
{
int sum = 0;
for (int i =1; i <=10; i++)
{
int square = i * i ;
sum = sum + square;
}
System. out. pri ntl n (sum) ;
}
The scope of a
variable is the part of
the program in which
it is visible.
© Available online in WileyPLUS and at www.wiley.com/college/horstmann.
226 Chapter 5 Methods
The scope of a variable that is declared in a for statement extends to the end of the
statement:
public static void main(String[] args)
{
int sum = 0;
for (int i =1; i <=10; i++)
{
sum = sum + i * i ;
}
System. out. println (sum) ;
}
Here is an example of a scope problem. The following code will not compile:
public static void main(String[] args)
{
double sideLength = 10;
int result = cubeVolume() ;
System. out. println (result) ;
}
public static double cubeVolume()
{
return sideLength * sideLength * sideLength; // ERROR
}
Note the scope of the variable sideLength. The cubeVolume method attempts to read
the variable, but it cannot— the scope of sideLength does not extend outside the main
method. The remedy is to pass it as an argument, as we did in Section 5.2.
It is possible to use the same variable name more than once in a program. Consider
the resul t variables in the following example:
public static void main(String[] args)
{
int result = square(B) + square(4);
System. out. println (result) ;
}
public static int square(int n)
{
int result = n * n;
return result;
}
In the same way that there can be a street named “Main Street” in different cities, a Java program
can have multiple variables with the same name.
5.8 Variable Scope 227
Two local or
parameter variables
can have the same
name, provided that
their scopes do
not overlap.
Each result variable is declared in a separate method, and their scopes do not overlap.
You can even have two variables with the same name in the same method, provided
that their scopes do not overlap:
public static void main(String[] args)
{
int sum = 0;
for (int i =1; i <=10; i++)
{
sum = sum + i ;
}
for (int i = 1; i <= 10; i++)
{
sum = sum + i * i ;
}
System . out . pri ntl n(sum) ;
It is not legal to declare two variables with the same name in the same method in such
a way that their scopes overlap. For example, the following is not legal:
public static int sumOfSquares(i nt n)
{
int sum = 0;
for (int i =1; i <= n; i++)
{
i nt n = i * i ; // ERROR
sum = sum + n;
}
return sum;
}
The scope of the local variable n is contained within the scope of the parameter vari¬
able n. In this case, you need to rename one of the variables.
Consider this sample program:
1 public class Sample
2 {
3 public static void main(String[] args)
4 {
5 int x = 4;
6 x = mystery(x + 1) ;
System. out. println(s) ;
8 }
9
TO public static int mystery (int x)
11 {
12 int s = 0;
13 for (int i =0; i < x; x++)
14 {
15
16
i nt x = i + 1;
s = s + x;
228 Chapter 5 Methods
17 }
18 return s;
19 }
20 }
3 1 . Which lines are in the scope of the variable i declared in line 13?
32. Which lines are in the scope of the parameter variable x declared in line 10?
33. The program declares two local variables with the same name whose scopes
don’t overlap. What are they?
34. There is a scope error in the mystery method. How do you fix it?
35. There is a scope error in the mai n method. What is it, and how do you fix it?
Practice It Now you can try these exercises at the end of the chapter: R5.9, R5.10.
VIDEO EXAMPLE 5.1
Debugging
fWILEYO
rPLUS
In this Video Example, you will learn how to use a debugger to find
errors in a program.
5.9 Recursive Methods (Optional)
A recursive method is a method that calls itself. This is not as unusual as it sounds at
first. Suppose you face the arduous task of cleaning up an entire house. You may well
say to yourself, “I’ll pick a room and clean it, and then I’ll clean the other rooms.” In
other words, the cleanup task calls itself, but with a simpler input. Eventually, all the
rooms will be cleaned.
Cleaning up a house can be solved recursively:
Clean one room , then dean up the rest.
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
5.9 Recursive Methods (Optional) 229
A recursive
computation solves
a problem by using
the solution of the
same problem with
simpler inputs.
For a recursion to
terminate, there must
be special cases for
the simplest inputs.
In Java, a recursive method uses the same principle. Here is a typical example. We
want to print triangle patterns like this:
[]
[][]
[][][]
[][][][]
Specifically, our task is to provide a method
public static void printTriangle(int sideLength)
The triangle given above is printed by calling printTriangle(4). To see how recursion
helps, consider how a triangle with side length 4 can be obtained from a triangle with
side length 3.
□
[][]
[][][]
[][][][]
Print the triangle with side length 3.
Print a line with four [].
More generally, here are the Java instructions for an arbitrary side length:
public static void printTriangle(int sideLength)
{
printTriangle(sideLength - 1);
for (int i = 0; i < sideLength; i++)
{
System. out. print("[]") ;
}
System. out. println() ;
}
There is just one problem with this idea. When the side length is 1, we don’t want to
call printTriangle(O), printTriangle(-l), and so on. The solution is simply to treat this
as a special case, and not to print anything when sideLength is less than 1.
public static void printTriangle(int sideLength)
{
if (sideLength < 1) { return; }
printTriangle(sideLength - 1);
for (int i = 0; i < sideLength; i++)
{
System. out. print("[]") ;
}
System. out. println() ;
}
Look at the printTri angle method one more time and notice how utterly reasonable it
is. If the side length is 0, nothing needs to be printed. The next part is just as reason¬
able. Print the smaller triangle and don’t think about why that works. Then print a
row of [] . Clearly, the result is a triangle of the desired size.
There are two key requirements to make sure that the recursion is successful:
• Every recursive call must simplify the task in some way.
• There must be special cases to handle the simplest tasks directly.
The printin' angle method calls itself again with smaller and smaller side lengths.
Eventually the side length must reach 0, and the method stops calling itself.
230 Chapter 5 Methods
Jp
Tracing a Recursion
I \\
ONLINE EXAMPLE
O The complete
TrianglePrinter
program.
This set of Russian dolls looks similar to the
call pattern of a recursive method.
Here is what happens when we print a triangle with side length 4:
• The call printTriangle(4) calls printTriangle(3).
• The call printTriangle(3) calls printTriangle(2).
• The call printTriangle(2) calls printTriangle(l).
• The call printTriangle(l) calls printTriangle(O).
• The call pri ntT ri angl e (0) returns, doing nothing.
• The call pri ntTri angle (1) prints [].
• The call pri ntTri angl e(2) prints [] [].
• The call pri ntTri angl e(3) prints [] [] [].
• The call pri ntTri angl e(4) prints [] [] [] [].
The call pattern of a recursive method looks complicated, and the key to the success¬
ful design of a recursive method is not to think about it.
Recursion is not really necessary to print triangle shapes. You can use nested loops,
like this:
public static void printTriangle(int sideLength)
{
for (int i = 0; i < sideLength; i++)
{
for (i nt j = 0; j < i ; j++)
{
System. out. pri nt(" [] ") ;
}
System. out. println() ;
}
}
However, this pair of loops is a bit tricky. Many people find the recursive solution
simpler to understand.
36. Consider this slight modification of the pri ntT ri angl e method:
public static void printTriangle(int sideLength)
{
if (sideLength < 1) { return; }
for (int i = 0; i < sideLength; i++)
{
System. out. print("[]") ;
5.9 Recursive Methods (Optional) 231
}
System . out . pri ntl n () ;
printTriangle(sidel_ength - 1);
}
What is the result of pri ntTriangle(4) ?
37. Consider this recursive method:
public static int mystery (int n)
{
if (n <= 0) { return 0; }
return n + mystery(n - 1);
}
What is my ste ry (4) ?
38. Consider this recursive method:
public static int mystery (int n)
{
if (n <= 0) { return 0; }
return mystery(n / 2) + 1;
}
What is mystery (20)?
39. Write a recursive method for printing n box shapes [] in a row.
40. The i ntName method in Section 5.7 accepted arguments < 1,000. Using a recursive
call, extend its range to 999,999. For example an input of 12,345 should return
"twelve thousand three hundred forty five".
Practice It Now you can try these exercises at the end of the chapter: R5.16, P5.16, P5.18.
HOW TO 5.2
Thinking Recursively
To solve a problem recursively requires a different mindset than to solve it by programming
loops. In fact, it helps if you are, or pretend to be, a bit lazy and let others do most of the work
for you. If you need to solve a complex problem, pretend that “someone else” will do most
of the heavy lifting and solve the problem for all simpler inputs. Then you only need to figure
out how you can turn the solutions with simpler inputs into a solution for the whole problem.
To illustrate the recursive thinking process, consider the problem of Section 4.2, computing
the sum of the digits of a number. We want to design a method di gi tSum that computes the sum
of the digits of an integer n.
For example, digitSum(1729) = 1 + 7 + 2 + 9 = 19
Step 1 Break the input into parts that can themselves be inputs to the problem.
In your mind, focus on a particular input or set of inputs for the task
that you want to solve, and think how you can simplify the inputs.
Look for simplifications that can be solved by the same task, and
whose solutions are related to the original task.
In the digit sum problem, consider how we can simplify an
input such as n = 1729. Would it help to subtract 1? After all,
digitSum(1729) = digitSum(1728) + 1. But consider n = 1000. There seems to be no obvious rela¬
tionship between digit Sum (1000) and di gi tSum(999).
A much more promising idea is to remove the last digit, that is, to compute n / 10 = 172. The
digit sum of 172 is directly related to the digit sum of 1729.
The key to finding a
recursive solution is
reducing the input to
a simpler input for
the same problem.
232 Chapter 5 Methods
Step 2 Combine solutions with simpler inputs into a solution of the original problem.
In your mind, consider the solutions for the simpler inputs that you have discovered in Step 1.
Don’t worry how those solutions are obtained. Simply have faith that the solutions are readily
available. Just say to yourself: These are simpler inputs, so someone else will solve the problem
for me.
In the case of the digit sum task, ask yourself how you can obtain
digitSum(1729) if you know digitSum(172). You simply add the last
digit (9) and you are done. How do you get the last digit? As the
remainder n % 10. The value digitSum(n) can therefore be obtained as
digitSum(n / 10) + n % 10
Don’t worry how digitSum(n / 10) is computed. The input is smaller,
and therefore it works.
Step 3 Find solutions to the simplest inputs.
A recursive computation keeps simplifying its inputs. To make sure that the recursion comes
to a stop, you must deal with the simplest inputs separately. Come up with special solutions
for them. That is usually very easy.
Look at the simplest inputs for the di gi tSum problem:
• A number with a single digit
• 0
When designing a
recursive solution,
do not worry about
multiple nested calls.
Simply focus on
reducing a problem
to a slightly
simpler one.
Random Fact 5.1 The Explosive Growth of Personal Computers
1 In 1971, Marcian E.
^ “Ted” Hoff, an engineer
at Intel Corporation,
was working on a chip for a manufac¬
turer of electronic calculators. He real¬
ized that it would be a better idea to
develop a general-purpose chip that
could be programmed to interface with
the keys and display of a calculator,
rather than to do yet another custom
design. Thus, the microprocessor was
born. At the time, its primary applica¬
tion was as a controller for calculators,
washing machines, and the like. It took
years for the computer industry to
notice that a genuine central process¬
ing unit was now available as a single
chip.
Hobbyists were the first to catch
on. In 1974 the first computer kit, the
Altair 8800, was available from MITS
Electronics for about $350. The kit
consisted of the microprocessor, a cir¬
cuit board, a very small amount of
memory, toggle switches, and a row of
display lights. Purchasers had to sol-
derand assemble it, then program it in
machine language through the toggle
switches. It was not a big hit.
The first big hit was the Apple II. It
was a real computer with a keyboard,
a monitor, and a floppy disk drive.
When it was first released, users had a
$3,000 machine that could play Space
Invaders, run a primitive bookkeep¬
ing program, or let users program it
in BASIC. The original Apple II did not
even support lowercase letters, mak¬
ing it worthless for word processing.
The breakthrough came in 1979 with
a new spreadsheet program, VisiCalc.
In a spreadsheet, you enter financial
data and their relationships into a grid
of rows and columns (see the figure at
right). Then you modify some of the
data and watch in real time how the
others change. For example, you can
see how changing the mix of widgets
in a manufacturing plant might affect
estimated costs and profits. Middle
managers in companies, who under¬
stood computers and were fed up with
having to wait for hours or days to get
their data runs back from the comput¬
ing center, snapped up VisiCalc and the
computer that was needed to run it.
For them, the computer was a spread¬
sheet machine.
The next big hit was the IBM Per¬
sonal Computer, ever after known as
the PC. It was the first widely available
personal computer that used Intel’s
16-bit processor, the 8086, whose
successors are still being used in per¬
sonal computers today. The success
of the PC was based not on any engi¬
neering breakthroughs but on the fact
that it was easy to clone. IBM published
the computer’s specifications in order
to encourage third parties to develop
plug-in cards. Perhaps IBM did not
foresee that functionally equivalent
versions of their computer could be
recreated by others, but a variety of
PC clone vendors emerged, and ulti¬
mately IBM stopped selling personal
computers.
IBM never produced an operating
system for its PCs — that is, the soft¬
ware that organizes the interaction
between the user and the computer,
starts application programs, and man¬
ages disk storage and other resources.
Instead, IBM offered customers the
option of three separate operating
systems. Most customers couldn’t
care less about the operating system.
5.9 Recursive Methods (Optional) 233
Step 4
ONLINE EXAMPLE
A program
illustrating the
digitSum method.
A number with a single digit is its own digit sum, so you can stop the recursion when n < 10,
and return n in that case. Or, you can be even lazier. If n has a single digit, then di gi tSum(n / 10)
+ n % 10 equals di gi tSum(O) + n. You can simply terminate the recursion when n is zero.
Implement the solution by combining the simple cases and the reduction step.
Now you are ready to implement the solution. Make separate cases for the simple inputs that
you considered in Step 3. If the input isn’t one of the simplest cases, then implement the logic
you discovered in Step 2.
Here is the complete di gi tSum method:
public static int digitSum(int n)
{
if (n == 0) { return 0; } // Special case for terminating the recursion
return digitSum(n / 10) + n % 10; // General case
}
VIDEO EXAMPLE 5.2
Fully Justified Text
AwiLEY©
rPLUS
In printed books (such as this one), all but the last line of a
paragraph have the same length. In this Video Example,
you will see how to achieve this effect.
They chose the system that was able
to launch most of the few applications
that existed at the time. It happened
to be DOS (Disk Operating System) by
Microsoft. Microsoft licensed the same
operating system to other hardware
vendors and encouraged software
companies to write DOS applications.
A huge number of useful application
programs for PC-compatible machines
was the result.
PC applications were certainly use¬
ful, but they were not easy to learn.
Every vendor developed a different
user interface: the collection of key¬
strokes, menu options, and settings
that a user needed to master to use
a software package effectively. Data
exchange between applications was
difficult, because each program used a
different data format. The Apple Mac¬
intosh changed all that in 1984. The
designers of the Macintosh had the
vision to supply an intuitive user inter¬
face with the computer and to force
software developers to adhere to it.
It took Microsoft and PC-compatible
manufacturers years to catch up.
Most personal computers are used
for accessing information from online
sources, entertainment, word process¬
ing, and home finance. Some analysts
predict that the personal computer will
merge with the television set and cable
network into an entertainment and
information appliance.
a VISICALC Screen:
U*«Y»y »n9. c«to.
Ctoiww f «ii» « coea<*AM«t
The Visicalc Spreadsheet Running on an Apple II
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
234 Chapter 5 Methods
CHAPTER SUMMARY
Understand the concepts of methods, arguments, and return values.
• A method is a named sequence of instructions.
• Arguments are supplied when a method is called.
• The return value is the result that the method computes
Be able to implement methods.
• When declaring a method, you provide a name for the method, a variable for each
argument, and a type for the result.
• Method comments explain the purpose of the method, the meaning of the param¬
eter variables and return value, as well as any special requirements.
Describe the process of parameter passing.
• Parameter variables hold the arguments
supplied in the method call.
Describe the process of returning a value from a method.
• The return statement terminates a method call and yields the
method result.
• Turn computations that can be reused into methods.
Design and implement methods without return values.
• Use a return type of voi d to indicate that a method does not return a value.
Develop methods that can be reused for multiple problems.
• Eliminate replicated code or pseudocode by defining a method.
• Design your methods to be reusable. Supply parameter variables for the values
that can vary when the method is reused.
Apply the design principle of stepwise refinement.
• Use the process of stepwise refinement to decompose complex tasks into
simpler ones.
• When you discover that you need a method, write a description of the parameter
variables and return values.
• A method may require simpler methods to carry out its work.
Review Exercises 235
Determine the scope of variables in a program.
• The scope of a variable is the part of the program in which it is
visible.
• Two local or parameter variables can have the same name,
provided that their scopes do not overlap.
Understand recursive method calls and implement simple recursive methods.
A recursive computation solves a problem by using the solution of the same
problem with simpler inputs.
For a recursion to terminate, there must be special cases for the simplest inputs.
The key to finding a recursive solution is reducing the input to a simpler input for
the same problem.
When designing a recursive solution, do not worry about multiple nested calls.
Simply focus on reducing a problem to a slightly simpler one.
REVIEW EXERCISES
■ R5.1 In which sequence are the lines of the Cubes, java program in Section 5.2 executed,
starting with the first line of mai n?
■ R5.2 Write method headers for methods with the following descriptions.
a. Computing the larger of two integers
b. Computing the smallest of three floating-point numbers
c. Checking whether an integer is a prime number, returning true if it is and
false otherwise
d. Checking whether a string is contained inside another string
e. Computing the balance of an account with a given initial balance, an annual
interest rate, and a number of years of earning interest
f . Printing the balance of an account with a given initial balance and an annual
interest rate over a given number of years
g. Printing the calendar for a given month and year
h. Computing the weekday for a given day, month, and year (as a string such
as "Monday")
i. Generating a random integer between 1 and n
■ R5.3 Give examples of the following methods from the Java library.
a. A method with a doubl e argument and a doubl e return value
b. A method with two double arguments and a double return value
c. A method with a Stri ng argument and a doubl e return value
d. A method with no arguments and a double return value
■ R5.4 True or false?
a. A method has exactly one return statement.
b. A method has at least one return statement.
236 Chapter 5 Methods
c. A method has at most one return value.
d. A method with return value voi d never has a return statement.
e. When executing a return statement, the method exits immediately.
f . A method with return value voi d must print a result.
g„ A method without parameter variables always returns the same value.
■ ■ R5.5 Consider these methods:
public static double f(double x) { return g(x) + Math.sqrt(h(x)); }
public static double g(double x) { return 4 * h (x) ; }
public static double h(double x) { return x * x + k(x) - 1; }
public static double k(double x) { return 2 * (x + 1) ; }
Without actually compiling and running a program, determine the results of the
following method calls.
a. double xl = f (2) ;
b. double x2 = g(h(2));
C. double x3 = k(g(2) + h (2) ) ;
d. double x4 = f(0) + f (1) + f (2) ;
e. double x5 = f(-l) + g(-l) + h (-1) + k(-l);
■ R5.6 What is the difference between an argument and a return value? How many argu¬
ments can a method call have? How many return values?
■ ■ R5.7 Design a method that prints a floating-point number as a currency value (with a $
sign and two decimal digits).
a. Indicate how the programs ch02/section_3/Volume2. java and ch04/section_3/
InvestmentTable. java should change to use your method.
b. What change is required if the programs should show a different currency, such
as euro?
■ ■ Business R5.8 Write pseudocode for a method that translates a telephone number with letters in it
(such as 1 -800-FLOWERS) into the actual phone number. Use the standard letters
on a phone pad.
QUO
QUO
nob
■ ■ R5.9 Describe the scope error in the following program and explain how to fix it.
public class Conversation
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in) ;
Review Exercises 237
}
}
System. out. print("What is your first name? ");
String input = in.next();
System. out. println("Hello, " + input);
System. out. print("How old are you? ");
int input = in.nextlnt() ;
input++;
System. out. print! n ("Next year, you will be " + input);
R5. T 0 For each of the variables in the following program, indicate the scope. Then deter¬
mine what the program prints, without actually running the program.
1
public class Sample
2
{
3
public static void main(String[]
4
{
5
int i = 10;
6
int b = g (i ) ;
7
System, out. println(b + i);
8
}
9
10
public static int f(int i)
1 1
{
12
int n = 0;
13
while (n * n <= i) { n++; }
14
return n - 1;
15
}
16
17
public static int g(int a)
18
{
19
int b = 0;
20
for (int n = 0; n < a; n++)
21
{
22
int i = f (n) ;
23
+
_Q
II
-Q
24
}
25
return b;
26
}
27
}
R5. 1 1 Use the process of stepwise refinement to describe the process of making scrambled
eggs. Discuss what you do if you do not find eggs in the refrigerator.
R5. 1 2 Perform a walkthrough of the i ntName method with the following arguments:
a. 5
b. 12
C. 21
d. SOI
e. 324
f. 0
g- 2
R5. 1 3 Consider the following method:
public static int f(int a)
{
if (a < 0) { return -1; }
int n = a;
238 Chapter 5 Methods
while (n > 0)
{
if (n % 2 == 0) // n is even
{
n = n / 2;
}
else if (n == 1) { return 1; }
else {n = 3*n + l; }
}
return 0;
}
Perform traces of the computations f(-l), f(0), f(l), f(2), f (10), and f(100).
■ ■ ■ R5. 1 4 Consider the following method that is intended to swap the values of two integers:
public static void fal seSwap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
public static void main(String[] args)
{
int x = 3;
int y = 4;
falseSwap(x, y) ;
System. out. print! n(x + " " + y) ;
}
Why doesn’t the fal seSwap method swap the contents of x and y ?
■ ■ ■ R5. 1 5 Give pseudocode for a recursive method for printing all substrings of a given string.
For example, the substrings of the string "rum" are "rum" itself, "ru" , "urn", "r", "u",
"m", and the empty string. You may assume that all letters of the string are different.
■ ■ ■ R5. 1 6 Give pseudocode for a recursive method that sorts all letters in a string. For example,
the string "goodbye" would be sorted into "bdegooy".
PROGRAMMING EXERCISES
■ P5. 1 Write the following methods and provide a program to test them.
a. double smallest(double x, double y, double z), returning the smallest of the
arguments
b. double average (double x, double y, double z), returning the average of the
arguments
■ ■ P5.2 Write the following methods and provide a program to test them.
a, boolean allTheSame(double x, double y, double z), returning true if the arguments
are all the same
b= boolean allDifferent(double x, double y, double z), returning true if the argu¬
ments are all different
c. boolean sorted(double x, double y, double z), returning true if the arguments are
sorted, with the smallest one coming first
Programming Exercises 239
P5.3 Write the following methods.
a. i nt fi rstDi gi t(i nt n), returning the first digit of the argument
b. int lastDigit(int n), returning the last digit of the argument
c. int digits(int n), returning the number of digits of the argument
For example, fi rstDigit(1729) is 1, lastDigit(1729) is 9, and di gi ts (1729) is 4. Provide a
program that tests your methods.
P5.4 Write a method
public static String middle (St ring str)
that returns a string containing the middle character in str if the length of str is odd,
or the two middle characters if the length is even. For example, middle ("middle")
returns "dd".
P 5 . 5 Write a metho d
public static String repeat(String str, int n)
that returns the string str repeated n times. For example, repeat("ho" , 3) returns
"hohoho".
P5.6 Write a method
public static int countVowels(String str)
that returns a count of all vowels in the string str. Vowels are the letters a, e, i, o, and
u, and their uppercase variants.
P 5 . 7 Write a metho d
public static int countWords(String str)
that returns a count of all words in the string str. Words are separated by spaces. For
example, countWords("Mary had a little lamb") should return 5.
P5.8 It is a well-known phenomenon that most people are easily able to read a text whose
words have two characters flipped, provided the first and last letter of each word are
not changed. For example,
I dn’ot gvie a dman for a man taht can olny sepll a wrod one way. (Mrak Taiwn)
Write a method String scramble (St ring word) that constructs a scrambled version of a
given word, randomly flipping two characters other than the first and last one. Then
write a program that reads words and prints the scrambled words.
P5.9 Write methods
public static double sphereVolume(double r)
public static double sphereSurface(double r)
public static double cylinderVolume(double r, double h)
public static double cylinderSurface(double r, double h)
public static double coneVolume (double r, double h)
public static double coneSurface(double r, double h)
that compute the volume and surface area of a sphere with radius r, a cylinder with a
circular base with radius r and height h, and a cone with a circular base with radius r
and height h. Then write a program that prompts the user for the values of r and h,
calls the six methods, and prints the results.
240 Chapter 5 Methods
■ ■ P5.10
■ ■ P5.ll
■ ■ P5.12
■ ■■ PS. 13
■ ■■ P5.14
■ ■ P5.15
■ ■ P5.16
■ ■ P5.17
. P5.18
. P5.19
■ ■ P5.20
Write a method
public static double readDouble(String prompt)
that displays the prompt string, followed by a space, reads a floating-point number
in, and returns it. Here is a typical usage:
salary = readDouble("Please enter your salary:");
percentageRai se = readDouble("What percentage raise would you like?");
Enhance the i ntName method so that it works correctly for values < 1 ,000,000,000.
Enhance the i ntName method so that it works correctly for negative values and zero.
Caution: Make sure the improved method doesn’t print 20 as "twenty zero".
For some values (for example, 20), the i ntName method returns a string with a lead¬
ing space (" twenty"). Repair that blemish and ensure that spaces are inserted only
when necessary. Hint: There are two ways of accomplishing this. Either ensure that
leading spaces are never inserted, or remove leading spaces from the result before
returning it.
Write a method String getTimeName(int hours, int mi nutes) that returns the English
name for a point in time, such as "ten minutes past two", "half past three", "a quarter to
four", or "five o'clock". Assume that hours is between 1 and 12.
Write a recursive method
public static String reverse(String str)
that computes the reverse of a string. For example, reverse("flow") should return
"wol f ". Hint: Reverse the substring starting at the second character, then add the first
character at the end. For example, to reverse "flow", first reverse "low" to "wol ", then
add the "f " at the end.
Write a recursive method
public static boolean isPalindrome(String str)
that returns true if str is a palindrome, that is, a word that is the same when reversed.
Examples of palindrome are “deed”, “rotor”, or “aibohphobia”. Hint: A word is a
palindrome if the first and last letters match and the remainder is also a palindrome.
Use recursion to implement a method public static boolean find(String str, String
match) that tests whether match is contained in str:
boolean b = find ("Mississippi", "sip"); // Sets b to true
Hint: If str starts with match, then you are done. If not, consider the string that you
obtain by removing the first character.
Use recursion to determine the number of digits in an integer n. Hint: If n is < 10, it
has one digit. Otherwise, it has one more digit than n / 10.
Use recursion to compute an, where n is a positive integer. Hint: If n is 1, then
an = a.\{n is even, then an = (<t”/2)2. Otherwise, an = ax an~l.
Leap years. Write a method
public static boolean isLeapYear(int year)
that tests whether a year is a leap year: that is, a year with 366 days. Exercise P3.28
describes how to test whether a year is a leap year. In this exercise, use multiple i f
statements and return statements to return the result as soon as you know it.
Programming Exercises 241
■ ■ P5.21 In Exercise P3.26 you were asked to write a program to
convert a number to its representation in Roman numerals.
At the time, you did not know how to eliminate duplicate
code, and as a consequence the resulting program was rather
long. Rewrite that program by implementing and using the
following method:
public static String romanDigit(int n, String one, String five, String ten)
That method translates one digit, using the strings specified for the one, five, and ten
values. You would call the method as follows:
romanOnes = romanDigit(n % 10, “I”, “V”, “X”);
n = n / 10;
romanTens = romanDigit(n % 10, “X”, “L”, “C”);
MCMXXVI
Business P5.22 Write a method that computes the balance of a bank account with a given initial
balance and interest rate, after a given number of years. Assume interest is com¬
pounded yearly.
Business P5.23 Write a program that prints instructions to get coffee, asking the user for input
whenever a decision needs to be made. Decompose each task into a method, for
example:
public static void brewCoffee()
{
System. out. println (“Add water to the coffee maker.”);
System. out. println(“Put a filter in the coffee maker.”);
grindCoffee() ;
System. out. println(“Put the coffee in the filter.”);
}
Business P5.24 Write a program that prints a paycheck. Ask the program user for the name of the
employee, the hourly rate, and the number of hours worked. If the number of hours
exceeds 40, the employee is paid “time and a half”, that is, 150 percent of the hourly
rate on the hours exceeding 40. Your check should look similar to that in the fig¬
ure below. Use fictitious names for the payer and the bank. Be sure to use stepwise
refinement and break your solution into several methods. Use the i ntName method to
print the dollar amount of the check.
)WILEYI
John Wiley & Sons, Inc.
Ill River Street
Hoboken, NJ 07030-5774
PAY
Publishers’ Bank Minnesota
2000 Prince Blvd
Jonesville, MN 55400
CHECK
NUMBER
063331
/ Date
Amount A
V 04/29/13
$*******274.15 J
TWO HUNDRED SEVENTY FOUR AND 15/100 ******************************************
TO THE ORDER OF:
JOHN DOE
1009 Franklin Blvd _
Sunnyvale, CA 95014
10a eudi: edoe. ao 3 7 5"" lacn
Business P5.25 Postal bar codes. For faster sorting of letters, the United States Postal Service encour¬
ages companies that send large volumes of mail to use a bar code denoting the zip
code (see Figure 6).
242 Chapter 5 Methods
*************** ECRLOT ** C057
CODE C671RTS2
JOHN DOE 0057
1009 FRANKLIN BLVD
SUNNYVALE CA 95014-5143
llilinlilill . IIiIiiIiIiIiiiiIIiIiiIiiIIiIiiIiI
Figure 6 A Postal Bar Code
The encoding scheme for a five-digit zip code is shown in Figure 7. There are
full-height frame bars on each side. The five encoded digits are followed by a check
digit, which is computed as follows: Add up all digits, and choose the check digit to
make the sum a multiple of 10. For example, the zip code 95014 has a sum of 19, so
the check digit is 1 to make the sum equal to 20.
II. I.. .1.1. II. n ...II .I..I mill
Digit 1 Digit 2 Digit 3 Digit 4 Digit 5 Check
Digit
Figure 7 Encoding for Five-Digit Bar Codes
Each digit of the zip code, and the check digit, is encoded according to the table
below, where 1 denotes a full bar and 0 a half bar:
Digit
Bar 1
Bar 2
Bar 3
Bar 4
Bar 5
(weight 7)
(weight 4)
(weight 2)
(weight 1 )
(weight 0)
1
0
0
0
1
1
2
0
0
1
0
1
3
0
0
1
1
0
4
0
1
0
0
1
5
0
1
0
1
0
6
0
1
1
0
0
7
1
0
0
0
1
8
1
0
0
1
0
9
1
0
1
0
0
0
1
1
0
0
0
The digit can be easily computed from the bar code using the column weights 7, 4, 2,
1, 0. For example, 01100is0x7+lx4 + lx2 + 0xl-i-0x0 = 6. The only exception
is 0, which would yield 1 1 according to the weight formula.
Programming Exercises 243
Write a program that asks the user for a zip code and prints the bar code. Use : for
half bars, | for full bars. For example, 95014 becomes
Provide these methods:
public static void printDigit(int d)
public static void printBarCode(int zipCode)
Business P5.26 Write a program that reads in a bar code (with : denoting half bars and | denoting
full bars) and prints out the zip code it represents. Print an error message if the bar
code is not correct.
Business P5.27 Write a program that converts a Roman number such as MCMLXXVIII to its deci¬
mal number representation. Hint: First write a method that yields the numeric value
of each of the letters. Then use the following algorithm:
total * 0
While the roman number string is not empty
If valueCfirst character) is at least valueisecond character), or the string has length 1
Add valuetfirst character) to total.
Remove the character.
Else
Add the difference valueisecond character) - valuelfirst character) to total.
Remove both characters.
Business P5.28 A non-governmental organization needs a program to calculate the amount of finan¬
cial assistance for needy families. The formula is as follows:
• If the annual household income is between $30,000 and $40,000 and the
household has at least three children, the amount is $1,000 per child.
• If the annual household income is between $20,000 and $30,000 and the
household has at least two children, the amount is $1,500 per child.
• If the annual household income is less than $20,000, the amount is $2,000 per
child.
Implement a method for this computation. Write a program that asks for the house¬
hold income and number of children for each applicant, printing the amount
returned by your method. Use -1 as a sentinel value for the input.
Business P5.29 In a social networking service, a user has friends, the
friends have other friends, and so on. We are interested
in knowing how many people can be reached from a
person by following a given number of friendship rela¬
tions. This number is called the “degree of separation”:
one for friends, two for friends of friends, and so on.
Because we do not have the data from an actual social
network, we will simply use an average of the number of friends per user.
Write a recursive method
public static double reachablePeople(int degree, double averageFriendsPerllser)
Use that method in a program that prompts the user for the desired degree and
average, and then prints the number of reachable people. This number should
include the original user.
244 Chapter 5 Methods
■ ■ Business P5.30 Having a secure password is a very important practice, when much of our informa¬
tion is stored online. Write a program that validates a new password, following these
rules:
• The password must be at least 8 characters long.
• The password must have at least one uppercase and one lowercase letter
• The password must have at least one digit.
Write a program that asks for a password, then asks again to confirm it. If the
passwords don’t match or the rules are not fulfilled, prompt again. Your program
should include a method that checks whether a password is valid.
■ ■ ■ Science P5.31 You are designing an element for a control panel that displays a temperature value
between 0 and 100. The element’s color should vary continuously from blue (when
the temperature is 0) to red (when the temperature is 100). Write a method publ i c
static int colorForValue(double temperature) that returns a color value for the given
temperature. Colors are encoded as red/green/blue values, each between 0 and 255.
The three colors are combined into a single integer, using the formula
color = 65536 x red + 256 x green + blue
Each of the intermediate colors should be fully saturated; that is, it should be on the
outside of the color cube, along the path that goes from blue through cyan, green,
and yellow to red.
You need to know how to interpolate between values. In general, if an output y
should vary from c to d as an input x varies from a to b, theny is computed as follows:
z = (x — a) / ( b-a )
y = dz + c(l-z )
If the temperature is between 0 and 25 degrees, interpolate between blue and cyan,
whose (red, green, blue) components are (0, 0, 255) and (0, 255, 255). For temperature
values between 25 and 50, interpolate between (0, 255, 255) and (0, 255, 0), which rep¬
resents the color green. Do the same for the remaining two path segments.
You need to interpolate each color component separately and then combine the
interpolated colors to a single integer.
Be sure to use appropriate helper methods to solve your task.
■ ■ Science P5.32 In a movie theater, the angle 9 at which a viewer sees the picture on the screen
depends on the distance x of the viewer from the screen. For a movie theater with the
dimensions shown in the picture below, write a method that computes the angle for a
given distance.
Programming Exercises 245
Next, provide a more general method that works for theaters with arbitrary
dimensions.
Science P5.33 The effective focal length/of a lens of thickness d
that has surfaces with radii of curvature R \ and R2
is given by
j = in - 0
where n is the refractive index of the lens medium.
Write a method that computes/in terms of the other
parameters.
Science P5.34 A laboratory container is shaped like the frustum of a cone:
Write methods to compute the volume and surface area, using these equations:
V = \nh[R2 + R2 + R1R2]
S = n(Rl + R2)^{R2- Rxf + h2 + nR2
Science P5.35
Electric wire, like that in the photo, is a cylindrical conductor covered by an insulat¬
ing material. The resistance of a piece of wire is given by the formula
p _ Pt _ 4pT
A nd 2
where p is the resistivity of the conductor, and L, A, and d are the length, cross-
sectional area, and diameter of the wire. The resistivity of copper is 1.678 x 10-8 Q m.
246 Chapter 5 Methods
The wire diameter, d, is commonly specified by the American wire gauge (AWG),
which is an integer, n. The diameter of an AWG n wire is given by the formula
36 —n
d = 0.127 x 92 39 mm
Write a method
public static double diameter(int wireCauge)
that accepts the wire gauge and returns the corresponding wire diameter. Write
another method
public static double copperWireResistance(double length, int wireCauge)
that accepts the length and gauge of a piece of copper wire and returns the resistance
of that wire. The resistivity of aluminum is 2.82 x 10-S Q m. Write a third method
public static double aluminumWireResistance(double length, int wireCauge)
that accepts the length and gauge of a piece of aluminum wire and returns the
resistance of that wire.
Write a program to test these methods.
■ ■ Science P5.36 The drag force on a car is given by
= 2 pv2ACD
where p is the density of air (1.23 kg/m3), v is the velocity in units of m/s, A is the
projected area of the car (2.5 m2), and Cjj is the drag coefficient (0.2).
The amount of power in watts required to overcome such drag force is P = Fjyv, and
the equivalent horsepower required is Hp =P/7 46. Write a program that accepts a
car’s velocity and computes the power in watts and in horsepower needed to over¬
come the resulting drag force. Note: 1 mph = 0.447 m/s.
ANSWERS TO SELF-CHECK QUESTIONS
1 . The arguments are 3 and 2. The return value
is 9.
2. The inner call to Math . pow returns 22 = 4. There¬
fore, the outer call returns 42 = 16.
3. 3.0
4. Users of the method can treat it as a black box.
5. 27
6. 8x8x8 = 512
7. double volume = Math. pow(sideLength, 3);
return volume;
8. public static double squareArea(
double sideLength)
{
double area = sideLength * sideLength;
return area;
}
9. (2 + 3) / (3 - 2) = 5
1 0. When the mystery method is called, x is set to
5, y is set to 7, and z becomes 12.0. Then z is
changed to 6.0, and that value is returned and
printed.
1 1 . When the method is called, x is set to 5. Then
y is set to 25, and that value is returned and
printed.
1 2. When the method is called, n is set to 5. Then n
is incremented twice, setting it to 7. That value
is returned and printed.
13. It acts the same way: If si deLength is 0, it returns
0 directly instead of computing 0x0x0.
1 4. It returns true if n is even; fal se if n is odd.
Answers to Self-Check Questions 247
15. public static boolean mystery (int n)
{
return n % 2 == 0;
}
16. boxStringC'Hello") ;
boxString("World") ;
1 7. The boxStri ng method does not return a value.
Therefore, you cannot use it in a call to the
pri nt method.
18. public static void shout(String message)
{
System. out. println(message ++ "!!!");
}
19. public static void boxStri ng(String contents)
{
int n = contents . length() ;
for (int i = 0; i < n + 4; i++)
{
System. out . pri nt("-") ;
}
System. out. pri ntln() ;
System. out. println(" ! " + contents + " !");
for (int i = 0; i < n + 4; i++)
{
System. out . pri nt("-") ;
}
System. out. pri ntln()
}
20. public static void printLine(int count)
{
for (int i = 0; i < count; i++)
{
System. out . pri nt("-") ;
}
System. out. pri ntln() ;
}
public static void boxString (String contents)
{
int n = contents . length() ;
printLine(n + 2) ;
System. out. println("!" + contents + "!");
printLine(n + 2) ;
}
21. int totalPennies = getPennies(total) ;
int taxPennies = getPennies (total * taxRate);
where the method is defined as
©param amount an amount in dollars and cents
©return the number of pennies in the amount
V
public static int getPennies(double amount)
{
return (int) Math. round (100 * amount) % 100;
22. if ( isEven(page)) . . .
where the method is defined as follows:
public static boolean isEven(int n)
{
return n % 2 == 0;
}
23. Add parameter variables so you can pass the
initial balance and interest rate to the method:
public static double balance(
double initialBalance, double rate,
int years)
{
return initialBalance * pow(
1 + rate / 100, years) ;
}
24. int spaces = countSpaces(input) ;
where the method is defined as follows:
©param str any string
©return the number of spaces in str
V
public static int countSpaces(Stri ng str)
{
int count = 0;
for (int i = 0; i < str.length() ; i++)
{
if (str.charAt(i) == ' ')
{
count++;
}
}
return count;
}
25. It is very easy to replace the space with any
character.
/**
©pa ram str any string
©pa ram ch a character whose occurrences
should be counted
©return the number of times that ch occurs
in str
V
public static int count(String str, char ch)
{
int count = 0;
for (int i = 0; i < str.length() ; i++)
{
if (str.charAt(i) == ch) { count++; }
}
return count;
}
This is useful if you want to count other char¬
acters. For example, count(input, ",") counts
the commas in the input.
248 Chapter 5 Methods
26. Change line 28 to
name = name + digitName(part / 100)
+ " hundred";
In line 25, add the statement
if (part >= 1000)
{
name = digitName(part / 1000) + "thousand
part = part % 1000;
}
Inline 18, change 1000 to 10000 in the
comment.
27. In the case of “teens”, we already have the last
digit as part of the name.
28. Nothing is printed. One way of dealing with
this case is to add the following statement
before line 23.
if (number == 0) { return "zero"; }
29. Here is the approximate trace:
Note that the string starts with a blank space.
Exercise P5.13 asks you to eliminate it.
30. Here is one possible solution. Break up the
task print table into print header and
print body. The print header task calls print separator,
prints the header cells, and calls print separator
again. The print body task repeatedly calls print row
and then calls print separator.
31. Lines 14-17.
32. Lines 11-19.
33. The variables x defined in lines 5 and 15.
34. Rename the local variable x that is declared in
line 15, or rename the parameter variable x that
is declared in line 1 0.
35. The mai n method accesses the local variable s
of the mystery method. Assuming that the mai n
method intended to print the last value of s
before the method returned, it should simply
print the return value that is stored in its local
variable x.
36. [][][][]
□ □□
□ □
[]
37. 4 + 3 + 2+ 1 + 0 = 10
38. mystery(lO) + 1 = mystery(5) + 2 = mystery(2) + 3
= mystery(l) + 4 = mystery(O) +5=5
39. The idea is to print one [] , then print n - 1 of
them.
public static void printBoxes(int n)
{
if (n == 0) { return; }
System. out. print("[]") ;
printBoxes(n - 1);
}
40. Simply add the following to the beginning of
the method:
if (part >= 1000)
{
return intName(part / 1000) + " thousand "
+ intName(part % 1000);
}
^^M3ZQE36
ARRAYS AND
ARRAY LISTS
CHAPTER
CHAPTER COALS
To collect elements using arrays
and array lists
To use the enhanced for loop for traversing arrays and array lists
To learn common algorithms for processing arrays and array lists
To work with two-dimensional arrays
CHAPTER CONTENTS
6.1 ARRAYS 250
Syntax 6. 1 : Arrays 2 5 1
Common Error 6.1 : Bounds Errors 255
Common Error 6.2: Uninitialized Arrays 255
Programming Tip 6.1 : Use Arrays for Sequences
of Related Items 256
Random Fact 6.1 : An Early Internet Worm 256
6.2 THE ENHANCED FOR LOOP 2 57
Syntax 6.2: The Enhanced for Loop 258
6.3 COMMON ARRAY ALGORITHMS 258
Common Error 6.3: Underestimating the Size
of a Data Set 267
SpecialTopic6.1 : Sorting with thejava Library 267
Special Topic 6.2: Binary Search 267
6.4 USING ARRAYS WITH METHODS 268
Special Topic 6.3: Methods with a Variable
Number of Parameters 272
6.5 PROBLEM SOLVING: ADAPTING
ALGORITHMS 272
Programming Tip 6.2: Reading Exception
Reports 274
HowTo 6. 1: Working with Arrays 275
Worked Example 6.1 : Rolling the Dice ©
6.6 PROBLEM SOLVING: DISCOVERING
ALGORITHMS BY MANIPULATING
PHYSICAL OBJECTS 279
Video Example 6.1 : Removing Duplicates from
an Array ©
6.7 TWO-DIMENSIONAL ARRAYS 282
Syntax 6.3: Two-Dimensional Array
Declaration 283
Worked Example 6.2: A World Population Table ©
Special Topic 6.4: Two-Dimensional Arrays with
Variable Row Lengths 288
Special Topic 6.5: Multidimensional Arrays 289
6.8 ARRAY LISTS 289
Syntax 6.4: Array Lists 290
Common Error 6.4: Length and Size 299
Special Topic 6.6: The Diamond Syntax
in Java 7 299
Video Example 6.2: Came of Life ©
9
In many programs, you need to collect large numbers of
values. In Java, you use the array and array list constructs
for this purpose. Arrays have a more concise syntax,
whereas array lists can automatically grow to any desired
size. In this chapter, you will learn about arrays, array lists,
and common algorithms for processing them.
6.1 Arrays
We start this chapter by introducing the array data type. Arrays are the fundamental
mechanism in Java for collecting multiple values. In the following sections, you will
learn how to declare arrays and how to access array elements.
6.1.1 Declaring and Using Arrays
Suppose you write a program that reads a sequence of values and prints out the
sequence, marking the largest value, like this:
32
54
67.5
29
35
80
115 <= largest value
44.5
100
65
You do not know which value to mark as the largest one until you have seen them all.
After all, the last value might be the largest one. Therefore, the program must first
store all values before it can print them.
Could you simply store each value in a separate variable? If you know that there
are ten values, then you could store the values in ten variables val uel, val ue2, val ue3, . . .,
val uelO. However, such a sequence of variables is not very practical to use. You would
have to write quite a bit of code ten times, once for each of the variables. In Java, an
array is a much better choice for storing a sequence of values of the same type.
Here we create an array that can hold ten values of type doubl e:
new double [10]
The number of elements (here, 10) is called the length of the array.
The new operator constructs the array. You will want to store the array in a variable
so that you can access it later.
The type of an array variable is the type of the element to be stored, followed by [] .
In this example, the type is doubl e [] , because the element type is doubl e.
Here is the declaration of an array variable of type doublet] (see Figure 1):
doublet] values; ^
When you declare an array variable, it is not yet initialized. You need to initialize the
variable with the array:
doublet] values = new doubl e [10] ; Q
An array collects a
sequence of values of
the same type.
250
6.1 Arrays 251
o
values =
Declare the array variable
Individual elements
in an array are
accessed by an
integer index i, using
the notation
array\_ i ] .
An array element
can be used like
any variable.
Syntax 6.1
Figure 1 An Array of Size 1 0
Now val ues is initialized with an array of 10 numbers. By default, each number in the
array is 0.
When you declare an array, you can specify the initial values. For example,
doublet] moreValues = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 };
When you supply initial values, you don’t use the new operator. The compiler deter¬
mines the length of the array by counting the initial values.
To access a value in an array, you specify which “slot” you want to use. That is
done with the [] operator:
val ues [4] = 35; Q
Now the number 4 slot of values is filled with 35 (see Figure 1). This “slot number” is
called an index. Each slot in an array contains an element.
Because values is an array of double values, each element val ues [i] can be used like
any variable of type double. For example, you can display the element with index 4
with the following command:
System. out. println(values[4]) ;
Arrays
Syntax To construct an array: new typeName[length ]
To access an element: arrayReference [index]
Name of array variable
Type of array variable
Element
type Length
double[] values = new doubl e [10] ;
double[] moreValues = { 32, 54, 67.5, 29, 35 };
Use brackets to access an element.
A
values[i] = 0;
List of initial values
The index must be > 0 and < the length of the array,
"'if See page 155.
252 Chapter 6 Arrays and Array Lists
Before continuing, we must take care of an
important detail of Java arrays. If you look
carefully at Figure 1, you will find that the
fifth element was filled when we changed
values [4], In Java, the elements of arrays
are numbered starting at 0. That is, the
legal elements for the val ues array are
val ues [0] , the first element
val ues [1] , the second element
val ues [2] , the third element
val ues [3] , the fourth element
val ues [4] , the fifth element
Like a mailbox that is identified by a box
number, an array element is identified by
an index.
An array index must
be at least zero and
less than the size of
the array.
A bounds error,
which occurs if you
supply an invalid
array index, can
cause your program
to terminate.
val ues [9] , the tenth element
In other words, the declaration
doublet] values = new doubl e [10] ;
creates an array with ten elements. In this array, an index can be any integer ranging
from 0 to 9.
You have to be careful that the index stays within the valid range. Trying to access
an element that does not exist in the array is a serious error. For example, if val ues has
ten elements, you are not allowed to access val ues [20]. Attempting to access an ele¬
ment whose index is not within the valid index range is called a bounds error. The
compiler does not catch this type of error. When a bounds error occurs at run time, it
causes a run-time exception.
Here is a very common bounds error:
doublet] values = new doubl e [10] ;
val ues [10] = value;
There is no val ues [10] in an array with ten elements — the index can range from 0 to 9.
To avoid bounds errors, you will want to know how many elements are in an array.
The expression val ues . 1 ength yields the length of the val ues array. Note that there are
no parentheses following 1 ength.
Table 1 Declaring Arrays
int[] numbers = new i nt [10] ;
An array of ten integers. All elements are
initialized with zero.
final int LENGTH = 10;
int[] numbers = new i nt [LENGTH] ;
It is a good idea to use a named constant
instead of a “magic number”.
int length = i n . nextlntO ;
double[] data = new double[length] ;
The length need not be a constant.
int[] squares = { 0, 1, 4, 9, 16 };
An array of five integers, with initial values.
String[] friends ft { "Emily", "Bob", "Cindy" };
An array of three strings.
doublet] data = new int [10];
Error: You cannot initialize a doubl e []
variable with an array of type i nt [] .
6.1 Arrays 253
Use the expression
array. length to find
the number of
elements in an array.
The following code ensures that you only access the array when the index variable
i is within the legal bounds:
if (0 <= i && i < values. length) { values [i] = value; }
Arrays suffer from a significant limitation: their length is fixed. If you start out with
an array of 10 elements and later decide that you need to add additional elements,
then you need to make a new array and copy all elements of the existing array into the
new array. We will discuss this process in detail in Section 6.3.9.
To visit all elements of an array, use a variable for the index. Suppose val ues has ten
elements and the integer variable i is set to 0, 1, 2, and so on, up to 9. Then the expres¬
sion val ues [1 ] yields each element in turn. For example, this loop displays all elements
in the val ues array.
for (int i =0; i <10; i++)
{
System. out. println (val ues [i ] ) ;
}
Note that in the loop condition the index is less than 10 because there is no element
corresponding to val ues [10] .
6.1.2 Array References
An array reference
specifies the location
of an array. Copying
the reference yields a
second reference to
the same array.
If you look closely at Figure 1, you will note that the variable values does not store
any numbers. Instead, the array is stored elsewhere and the values variable holds a
reference to the array. (The reference denotes the location of the array in memory.)
When you access the elements in an array, you need not be concerned about the fact
that Java uses array references. This only becomes important when copying array
references.
When you copy an array variable into another, both variables refer to the same
array (see Figure 2).
int[] scores = { 10, 9, 7, 4, 5 };
int[] values = scores; // Copying array reference
You can modify the array through either of the variables:
scores[3] = 10;
System. out. println(values[3]) ; // Prints 10
Section 6.3.9 shows how you can make a copy of the contents of the array.
scores =
values =
Figure 2
Two Array Variables Referencing the Same Array
254 Chapter 6 Arrays and Array Lists
6.1.3 Partially Filled Arrays
With a partially filled
array, you need to
remember how many
elements are filled.
An array cannot change size at run time. This is a problem when you don’t know in
advance how many elements you need. In that situation, you must come up with a
good guess on the maximum number of elements that you need to store. For exam¬
ple, we may decide that we sometimes want to store more than ten elements, but
never more than 100:
final int LENGTH = 100;
doublet] values = new doubl e [LENGTH] ;
In a typical program run, only a part of the array will be occupied by actual elements.
We call such an array a partially filled array. You must keep a companion variable
that counts how many elements are actually used. In Figure 3 we call the companion
variable currentSize.
The following loop collects inputs and fills up the val ues array:
int currentSize = 0;
Scanner in = new Scanner(System.in);
while (in.hasNextDoubleO)
{
if (currentSize < values. length)
{
values[currentSize] = in.nextDouble() ;
currentSize++;
}
}
With a partially filled
array, keep a
companion variable
for the current size.
ONLINE EXAMPLE
A program
demonstrating array
operations.
At the end of this loop, currentSize contains the actual number of elements in the
array. Note that you have to stop accepting inputs if the currentSize companion vari¬
able reaches the array length.
To process the gathered array elements, you again use the companion variable, not
the array length. This loop prints the partially filled array:
for (int i = 0; i < currentSize; i++)
{
System. out. println (val ues [i ] ) ;
}
>• currentSi ze
r val ues .length
Figure 3 A Partially Filled Array
6.1 Arrays 255
Practice It
Common Error 6.1
■" f.
Common Error 6.2
" f X
1 . Declare an array of integers containing the first five prime numbers.
2 . Assume the array primes has been initialized as described in Self Check 1 . What
does it contain after executing the following loop?
for (int i =0; i < 2 ; i++)
{
primes[4 - i] = pri mes [i ] ;
}
3. Assume the array primes has been initialized as described in Self Check 1. What
does it contain after executing the following loop?
for (int i = 0; i < 5; i++)
{
primes[i]++;
}
4. Given the declaration
int[] values = new i nt [10] ;
write statements to put the integer 10 into the elements of the array val ues with
the lowest and the highest valid index.
5. Declare an array called words that can hold ten elements of type Stri ng.
6. Declare an array containing two strings, "Yes", and "No".
7. Can you produce the output on page 250 without storing the inputs in an array,
by using an algorithm similar to the algorithm for finding the maximum in
Section 4.7.5?
Now you can try these exercises at the end of the chapter: R6.1, R6.2, R6.6, P6.1.
Bounds Errors
Perhaps the most common error in using arrays is accessing a nonexistent element.
doubled values = new double [10];
val ues [10] = 5.4;
// Error— values has 10 elements, and the index can range from 0 to 9
If your program accesses an array through an out-of-bounds index, there is no compiler error
message. Instead, the program will generate an exception at run time.
Uninitialized Arrays
A common error is to allocate an array variable, but not an actual array,
doublet] values;
val ues [0] = 29.95; // Error — values not initialized
The J ava compiler will catch this error. The remedy is to initialize the variable with an array:
doublet] values = new double [10];
256 Chapter 6 Arrays and Array Lists
Use Arrays for Sequences of Related Items
Arrays are intended for storing sequences of values with the same meaning. For example, an
array of test scores makes perfect sense:
int[] scores = new int[NUMBER_OF_SCORES] ;
But an array
int[] personal Data = new int[3];
that holds a person’s age, bank balance, and shoe size in positions 0, 1, and 2 is bad design.
It would be tedious for the programmer to remember which of these data values is stored in
which array location. In this situation, it is far better to use three separate variables.
Random Fact 6.1 An Early Internet Worm
In November 1988,
Robert Morris, a stu¬
dent at Cornell University, launched a
so-called virus program that infected
about 6,000 computers connected to
the Internet across the United States.
Tens of thousands of computer users
were unable to read their e-mail or oth¬
erwise use their computers. All major
universities and many high-tech com¬
panies were affected. (The Internet was
much smaller then than it is now.)
The particular kind of virus used in
this attack is called a worm. The worm
program crawled from one computer
on the Internet to the next. The worm
would attempt to connect to finger,
a program in the UNIX operating sys¬
tem for finding information on a user
who has an account on a particular
computer on the network. Like many
programs in UNIX, finger was written
in the C language. In order to store
the user name, the finger program
allocated an array of 512 characters,
under the assumption that nobody
would ever provide such a long input.
Unfortunately, C does not check that
an array index is less than the length
of the array. If you write into an array
using an index that is too large, you
simply overwrite memory locations
that belong to some other objects. In
some versions of the finger program,
the programmer had been lazy and had
not checked whether the array holding
the input characters was large enough
to hold the input. So the worm pro¬
gram purposefully filled the 512-char-
acter array with 536 bytes. The excess
24 bytes would overwrite a return
address, which the attacker knew was
stored just after the array. When that
method was finished, it didn’t return
to its caller but to code supplied by the
worm (see the figure, A “Buffer Over¬
run” Attack). That code ran under the
same super-user privileges as finger,
allowing the worm to gain entry into
the remote system. Had the program¬
mer who wrote finger been more
conscientious, this particular attack
would not be possible.
In Java, as in C, all programmers
must be very careful not to overrun
array boundaries. However, in Java,
this error causes a run-time exception,
and it never corrupts memory outside
the array. This is one of the safety fea¬
tures of Java.
One may well speculate what would
possess the virus author to spend
many weeks to plan the antisocial act
of breaking into thousands of comput¬
ers and disabling them. It appears that
the break-in was fully intended by the
author, but the disabling of the com¬
puters was a bug, caused by continu¬
ous reinfection. Morris was sentenced
to 3 years probation, 400 hours of com¬
munity service, and a $1 0,000 fine.
In recent years, computer attacks
have intensified and the motives
have become more sinister. Instead
of disabling computers, viruses often
steal financial data or use the attacked
computers for sending spam e-mail.
Sadly, many of these attacks continue
to be possible because of poorly writ¬
ten programs that are susceptible to
buffer overrun errors.
Before the attack
Buffer for input
(512 bytes)
Return address
After the attack
A "Buffer Overrun" Attack
6.2 The Enhanced for Loop 257
6.2 The Enhanced for Loop
You can use the
enhanced for loop
to visit all elements
of an array.
Use the enhanced
for loop if you do
not need the index
values in the
loop body.
ONLINE EXAMPLE
© An program that
demonstrates the
enhanced for loop.
Often, you need to visit all elements of an array. The enhanced for loop makes this
process particularly easy to program.
Here is how you use the enhanced for loop to total up all elements in an array
named values:
doublet] values = . . . ;
double total = 0;
for (double element : values)
{
total = total + element;
}
The loop body is executed for each element in the array values. At the beginning of
each loop iteration, the next element is assigned to the variable element. Then the loop
body is executed. You should read this loop as “for each el ement in val ues”.
This loop is equivalent to the following for loop and an explicit index variable:
for (i nt i = 0; i < values. length; i++)
{
double element = values[i];
total = total + element;
}
Note an important difference between the enhanced for loop and the basic for loop.
In the enhanced for loop, the element variable is assigned val ues [0], val ues [1], and so
on. In the basic for loop, the index variable i is assigned 0, 1, and so on.
Keep in mind that the enhanced for loop has a very specific purpose: getting the
elements of a collection, from the beginning to the end. It is not suitable for all array
algorithms. In particular, the enhanced for loop does not allow you to modify the
contents of an array. The following loop does not fill an array with zeroes:
for (double element : values)
{
element = 0; // ERROR: this assignment does not modify array elements
}
When the loop is executed, the variable el ement is set to val ues [0] . Then el ement is set to
0, then to val ues [1] , then to 0, and so on. The values array is not modified. The remedy
is simple: Use a basic for loop:
for (int i =0; i < val ues. length; i++)
{
val ues [i] = 0; // OK
}
The enhanced for loop is a convenient mechanism for
traversing all elements in a collection.
258 Chapter 6 Arrays and Array Lists
Syntax 6.2
The Enhanced for Loop
Syntax for ( typeName variable : collection )
{
statements
}
This variable is set in each loop iteration.
It is only defined inside the loop. '
An array
/
These statements
are executed for each
element.
for (double element : values)
{
sum = sum + element; The variable
} contains an element,
not an index.
8. What does this enhanced for loop do?
int counter = 0;
for (double element : values)
{
if (element == 0) { counter++; }
}
9. Write an enhanced for loop that prints all elements in the array val ues.
1 0. Write an enhanced for loop that multiplies all elements in a doubl e [] array named
factors, accumulating the result in a variable named product.
1 1 . Why is the enhanced for loop not an appropriate shortcut for the following basic
for loop?
for (int i = 0; i < values. length; i++) { values[i] = i * i; }
Practice It Now you can try these exercises at the end of the chapter: R6.7, R6.8, R6.9.
6.3 Common Array Algorithms
In the following sections, we discuss some of the most common algorithms for work¬
ing with arrays. If you use a partially filled array, remember to replace val ues. length
with the companion variable that represents the current size of the array.
6.3.1 Filling
This loop fills an array with squares (0, 1, 4, 9, 16, ...). Note that the element with
index 0 contains 02, the element with index 1 contains l2, and so on.
for (int i = 0; i < values. length; i++)
{
val ues [i] = i * i ;
}
6.B Common Array Algorithms 259
6.3.2 Sum and Average Value
You have already encountered this algorithm in Section 4.7.1. When the values are
located in an array, the code looks much simpler:
double total = 0;
for (double element : values)
{
total = total + element;
}
double average = 0;
If (values. length > 0) { average = total / values. length; }
6.3.3 Maximum and Minimum
Use the algorithm from Section 4.7.5 that keeps a variable for the largest element
already encountered. Here is the implementation of that algorithm for an array:
double largest = values[0];
for (int i = 1; i < values. length; i++)
{
if (values[i] > largest)
{
largest = values[i] ;
}
}
Note that the loop starts at 1 because we initialize largest with values [0].
To compute the smallest element, reverse the comparison.
These algorithms require that the array contain at least one element.
6.3.4 Element Separators
When separating
elements, don’t place
a separator before
the first element.
To print five
elements, you need
four separators.
When you display the elements of an array, you usually want to separate them, often
with commas or vertical lines, like this:
32 | 54 | 67.5 | 29 | 35
Note that there is one fewer separator than there are numbers. Print the separator
before each element in the sequence except the initial one (with index 0) like this:
for (int i =0; i < values. length; i++)
{
if (i > 0)
{
System. out. print(" | ");
}
System. out. print(values[i]) ;
}
If you want comma separators, you can use the Arrays. toString method. The
expression
Arrays . toStri ng(val ues)
returns a string describing the contents of the array val ues in the form
[32, 54, 67.5, 29, 35]
260 Chapter 6 Arrays and Array Lists
The elements are surrounded by a pair of brackets and separated by commas. This
method can be convenient for debugging:
System. out. print! n("va1ues=" + Arrays. toString(values));
6.3.5 Linear Search
To search for a
specific element,
visit the elements
and stop when you
encounter the match.
A linear search
inspects elements in
sequence until a
match is found.
You often need to search for the position of a specific element in an array so that you
can replace or remove it. Visit all elements until you have found a match or you have
come to the end of the array. Here we search for the position of the first element in an
array that is equal to 100:
int searchedValue = 100;
int pos = 0;
boolean found = false;
while (pos < values. length && ! found)
{
if (values [pos] == searchedValue)
{
found = true;
}
else
{
pos++;
}
}
if (found) { System. out. println("Found at position: " + pos); }
else { System. out. println("Not found"); }
This algorithm is called linear search or sequential search because you inspect the
elements in sequence. If the array is sorted, you can use the more efficient binary
search algorithm— see Special Topic 6.2 on page 267.
6.3.6 Removing an Element
Suppose you want to remove the element with index pos from the array values. As
explained in Section 6.1.3, you need a companion variable for tracking the number of
elements in the array. In this example, we use a companion variable called currentSize.
If the elements in the array are not in any particular order, simply overwrite the
element to be removed with the last element of the array, then decrement the current-
Si ze variable. (See Figure 4.)
32
[0]
32
[0]
54
[1]
54
[1]
67.5
[2]
67.5
[2]
29
29
currentSize
....•► 34.5
[pos]
O
. ► 80
[pos]
80
/ 115
Decrement after
0
©
o
A.
44.5
Decrement after
moving elements
\ 44.5
moving element
100
l '• . 65
[currentSize - 1]
w
[currentSize - 1]
Figure 4
Figure 5
Removing an Element in an Unordered Array Removing an Element in an Ordered Array
6.3 Common Array Algorithms 261
values[pos] = values [currents! ze - 1] ;
currents! ze--;
It
Removing from
an Array
'I'
The situation is more complex if the order of the elements matters. Then you must
move all elements following the element to be removed to a lower index, and then
decrement the variable holding the size of the array. (See Figure 5.)
for (int i = pos + 1; i < currentSize; i++)
{
values [i - 1] = valuesfi];
}
currentSize--;
6.3.7 Inserting an Element
Inserting into
an Array
In this section, you will see how to insert an element into an array. Note that you
need a companion variable for tracking the array size, as explained in Section 6.1.3.
If the order of the elements does not matter, you can simply insert new elements at
the end, incrementing the variable tracking the size.
if (currentSize < values. length)
{
currentSize++;
values [currentSize - 1] = newElement;
}
Before inserting an
element, move
elements to the end
of the array starting
with the last one.
It is more work to insert an element at a particular position in the middle of an array.
First, move all elements after the insertion location to a higher index. Then insert the
new element (see Figure 7).
Note the order of the movement: When you remove an element, you first move
the next element to a lower index, then the one after that, until you finally get to the
end of the array. When you insert an element, you start at the end of the array, move
that element to a higher index, then move the one before that, and so on until you
finally get to the insertion location.
if (currentSize < values. length)
{
currentSize++;
for (int i = currentSize - 1; i > pos; i--)
{
values [i] = values [i - 1];
}
values [pos] = newElement;
currentSize -<
32
54
67.5
29
34.5
80
115
44.5
100
[0]
[1]
[2]
Insert new element here
Incremented before
inserting element
[currentSize - 1]
Q
O
Q
G
O
32
[0]
54
[1]
67.5
[2]
Insert new element here
29
[pos]
Incremented before
moving elements
■■■■► 100
[currentSize - 1]
Figure 6
Inserting an Element in an Unordered Array
Figure 7
Inserting an Element in an Ordered Array
262 Chapter 6 Arrays and Array Lists
Use a temporary
variable when
swapping two
elements.
6.3.8 Swapping Elements
You often need to swap elements of an array. For example,
you can sort an array by repeatedly swapping elements
that are not in order.
Consider the task of swapping the elements at posi¬
tions i and j of an array values. We’d like to set values [i]
to val ues [j] . But that overwrites the value that is currently
stored in val ues [1 ], so we want to save that first:
double temp = val ues [1];
val ues [i] = val ues [j];
Now we can set val ues [ j] to the saved value.
values[j] = temp;
To swap two elements, you
need a temporary variable.
Figure 8 shows the process.
values =
32
54
67.5
29
34.5
[0]
[1] [i]
[2]
[3] [j]
[4]
Values to be swapped
values =
32
54
67.5
29
34.5
[i]
[j]
temp =
54
values =
32
29
67.5
29
34.5
[i]
[j]
temp =
54
values =
32
29
67.5
54
34.5
[i]
[j]
temp =
54
Figure 8 Swapping Array Elements
6.3 Common Array Algorithms 263
6.3.9 Copying Arrays
Use the Arrays .
copyOf method to
copy the elements of
an array into a
new array.
Array variables do not themselves hold array elements. They hold a reference to the
actual array. If you copy the reference, you get another reference to the same array
(see Figure 9):
doublet] values = new doubl e [6] ;
...II Fill array
doublet] prices = values; Q
If you want to make a true copy of an array, call the Arrays. copyOf method (as shown
in Figure 9).
doublet] prices = Arrays. copyOf (values, values. length); Q
The call Arrays . copyOf (val ues , n) allocates an array of length n, copies the first n elements
of val ues (or the entire values array if n > val ues . 1 ength) into it, and returns the new array.
After the assignment pri ces = values
values =
prices =
Q After calling Arrays . copyOf
values = - ^
prices =
doubl e[]
32
54
67.5
29
35
47.5
doubl e[]
32
54
67.5
29
35
47.5
Figure 9 Copying an Array Reference versus Copying an Array
In order to use the Arrays class, you need to add the following statement to the top of
your program:
import java. util .Arrays;
Another use for Arrays. copyOf is to grow an array that has run out of space. The fol¬
lowing statements have the effect of doubling the length of an array (see Figure 10):
doublet] newValues = Arrays. copyOf (val ues, 2 * val ues. 1 ength) ; Q
values = newValues; Q
The copyOf method was added in Java 6. If you use Java 5, replace
doublet] newValues = Arrays. copyOf (val ues, n)
with
264 Chapter 6 Arrays and Array Lists
Figure TO Crowing an Array
doublet] newValues = new double[n];
for (int i =0; i < n && i < values. length; i++)
{
newValues [i] = val ues [i ] ;
}
6.3.1 0 Reading Input
If you know how many inputs the user will supply, it is simple to place them into an
array:
doublet] inputs = new double [NUMBER„OF_INPUTS] ;
for (i =0; i < inputs. length; i++)
{
i nputs [i ] = in . nextDouble() ;
}
However, this technique does not work if you need to read a sequence of arbitrary
length. In that case, add the inputs to an array until the end of the input has been
reached.
int currentSize = 0;
while (in.hasNextDoubleO && currentSize < inputs. length)
{
inputsfcurrentSize] = in.nextDouble();
currentSize++;
}
6.B Common Array Algorithms 265
Now inputs is a partially filled array, and the companion variable currentSize is set to
the number of inputs.
However, this loop silently throws away inputs that don’t fit into the array. A bet¬
ter approach is to grow the array to hold all inputs.
doublet] inputs = new double [INITIAL_SIZE] ;
int currentSize = 0;
while (in.hasNextDoubleO)
{
// Grow the array if it has been completely filled
if (currentSize >= inputs. length)
{
inputs = Arrays. copyOf (inputs, 2 * inputs. length) ; // Grow the inputs array
}
inputs [currentSize] = in.nextDouble();
currentSize++;
}
When you are done, you can discard any excess (unfilled) elements:
inputs = Arrays. copyOf (inputs, currentSize);
The following program puts these algorithms to work, solving the task that we set our¬
selves at the beginning of this chapter: to mark the largest value in an input sequence.
section_3/LargestlnArray.java
1 import java. util .Scanner;
2
3 /**
4 This program reads a sequence of values and prints them, marking the largest value.
5 V
6 public class LargestlnArray
7 {
8 public static void main(String[] args)
9 {
10 final int LENGTH = 100;
11 doublet] values = new double[LENGTH] ;
12 int currentSize = 0;
13
14 // Read inputs
15
16 System. out. println( Please enter values, Q to quit );
17 Scanner in = new Scanner(System.in) ;
18 while (in.hasNextDoubleO && currentSize < values. length)
19 {
20 val ues[currentSize] = in.nextDouble() ;
21 currentSize++;
22 }
23
24 // Find the largest value
25
26 double largest = values[0];
27 for (int i = 1; i < currentSize; i++)
28 {
29 if (values[i] > largest)
30 {
31 largest = values[i];
32 }
33
}
266 Chapter 6 Arrays and Array Lists
34
35 // Print all values, marking the largest
36
for (int i = 0; i < currentSize; i++)
38 {
39 System. out. print(values[i]) ;
40 if (val ues[i] == largest)
41 {
42 System. out. print( <== largest value );
43 }
44 System. out. printlnO ;
45 }
46 }
47 }
Program Run
Please enter values, Q to quit:
34.5 80 115 44.5 Q
34.5
80
115 <== largest value
44.5
1 2. Given these inputs, what is the output of the LargestlnArray program?
20 10 20 Q
1 3. Write a loop that counts how many elements in an array are equal to zero.
1 4. Consider the algorithm to find the largest element in an array. Why don’t we
initialize 1 argest and i with zero, like this?
double largest = 0;
for (int i =0; i < values. length; i++)
{
if (values[i] > largest)
{
largest = values [i] ;
}
}
1 5. When printing separators, we skipped the separator before the initial element.
Rewrite the loop so that the separator is printed after each element, except for
the last element.
1 6. What is wrong with these statements for printing an array with separators ?
System. out. print(values[0]) ;
for (int i = 1; i < values. length; i++)
{
System. out. print(", " + values[i]);
}
1 7. When finding the position of a match, we used a whi 1 e loop, not a for loop. What
is wrong with using this loop instead?
for (pos = 0; pos < values. length && ! found; pos++)
{
if (values [pos] > 100)
{
found = true;
}
6.3 Common Array Algorithms 267
}
1 8. When inserting an element into an array, we moved the elements with larger
index values, starting at the end of the array. Why is it wrong to start at the inser¬
tion location, like this?
for (int i = pos; i < currentSize - 1; i++)
{
values [i + 1] = values[i];
}
Practice It Now you can try these exercises at the end of the chapter: R6.17, R6.20, P6.15.
Underestimating the Size of a Data Set
Programmers commonly underestimate the amount of input data that a user will pour into an
unsuspecting program. Suppose you write a program to search for text in a file. You store each
line in a string, and keep an array of strings. How big do you make the array? Surely nobody
is going to challenge your program with an input that is more than 100 lines. Really? It is very
easy to feed in the entire text of Alice in Wonderland or War and Peace (which are available on
the Internet). All of a sudden, your program has to deal with tens or hundreds of thousands of
lines. You either need to allow for large inputs or politely reject the excess input.
Sorting with the Java Library
Sorting an array efficiently is not an easy task. You will
learn in Chapter 14 how to implement efficient sorting
algorithms. Fortunately, the Java library provides an effi¬
cient sort method.
To sort an array val ues, call
Arrays . sort(val ues) ;
If the array is partially filled, call
Arrays . sort(val ues , 0, currentSize);
Binary Search
When an array is sorted, there is a much faster search algorithm than the linear search of Sec¬
tion 6.3.5.
Consider the following sorted array values.
[0] [1] [2] [3] [4] [5] [6] [7]
9
12
17
20
32
We would like to see whether the number 15 is in the array. Let’s narrow our search by finding
whether the number is in the first or second half of the array. The last point in the first half of
the values array, val ues [3], is 9, which is smaller than the number we are looking for. Hence,
we should look in the second half of the array for a match, that is, in the sequence:
[0] [1] [2] [3] [4] [5] [6] [7]
15 8 9
12
17
20
32
268 Chapter 6 Arrays and Array Lists
Now the last element of the first half of this sequence is 17; hence, the number must be located
in the sequence:
[0] [1] [2] [3] [4] [5] 6] [7]
1
5 8 9 12
17
20 32
The last element of the first half of this very short sequence is 12, which is smaller than the
number that we are searching, so we must look in the second half:
[0] [1] [2] [3] [4] [5] [6] [7]
1 5 8 9 12 17 20 32
We still don’t have a match because 15*17, and we cannot divide the subsequence further. If
we wanted to insert 15 into the sequence, we would need to insert it just before values [5].
This search process is called a binary search, because we cut the size of the search in half in
each step. That cutting in half works only because we know that the array is sorted. Here is an
implementation in Java:
boolean found = false;
int low = 0;
int high = values. length - 1;
int pos = 0;
while (low <= high && Ifound)
{
pos = (low + high) / 2; // Midpoint of the subsequence
if (values[pos] == searchedNumber) { found = true; }
else if (values [pos] < searchedNumber) { low = pos + 1; } // Look in second half
else { high = pos - 1; } // Look in first half
}
if (found) { System. out. pri ntl n("Found at position " + pos); }
else { System. out. println("Not found. Insert before position " + pos); }
6.4 Using Arrays with Methods
In this section, we will explore how to write methods that process arrays.
. When you define a method with an array argument, you provide a parameter vari-
Arrays can occur as riri ^ . . r .. < ° . J J r ,r r
method arguments able tor the array. For example, the following method computes the sum of an array
and return values. of floating-point numbers:
public static double sum(double[] values)
{
double total = 0;
for (double element : values)
{
total = total + element;
}
return total ;
}
This method visits the array elements, but it does not modify them. It is also possible
to modify the elements of an array. The following method multiplies all elements of
an array by a given factor:
public static void multiply(double[] values, double factor)
{
for (int i =0; i < val ues . length ; i++)
{
6.4 Using Arrays with Methods 269
Figure 1 1
Trace of Call to
the multiply Method
values [i] = values [i] * factor;
}
}
Figure 1 1 traces the method call
multiply(scores, 10);
Note these steps:
• The parameter variables val ues and factor are created. ©
• The parameter variables are initialized with the arguments that are passed in the
call. In our case, val ues is set to scores and factor is set to 10. Note that values and
scores are references to the same array. ©
• The method multiplies all array elements by 1 0. ©
• The method returns. Its parameter variables are removed. However, scores still
refers to the array with the modified elements. ©
o
Method call
scores =
val ues
factor
o
scores =
values =
factor =
Initializing method parameter variables
o
scores =
values =
factor =
About to return to the caller
©
After method call
scores
270 Chapter 6 Arrays and Array Lists
A method can return an array. Simply build up the result in the method and return it.
In this example, the squares method returns an array of squares from 02 up to ( n - l)2:
public static int[] squares (int n)
{
int[] result = new i n t [ n ] ;
for (int i =0; i < n; i++)
{
resul t [i ] = i * i ;
}
return result;
}
The following example program reads values from standard input, multiplies them
by 10, and prints the result in reverse order. The program uses three methods:
• The readlnputs method returns an array, using the algorithm of Section 6.3.10.
• The multi pi y method has an array argument. It modifies the array elements.
• The pri ntReversed method also has an array argument, but it does not modify the
array elements.
section_4/Reverse.java
1 import java. util .Scanner;
2
3 /**
4 This program reads, scales, and reverses a sequence of numbers.
5 */
6 public class Reverse
7 {
8 public static void main(String[] args)
9 {
10 doublet] numbers = readlnputs(5) ;
11 multiply(numbers, 10);
12 pri ntReversed(numbers) ;
13 }
14
15 /**
1 6 Reads a sequence of floating-point numbers.
17 ©param numberOflnputs the number of inputs to read
1 8 ©return an array containing the input values
19 */
20 public static doublet] readlnputs(int numberOflnputs)
21 {
22 System. out. println( Enter + numberOflnputs + numbers: );
23 Scanner in = new Scanner(System.in) ;
24 doublet] inputs = new doublefnumberOflnputs] ;
25 for (int i = 0; i < inputs. length; i++)
26 {
27 inputs[i] = in.nextDouble() ;
28 }
29 return inputs;
30 }
31
32 /**
33 Multiplies all elements of an array by a factor.
34 ©param values an array
35 ©param factor the value with which element is multiplied
36 */
6.4 Using Arrays with Methods 271
public static void multiply(double[] values, double factor)
38 {
39 for (int i = 0; i < values. length; i++)
40 {
41 val ues[i] = values[i] * factor;
42 }
43 }
44
45 /**
46 Prints an array in reverse order.
47 @param values an array of numbers
48 ©return an array that contains the elements of val ues in reverse order
49 */
public static void printReversed(double[] values)
51 {
52 // Traverse the array in reverse order, starting with the last element
for (int i = val ues. length - 1; i >= 0; i--)
54 {
System. out. print(values[i] + );
56 }
57 System. out. println();
58 }
59 }
Program Run
Enter 5 numbers:
12 25 20 0 10
100.0 0.0 200.0 250.0 120.0
1 9. How do you call the squares method to compute the first five squares and store
the result in an array numbers?
20. Write a method fi 1 1 that fills all elements of an array of integers with a given
value. For example, the call fi 1 1 (scores , 10) should fill all elements of the array
scores with the value 10.
2 1 . Describe the purpose of the following method:
public static int[] mystery(int length, int n)
{
int[] result = new i nt [1 ength] ;
for (int i = 0; i < result. length; i++)
{
result[i] = (int) (n * Math. randomO) ;
}
return result;
}
22. Consider the following method that reverses an array:
public static i nt [] reverse(int[] values)
{
i nt [] result = new intfvalues. length] ;
for (int i =0; i < val ues. length; i++)
{
resultin'] = val ues [val ues. length - 1 - i];
}
return result;
272 Chapter 6 Arrays and Array Lists
Suppose the reverse method is called with an array scores that contains the
numbers 1, 4, and 9. What is the contents of scores after the method call?
23. Provide a trace diagram of the reverse method when called with an array that
contains the values 1, 4, and 9.
Practice It Now you can try these exercises at the end of the chapter: R6.25, P6.6, P6.7.
Methods with a Variable Number of Parameters
Starting with Java version 5.0, it is possible to declare methods that receive a variable number
of parameters. For example, we can write a sum method that can compute the sum of any num¬
ber of arguments:
int a = sum(l, 3); // Sets a to 4
int b = sum(l, 7, 2, 9); // Sets b to 19
The modified sum method must be declared as
public static void sum(int... values)
The . . . symbol indicates that the method can receive any number of i nt arguments. The val ues
parameter variable is actually an i nt [] array that contains all arguments that were passed to the
method. The method implementation traverses the val ues array and processes the elements:
public void sum(int... values)
{
int total = 0;
for (int i = 0; i < values. length; i++) // values is an int []
{
total = total + val ues [i];
}
return total;
}
6.5 Problem Solving: Adapting Algorithms
By combining
fundamental
algorithms, you can
solve complex
programming tasks.
In Section 6.3, you were introduced to a number of fundamental array algorithms.
These algorithms form the building blocks for many programs that process arrays.
In general, it is a good problem-solving strategy to have a repertoire of fundamental
algorithms that you can combine and adapt.
Consider this example problem: You are given the quiz scores of a student. You are
to compute the final quiz score, which is the sum of all scores after dropping the low¬
est one. For example, if the scores are
8 7 8.5 9.5 7 4 10
then the final score is 50.
We do not have a ready-made algorithm for this situation. Instead, consider which
algorithms may be related. These include:
• Calculating the sum (Section 6.3.2)
• Finding the minimum value (Section 6.3.3)
• Removing an element (Section 6.3.6)
6.5 Problem Solving: Adapting Algorithms 273
We can formulate a plan of attack that combines these algorithms:
Find the minimum.
Remove it from the array.
Calculate the sum.
Let’s try it out with our example. The minimum of
[0]
[i]
[2]
[3]
[4]
[5]
[6]
8
7
8.5
9.5
7
4
10
is 4. How do we remove it?
Now we have a problem. The removal algorithm in Section 6.3.6 locates the ele¬
ment to be removed by using the position of the element, not the value.
But we have another algorithm for that:
• Linear search (Section 6.3.5)
We need to fix our plan of attack:
Find the minimum value.
Find its position.
Remove that position from the array.
Calculate the sum.
Will it work? Let’s continue with our example.
We found a minimum value of 4. Linear search tells us that the value 4 occurs at
position 5.
[0] [1] [2] [3] [4] [5] [6]
8
7
8.5
9.5
7
B
10
We remove it:
[0]
[i]
[2]
[3]
[4]
[5]
8
7
8.5
9.5
7
10
You should be
familiar with the
implementation of
fundamental
algorithms so that
you can adapt them.
Finally, we compute the sum: 8 + 7 + 8.5 + 9.5 + 7 + 10 = 50.
This walkthrough demonstrates that our strategy works.
Can we do better? It seems a bit inefficient to find the minimum and then make
another pass through the array to obtain its position.
We can adapt the algorithm for finding the minimum to yield the position of the
minimum. Here is the original algorithm:
double smallest = values[0];
for (int i = 1; i < values. length; i++)
{
if (values[i] < smallest)
{
smallest = values[i] ;
}
}
When we find the smallest value, we also want to update the position:
if (values[i] < smallest)
{
smallest = values[i] ;
smallestPosition = i ;
}
274 Chapter 6 Arrays and Array Lists
ONLINE EXAMPLE
O A program that
computes the final
score using the
adapted algorithm
for finding the
minimum.
In fact, then there is no reason to keep track of the smallest value any longer. It is sim¬
ply val ues [smal 1 estPosi ti on] . With this insight, we can adapt the algorithm as follows:
int smallestPosition = 0;
for (int i = 1; i < values. length; i++)
{
if (values[i] < values[smallestPosition])
{
small estPosi ti on = i ;
}
}
With this adaptation, our problem is solved with the following strategy:
Find the position of the minimum.
Remove it from the array.
Calculate the sum.
The next section shows you a technique for discovering a new algorithm when none
of the fundamental algorithms can be adapted to a task.
27.
28.
Section 6.3.6 has two algorithms for removing an element. Which of the two
should be used to solve the task described in this section?
It isn’t actually necessary to remove the minimum in order to compute the total
score. Describe an alternative.
How can you print the number of positive and negative values in a given array,
using one or more of the algorithms in Section 4.7?
How can you print all positive values in an array, separated by commas?
Consider the following algorithm for collecting all matches in an array:
int matchesSize = 0;
for (int i = 0; i < values. length; i++)
{
if (values[i] fulfills the condition)
{
matches [matchesSize] = values[i];
matchesSize++;
}
}
How can this algorithm help you with Self Check 27?
Practice It
Now you can try these exercises at the end of the chapter: R6.26, R6.27.
Reading Exception Reports
You will sometimes have programs that terminate, reporting an “exception”, such as
Exception in thread “main” java.lang.ArraylndexOutOfBoundsException: 10
at Homeworkl. processVal ues(Homeworkl. java: 14)
at Homeworkl.mai n (Homeworkl. java: 36)
Quite a few students give up at that point, saying “it didn’t work”, or “my program died”,
without reading the error message. Admittedly, the format of the exception report is not very
friendly. But, with some practice, it is easy to decipher it.
6.5 Problem Solving: Adapting Algorithms 275
There are two pieces of useful information:
1. The name of the exception, such as ArraylndexOutOfBoundsException
2. The stack trace, that is, the method calls that led to the exception, such as
Homeworkl. java: 14 and Homeworkl. java: 36 in our example.
The name of the exception is always in the first line of the report, and it ends in Exception.
If you get an ArraylndexOutOfBoundsException, then there was a problem with an invalid array
index. That is useful information.
To determine the line number of the offending code, look at the file names and line num¬
bers. The first line of the stack trace is the method that actually generated the exception. The
last line of the stack trace is a line in mai n. In our example, the exception was caused by line 14
of Homeworkl. java. Open up the file, go to that line, and look at it! Also look at the name of the
exception. In most cases, these two pieces of information will make it completely obvious
what went wrong, and you can easily fix your error.
Sometimes, the exception was thrown by a method that is in the standard library. Here is a
typical example:
Exception in thread "main" java.lang.StringlndexOutOfBoundsException: String index
out of range: -4
at j ava . 1 ang . St ri ng . subst ri ng (St ri ng .java : 1444)
at Homework2 .main (Homework2 .java: 29)
The exception happened in the substring method of the String class, but the real culprit is the
first method in a file that you wrote. In this example, that is Homework2.main, and you should
look at line 29 of Homework2 . java.
HOW TO 6.1
Working with Arrays
In many data processing situations, you
need to process a sequence of values. This
How To walks you through the steps for
storing input values in an array and carrying
out computations with the array elements.
Consider again the problem from Sec¬
tion 6.5: A final quiz score is computed by
adding all the scores, except for the lowest
one. For example, if the scores are
8 7 8.5 9.5 7 5 10
then the final score is 50.
Step 1 Decompose your task into steps.
You will usually want to break down your task into multiple steps, such as
• Reading the data into an array.
• Processing the data in one or more steps.
• Displaying the results.
When deciding how to process the data, you should be familiar with the array algorithms in
Section 6.3. Most processing tasks can be solved by using one or more of these algorithms.
276 Chapter 6 Arrays and Array Lists
In our sample problem, we will want to read the data. Then we will remove the minimum
and compute the total. For example, if the input is 8 7 8.5 9.5 7 5 10, we will remove the mini¬
mum of 5, yielding 8 7 8.5 9.5 7 10. The sum of those values is the final score of 50.
Thus, we have identified three steps:
Read inputs.
Remove the minimum.
Calculate the sum.
Step 2 Determine which algorithm(s) you need.
Sometimes, a step corresponds to exactly one of the basic array algorithms in Section 6.3. That
is the case with calculating the sum (Section 6.3.2) and reading the inputs (Section 6.3.10). At
other times, you need to combine several algorithms. To remove the minimum value, you can
find the minimum value (Section 6.3.3), find its position (Section 6.3.5), and remove the ele¬
ment at that position (Section 6.3.6).
We have now refined our plan as follows:
Read inputs.
Find the minimum.
Find its position.
Remove the minimum.
Calculate the sum.
This plan will work— see Section 6.5. But here is an alternate approach. It is easy to compute
the sum and subtract the minimum. Then we don’t have to find its position. The revised plan is
Read inputs.
Find the minimum.
Calculate the sum.
Subtract the minimum.
Step 3 Use methods to structure the program.
Even though it may be possible to put all steps into the mai n method, this is rarely a good idea.
It is better to make each processing step into a separate method. In our example, we will imple¬
ment three methods:
• readlnputs
• sum
• minimum
The main method simply calls these methods:
double!] scores = readlnputsO;
double total = sum(scores) - mi nimum(scores) ;
System. out. println("Final score: " + total);
Step 4 Assemble and test the program.
Place your methods into a class. Review your code and check that you handle both normal
and exceptional situations. What happens with an empty array? One that contains a single ele¬
ment? When no match is found? When there are multiple matches? Consider these boundary
conditions and make sure that your program works correctly.
In our example, it is impossible to compute the minimum if the array is empty. In that case,
we should terminate the program with an error message before attempting to call the minimum
method.
6.5 Problem Solving: Adapting Algorithms 277
What if the minimum value occurs more than once? That means that a student had more
than one test with the same low score. We subtract only one of the occurrences of that low
score, and that is the desired behavior.
The following table shows test cases and their expected output:
Test Case
Expected Output
Comment
! 7 8.5 9.5 7 5 10
50
See Step 1.
8 7 7 9
24
Only one instance of the low score should be removed.
8
0
After removing the low score, no score remains.
(no inputs)
Error
That is not a legal input.
Here’s the complete program (how_to_l/Scores . j ava):
import java. uti 1 .Arrays ;
import java. util .Scanner;
/**
This program computes a final score for a series of quiz scores: the sum after dropping
the lowest score. The program uses arrays.
*/
public class Scores
{
public static void main(String[] args)
{
doublet] scores = readlnputsO ;
if (scores. length == 0)
{
System. out. println("At least one score is required.");
}
else
{
double total = sum(scores) - minimum(scores) ;
System. out. print! n("Fi nal score: " + total);
}
}
/**
Reads a sequence of floating-point numbers.
©return an array containing the numbers
V
public static doublet] readlnputsO
{
// Read the input values into an array
final int INITIAL_SIZE = 10;
doublet] inputs = new double [INITIAL_SIZE] ;
System. out. println("Please enter values, Q to quit:");
Scanner in = new Scanner(System. in) ;
int currentSize = 0;
while (in.hasNextDoubleO)
{
// Grow the array if it has been completely filled
278 Chapter 6 Arrays and Array Lists
if (currentSize >= i nputs . length)
{
inputs = Arrays. copyOf (inputs, 2 * i nputs . length) ;
}
inputs [currentSize] = i n.nextDoubleO ;
currentSize++;
}
return Arrays. copyOf(inputs, currentSize);
Computes the sum of the values in an array.
@param val ues an array
©return the sum of the values in values
V
public static double sum(double[] values)
{
double total = 0;
for (double element : values)
{
total = total + element;
}
return total ;
Gets the minimum value from an array.
@param values an array of size >= 1
©return the smallest element of values
V
public static double minimum(double[] values)
{
double smallest = val ues [0];
for (int i = 1; i < val ues. length; i++)
{
if (val ues [i] < smallest)
{
smallest = values[i] ;
}
}
return smallest;
}
}
WORKED EXAMPLE 6.1
Rolling the Dice
This Worked Example shows how to analyze a set of die
tosses to see whether the die is “fair”.
© Available online in WileyPLUS and at www.wiley.com/college/horstmann.
6.6 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 279
6.6 Problem Solving: Discovering Algorithms by
Manipulating Physical Objects
Manipulating physical objects
can give you ideas for
discovering algorithms.
In Section 6.5, you saw how to solve a problem by combining and adapting
known algorithms. But what do you do when none of the standard algorithms
is sufficient for your task? In this section, you will learn a technique for dis¬
covering algorithms by manipulating physical objects.
Consider the following task: You are given an array whose size is an even
number, and you are to switch the first and the second half. For example, if the
array contains the eight numbers
9 13 21 4 11 7 1 3
then you should change it to
11 7 1 3 9 13 21 4
Use a sequence of
coins, playing cards
or toys to visualize
an array of values.
Many students find it quite challenging to come up with an algorithm. They may
know that a loop is required, and they may realize that elements should be inserted
(Section 6.3.7) or swapped (Section 6.3.8), but they do not have sufficient intuition to
draw diagrams, describe an algorithm, or write down pseudocode.
One useful technique for discovering an algorithm is to manipulate physical
objects. Start by lining up some objects to denote an array. Coins, playing cards, or
small toys are good choices.
Here we arrange eight coins:
© # ©
Now let’s step back and see what we can do to change the order of the coins.
We can remove a coin (Section 6.3.6):
Visualizing the
removal of an
array element
We can insert a coin (Section 6.3.7):
280 Chapter 6 Arrays and Array Lists
Or we can swap two coins (Section 6.3.8).
Visualizing the
swapping of
m
i
two coins
T
m
^ 9 9
Go ahead— line up some coins and try out these three operations right now so that
you get a feel for them.
Now how does that help us with our problem, switching the first and the second
half of the array?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
Java programmers, we will say that we swap the coins in positions 0 and 4:
\
• # # #
t
S H
<# # #
Next, we swap the coins in positions 1 and 5:
I
® # f
Two more swaps, and we are done:
\
6.6
Problem Solving: Discovering Algorithms by Manipulating Physical Objects 281
ONLINE EXAMPLE
© A program that
implements the
algorithm that
switches the first
and second halves
of an array.
You can use paper
clips as position
markers or counters.
Now an algorithm is becoming apparent:
i * 0
j s ... (we'll think about that in a minute)
While (don't know yet)
Swap elements at positions i and j
i++
j++
Where does the variable j start? When we have eight coins, the coin at position zero is
moved to position 4. In general, it is moved to the middle of the array, or to position
size / 1.
And how many iterations do we make? We need to swap all coins in the first half.
That is, we need to swap size / 1 coins. The pseudocode is
i * 0
j s size / 1
While (i < size / 1 )
Swap elements at positions i and j
i*+
j++
It is a good idea to make a walkthrough of the pseudocode (see Section 4.2). You can
use paper clips to denote the positions of the variables i and j. If the walkthrough is
successful, then we know that there was no “off-by-one” error in the pseudocode.
Self Check 29 asks you to carry out the walkthrough, and Exercise P6.8 asks you to
translate the pseudocode to Java. Exercise R6.28 suggests a different algorithm for
switching the two halves of an array, by repeatedly removing and inserting coins.
Many people find that the manipulation of physical objects is less intimidating
than drawing diagrams or mentally envisioning algorithms. Give it a try when you
need to design a new algorithm!
29. Walk through the algorithm that we developed in this section, using two paper
clips to indicate the positions for i and j. Explain why there are no bounds errors
in the pseudocode.
30. Take out some coins and simulate the following pseudocode, using two paper
clips to indicate the positions for i and j.
i * 0
j * size - 1
While (i * j)
Swap elements at positions i and j
\**
i-
What does the algorithm do?
31 . Consider the task of rearranging all elements in an array so that the even num¬
bers come first. Otherwise, the order doesn’t matter. For example, the array
1 4 14 2 1 3 5 6 23
could be rearranged to
4 2 14 6 1 5 3 23 1
282 Chapter 6 Arrays and Array Lists
32.
33.
Using coins and paperclips, discover an algorithm that solves this task by
swapping elements, then describe it in pseudocode.
Discover an algorithm for the task of Self Check 31 that uses removal and
insertion of elements instead of swapping.
Consider the algorithm in Section 4.7.4 that finds the
largest element in a sequence of inputs — wot the largest
element in an array. Why is this algorithm better visual¬
ized by picking playing cards from a deck rather than
arranging toy soldiers in a sequence?
Practice It Now you can try these exercises at the end of the chapter: R6.28, R6.29, P6.8.
VIDEO EXAMPLE 6.1
Removing Duplicates from an Array
fWILEYO
'PLUS
In this Video Example, we will discover an algorithm for removing duplicates from an array.
6.7 Two-Dimensional Arrays
It often happens that you want to store
collections of values that have a two-
dimensional layout. Such data sets com¬
monly occur in financial and scientific
applications. An arrangement consisting
of rows and columns of values is called a
two-dimensional array, or a matrix.
Let’s explore how to store the example
data shown in Figure 12: the medal counts
of the figure skating competitions at the
2010 Winter Olympics.
Gold
Silver
Bronze
Canada
1
0
1
China
1
1
0
Germany
0
0
1
Korea
1
0
0
Japan
0
1
1
Russia
0
1
1
United States
1
1
0
Figure 12 Figure Skating Medal Counts
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
6.7 Two-Dimensional Arrays 283
Use a two-
dimensional array to
store tabular data.
Syntax 6.3
Individual elements
in a two-dimensional
array are accessed by
using two index
values, array[ i] [j].
6.7.1 Declaring Two-Dimensional Arrays
In Java, you obtain a two-dimensional array by supplying the number of rows and
columns. For example, new int[7] [3] is an array with seven rows and three columns.
You store a reference to such an array in a variable of type i nt [] [] . Here is a complete
declaration of a two-dimensional array, suitable for holding our medal count data:
final int COUNTRIES = 7;
final int MEDALS = S;
i nt [] [] counts = new i nt [COUNTRIES] [MEDALS] ;
Alternatively, you can declare and initialize the array by grouping each row:
int[] [] counts =
{
{ 1, 0, 1 },
{ 1, 1, 0 },
{ 0, 0, 1 },
{ 1, 0, 0 },
{ o, 1, 1 },
{ o, 1, 1 },
{ 1, 1, 0 }
};
As with one-dimensional arrays, you cannot change the size of a two-dimensional
array once it has been declared.
Two-Dimensional Array Declaration
Number of rows
Name Element type / Numberof columns
\ \ / /
doublet] [] tableEntries = new doubl e [7] [3] ;
All values are initialized with 0.
Name
\
i nt [] [] data = {
list of initial values
{ 16, 3, 2, 13 },
{ 5, 10, 11, 8 },
{ 9, 6, 7, 12 },
{4, 15, 14, 1 },
6.7.2 Accessing Elements
To access a particular element in the two-dimensional array, you need to specify two
index values in separate brackets to select the row and column, respectively (see Fig¬
ure 13):
Int medal Count = counts [3] [1] ;
284 Chapter 6 Arrays and Array Lists
To access all elements in a two-dimensional array, you use two nested loops. For
example, the following loop prints all elements of counts:
for (int i = 0; i < COUNTRIES; i++)
{
// Process the i th row
for (int j = 0; j < MEDALS; j++)
{
// Process the j th column in the ith row
System. out . printf ("%8d" , counts [i] [j]) ;
}
System. out. pri ntl n () ; // Start a new line at the end of the row
}
Figure 1 3
Accessing an Element in a
Two-Dimensional Array
Column index
o
1 _ 1
<u
-a
[1]
[2]
[3]
F§
[4]
[5]
Oh
i _ i
counts [3] [1]
6.7.3 Locating Neighboring Elements
Some programs that work with two-dimensional arrays need to locate the elements
that are adjacent to an element. This task is particularly common in games. Figure 14
shows how to compute the index values of the neighbors of an element.
For example, the neighbors of counts [3] [1] to the left and right are counts [3] [0] and
counts [3] [2] . The neighbors to the top and bottom are counts [2] [1] and counts [4] [1] .
You need to be careful about computing neighbors at the boundary of the array.
For example, counts [0] [1] has no neighbor to the top. Consider the task of computing
the sum of the neighbors to the top and bottom of the element count [i] [j]. You need
to check whether the element is located at the top or bottom of the array:
int total = 0;
if (i > 0) { total = total + counts [i - 1] [j] ; }
if (i < ROWS - 1) { total = total + counts [i + 1] [ j ] ; }
[i - 1] [ j - 1] [i - 1] [j] [i - 1] [j + 1]
[i ] [ j - 1] [i] [jl [i] [j + 1]
[i + 1] [j]
Figure 14
Neighboring Locations in a
Two-Dimensional Array
[i + 1] [j - 1]
[i + 1] [j + 1]
6.7 Two-Dimensional Arrays 285
6.7.4 Computing Row and Column Totals
A common task is to compute row or column totals. In our example, the row totals
give us the total number of medals won by a particular country.
Finding the right index values is a bit tricky, and it is a good idea to make a quick
sketch. To compute the total of row i, we need to visit the following elements:
0 MEDALS - 1
[i] [0]
[i] [1]
[i] [2]
As you can see, we need to compute the sum of counts [i ] [ j ] , where j ranges from 0 to
MEDALS - 1. The following loop computes the total:
int total = 0;
for (int j = 0; j < MEDALS; j++)
{
total = total + counts [i ] [ j ] ;
}
On
Tracing a Nested
Loop in a 2D Array
I If \
Computing column totals is similar. Form the sum of counts [i] [j], where i ranges
fromO to COUNTRIES - 1.
int total = 0;
for (int i = 0; i < COUNTRIES; i++)
{
total = total + counts[i] [j] ;
}
column j
[0] [j]
- - 0
[1] [j]
[2] [j]
[3] [j]
[4] [j]
[5] [j]
[6] [j]
- - COUNTRIES
286 Chapter 6 Arrays and Array Lists
6.7.5 Two-Dimensional Array Parameters
When you pass a two-dimensional array to a method, you will want to recover the
dimensions of the array. If val ues is a two-dimensional array, then
• val ues . 1 ength is the number of rows.
• val ues [0] . 1 ength is the number of columns. (See Special Topic 6.4 for an explana¬
tion of this expression.)
For example, the following method computes the sum of all elements in a two-
dimensional array:
public static int sum(int[][] values)
{
int total = 0;
for (int i =0; i < values. length; i++)
{
for (int j = 0; j < val ues [0] .length; j++)
{
total = total + val ues [i ] [ j ] ;
}
}
return total;
}
Working with two-dimensional arrays is illustrated in the following program. The
program prints out the medal counts and the row totals.
section_7/Medals.java
1 /**
2 This program prints a table of medal winner counts with row totals.
3 */
4 public class Medals
5 {
6 public static void main(String[] args)
7 {
8
final int COUNTRIES =
9
final int MEDALS = 3;
10
1 1
Stringf] countries =
12
{
13
"Canada" ,
14
"Chi na" ,
15
"Germany" ,
16
"Korea" ,
17
"Japan ,
18
"Russia" ,
19
"United States"
20
};
21
22
i nt [] [] counts =
23
{
24
{ 1, 0, 1 },
25
{ 1, 1, o },
26
{ 0, 0, 1 },
27
{ 1, o, 0 },
28
{ o, 1, 1 },
29
{ o, 1, 1 },
30
{ 1, 1, o }
6.7 Two-Dimensional Arrays 287
31 };
32
33 System. out. println( Country Cold Silver Bronze Total );
34
35 // Print countries, counts, and row totals
36 for (int i =0; i < COUNTRIES; i++)
37 {
38 // Process the i th row
39 System. out. printf("%15s , countries[i]) ;
40
41 int total = 0;
42
43 // Print each row element and update the row total
44 for (int j = 0 ; j < MEDALS; j++)
45 {
46 System. out. printf( "%8d" , counts [i ] [ j ] ) ;
47 total = total + counts[i] [j] ;
48 }
49
50 // Display the row total and print a new line
51 System. out. printf("%8d\n” , total);
52 }
53 }
54 }
Program Run
Country
Cold
Silver
Bronze
Total
Canada
1
0
1
2
Chi na
1
1
0
2
Germany
0
0
1
1
Korea
1
0
0
1
Japan
0
1
1
2
Russia
0
1
1
2
United States
1
1
0
2
34. What results do you get if you total the columns in our sample data?
35. Consider an 8 x 8 array for a board game:
int[][] board = new int [8] [8];
Using two nested loops, initialize the board so that zeroes and ones alternate, as
on a checkerboard:
01010101
10101010
01010101
10101010
Hint: Check whether i + j is even.
36. Declare a two-dimensional array for representing a tic-tac-toe board. The board
has three rows and columns and contains strings "x", "o", and " ".
37. Write an assignment statement to place an "x" in the upper-right corner of the
tic-tac-toe board in Self Check 36.
38. Which elements are on the diagonal joining the upper-left and the lower-right
corners of the tic-tac-toe board in Self Check 36?
288 Chapter 6 Arrays and Array Lists
Practice It Now you can try these exercises at the end of the chapter: R6.30, P6.18, P6.19.
WORKED EXAMPLE 6.2
A World Population Table
This Worked Example shows how to print world population data in a table with row and col¬
umn headers, and with totals for each of the data columns.
Two-Dimensional Arrays with Variable Row Lengths
When you declare a two-dimensional array with the command
int[] [] a = new int[3] [3] ;
then you get a 3 x 3 matrix that can store 9 elements:
a[0][0] a [0] [1] a [0] [2]
a[l] [0] a[l] [1] all] [2]
a [2 ] [0] a [2] [1] a[2][2]
In this matrix, all rows have the same length.
In Java it is possible to declare arrays in which the row length varies. For example, you can
store an array that has a triangular shape, such as:
b [0] [0]
b [1] [0] b[l][l]
b [2] [0] b [2] [1] b [2] [2]
To allocate such an array, you must work harder. First, you allocate space to hold three rows.
Indicate that you will manually set each row by leaving the second array index empty:
double!] [] b = new doubl e [3] [] ;
Then allocate each row separately (see Figure 15):
for (int i =0; i < b. length; i++)
{
b[i] = new double[i + 1];
}
You can access each array element as b[i] [j]. The expression b[i] selects the ith row, and the
[j] operator selects the jth element in that row.
Figure 15 A Triangular Array
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
6.8 Array Lists 289
Note that the number of rows is b. length, and the length of the ith row is b[i] .length. For
example, the following pair of loops prints a ragged array:
for (int i =0; i < b. length; i++)
{
for (int j = 0; j < b [i ] . length; j++)
{
System. out. print(b[i] [j]) ;
}
System. out. println() ;
}
Alternatively, you can use two enhanced for loops:
for (doublet] row : b)
{
for (double element : row)
{
System . out . pri nt(el ement) ;
}
System. out. println() ;
}
Naturally, such “ragged” arrays are not very common.
Java implements plain two-dimensional arrays in exactly the same way as ragged arrays:
as arrays of one-dimensional arrays. The expression new int [3] [3] automatically allocates an
array of three rows, and three arrays for the rows’ contents.
Multidimensional Arrays
You can declare arrays with more than two dimensions. For example, here is a three-dimen¬
sional array:
int[][][] rubiksCube = new i nt [3] [3] [3] ;
Each array element is specified by three index values:
rubiksCube[i] [j] [k]
6.8 Array Lists
An array list stores
a sequence of
values whose
size can change.
When you write a program that collects inputs, you
don’t always know how many inputs you will have.
In such a situation, an array list offers two significant
advantages:
• Array lists can grow and shrink as needed.
• The Ar ray Li st class supplies methods for common
tasks, such as inserting and removing elements.
In the following sections, you will learn how to work
with array lists.
An array list expands to hold as many elements as needed.
290 Chapter 6 Arrays and Array Lists
Syntax 6.4
The ArrayLi st class
is a generic class:
ArrayLi st <Type>
collects elements of
the specified type.
Before add
names =
Array Lists
Syntax To construct an array list: new ArrayLi st<typeName>0
To access an element:
Variable type Variable name
\
arraylistReference . get (i ndex)
arraylistReference . set (i ndex , val ue)
Am array list object of size 0
ArrayLi st<String> friends = new ArrayLi st<String>() ;
Use the
get and set methods
to access m element.
f ri ends . add("Ci ndy") ;
String name = friends. get(i) ;
friends. set(i , "Harry");
The add method
appends an element to the array list,
increasing its size.
The index must be > 0 and < friends.size().
6.8.1 Declaring and Using Array Lists
The following statement declares an array list of strings:
ArrayLi st<String> names = new ArrayLi st<Stri ng>() ;
The ArrayLi st class is contained in the java, util package. In order to use array lists in
your program, you need to use the statement import java, util .Array List.
The type ArrayLi st<String> denotes an array list of String elements. The angle
brackets around the String type tell you that String is a type parameter. You can
replace String with any other class and get a different array list type. For that reason,
ArrayLi st is called a generic class. However, you cannot use primitive types as type
parameters — there is no ArrayLi st<int> or ArrayList<double>. Section 6.8.5 shows how
you can collect numbers in an array list.
It is a common error to forget the initialization:
ArrayLi st<String> names;
names. add("Harry") ; // Error— names not initialized
Here is the proper initialization:
ArrayLi st<String> names = new ArrayLi st<Stri ng>() ;
Note the () after new ArrayLi st<String> on the right-hand side of the initialization. It
indicates that the constructor of the ArrayLi st<String> class is being called. We will
discuss constructors in Chapter 8.
ArrayLi st<String>
2
Q After add
names =
Size increased
New element
added at end
Figure 16 Adding an Element with add
6.8 Array Lists 291
Use the size method
to obtain the current
size of an array list.
Use the get and set
methods to access an
array list element at a
given index.
Am array list has
methods for adding
and removing ele¬
ments in the middle.
When the ArrayList<Stri ng>is first constructed, it has size 0. You use the add method
to add an element to the end of the array list.
names. add("Emily") ; // Now names has size 1 and element "Emily"
names. add("Bob") ; // Now names has size 2 and elements "Emily", "Bob"
names. add("Cindy") ; // names has size 3 and elements "Emily", "Bob", and "Cindy"
The size increases after each call to add (see Figure 16). The size method yields the
current size of the array list.
To obtain an array list element, use the get method, not the [] operator. As with
arrays, index values start at 0. For example, names . get (2) retrieves the name with index
2, the third element in the array list:
String name = names. get(2) ;
As with arrays, it is an error to access a nonexistent element. A very common bounds
error is to use the following:
int i = names . size() ;
name = names. get(i); // Error
The last valid index is names, si ze() - 1.
To set an array list element to a new value, use the set method.
names. set(2, "Carolyn");
This call sets position 2 of the names array list to "Carolyn", overwriting whatever value
was there before.
The set method overwrites existing values. It is different from the add method,
which adds a new element to the array list.
You can insert an element in the middle of an array list. For example, the call names .
add(l, "Ann") adds a new element at position 1 and moves all elements with index 1 or
larger by one position. After each call to the add method, the size of the array list
increases by 1 (see Figure 17).
Figure 1 7
Adding and
Removing
Elements in the
Middle of an
Array List
Before add
names =
Q After names . add (1, "Ann")
names =
Array Li st<Stri ng>
"Emily"
"Bob "
"Carolyn”
ArrayList<String>
"Emily"
"Ann”
"Bob"
"Carolyn”
Q After names . remove (1)
names =
Ar rayLi st<Stri ng>
"Emily"
Ml
"Bob "
"Carolyn"
New element
added at index 1
Moved from index 1 to 2
Moved from index 2 to 3
Moved from index 2 to 1
Moved from index 3 to 2
292 Chapter 6 Arrays and Array Lists
Use the add and
remove methods to
add and remove
array list elements.
Conversely, the remove method removes the element at a given position, moves all
elements after the removed element down by one position, and reduces the size of the
array list by 1 . Part 3 of Figure 1 7 illustrates the result of names . remove (1) .
With an array list, it is very easy to get a quick printout. Simply pass the array list
to the pri ntl n method:
System. out. println(names); // Prints [Emily, Bob, Carolyn]
6.8.2 Using the Enhanced for Loop with Array Lists
You can use the enhanced for loop to visit all elements of an array list. For example,
the following loop prints all names:
ArrayList<String> names = . . . ;
for (String name : names)
{
System. out. pri ntln (name) ;
}
This loop is equivalent to the following basic for loop:
for (int i = 0; i < names. size() ; i++)
{
String name = names. get(i) ;
System. out. pri ntln (name) ;
}
Table 2 Working with Array Lists
ArrayList<String> names = new ArrayList<Stri ng>() ;
Constructs an empty array list that can
hold strings.
names. add("Ann") ;
names. add("Cindy") ;
Adds elements to the end.
System. out. pri ntl n(names) ;
Prints [Ann, Cindy].
names. add(l, "Bob");
Inserts an element at index 1.
names is now [Ann, Bob, Cindy].
names. remove(O) ;
Removes the element at index 0.
names is now [Bob, Cindy].
names. set(0, "Bill");
Replaces an element with a different value,
names is now [Bill, Ci ndy] .
String name = names. get (i ) ;
Gets an element.
String last = names. get(names.size() - 1);
Gets the last element.
ArrayLi st<Integer> squares = new ArrayLi st<Integer>() ;
for (int i =0; i <10; i++)
{
squares . add (i * i) ;
}
Constructs an array list holding the first
ten squares.
6.8 Array Lists 293
To collect numbers in
array lists, you must
use wrapper classes.
6.8.3 Copying Array Lists
As with arrays, you need to remember that array list variables hold references. Copy¬
ing the reference yields two references to the same array list (see Figure 18).
ArrayLi st<String> friends = names;
friends. add ("Harry") ;
Now both names and friends reference the same array list to which the string "Harry"
was added.
If you want to make a copy of an array list, construct the copy and pass the original
list into the constructor:
ArrayLi st<String> newNames = new ArrayLi st<String>(names);
Figure 18 Copying an Array List Reference
6.8.4 Array Lists and Methods
Like arrays, array lists can be method arguments and return values. Here is an exam¬
ple: a method that receives a list of strings and returns the reversed list.
public static ArrayLi st<Stri ng> reverse(ArrayList<String> names)
{
// Allocate a list to hold the method result
ArrayLi st<String> result = new ArrayLi st<String>() ;
// Traverse the names list in reverse order, starting with the last element
for (int i = names. size() - 1; i >= 0; i--)
{
// Add each name to the result
result. add(names.get(i)) ;
}
return result;
}
If this method is called with an array list containing the names Emily, Bob, Cindy, it
returns a new array list with the names Cindy, Bob, Emily.
6.8.5 Wrappers and Auto-boxing
In Java, you cannot directly insert primitive type values — numbers, characters, or
boolean values — into array lists. For example, you cannot form an ArrayList<double>.
Instead, you must use one of the wrapper classes shown in the following table.
294 Chapter 6 Arrays and Array Lists
Primitive Type
Wrapper Class
byte
Byte
boolean
Boolean
char
Character
double
Double
float
Float
int
Integer
long
Long
short
Short
For example, to collect double values in an array list, you use an ArrayList<Double>.
Note that the wrapper class names start with uppercase letters, and that two of them
differ from the names of the corresponding primitive type: Integer and Character.
Conversion between primitive types and the corresponding wrapper classes is
automatic. This process is called auto-boxing (even though auto-wrapping would
have been more consistent).
For example, if you assign a double value to a Double variable, the number is auto¬
matically “put into a box” (see Figure 19).
Double wrapper = 29.95;
Conversely, wrapper values are automatically “unboxed” to primitive types,
double x = wrapper;
Because boxing and unboxing is automatic, you don’t need to think about it. Simply
remember to use the wrapper type when you declare array lists of numbers. From
then on, use the primitive type and rely on auto-boxing.
ArrayLlst<Double> values = new Arrayl_ist<Double>() ;
values. add(29. 95) ;
double x = values. get(O) ;
wrapper =
Figure 19 A Wrapper Class Variable
Like truffles that must be in a wrapper to be sold,
a number must be placed in a wrapper to be stored in an array list.
6.8 Array Lists 295
6.8.6 Using Array Algorithms with Array Lists
The array algorithms in Section 6.3 can be converted to array lists simply by using the
array list methods instead of the array syntax (see Table 3 onpage 297). For example, this
code snippet finds the largest element in an array:
double largest = values[0];
for (int i = 1; i < values. length; 1++)
{
if (values [i] > largest)
{
largest = values [i] ;
}
}
Here is the same algorithm, now using an array list:
double largest = values. get(O) ;
for (int i = 1; i < values. size() ; i++)
{
if (values. get(i) > largest)
{
largest = values. get(i) ;
}
}
6.8.7 Storing Input Values in an Array List
When you collect an unknown number of inputs, array lists are much easier to use
than arrays. Simply read inputs and add them to an array list:
ArrayLi st<Double> inputs = new ArrayList<Double>() ;
while (in.hasNextDoubleO)
{
inputs. add(in.nextDouble()) ;
}
6.8.8 Removing Matches
It is easy to remove elements from an array list, by calling the remove method. A com¬
mon processing task is to remove all elements that match a particular condition. Sup¬
pose, for example, that we want to remove all strings of length < 4 from an array list.
Of course, you traverse the array list and look for matching elements:
ArrayLi st<String> words = ...;
for (int i = 0; i < words. size() ; i++)
{
String word = words. get(i ) ;
if (word.length() < 4)
{
Remove the element at index i.
}
}
But there is a subtle problem. After you remove the element, the for loop increments
i, skipping past the next element.
296 Chapter 6 Arrays and Array Lists
Consider this concrete example, where words contains the strings "Welcome", "to",
"the", "island!". When i is 1, we remove the word "to" at index 1. Then i is incre¬
mented to 2, and the word "the", which is now at position 1, is never examined.
i
words /
»
"Welcome", "to", "the", "island8-
"Welcome", "the", "island" )
l
\
We should not increment the index when removing a word. The appropriate pseudo¬
code is
If the element at index i matches the condition
Remove the element.
Else
Increment i.
Because we don’t always increment the index, a for loop is not appropriate for this
algorithm. Instead, use awhile loop:
int i = 0;
while (i < words. sizeO)
{
String word = words. get(i) ;
if (word.lengthO < 4)
{
words. remove(i);
}
else
{
i++;
}
}
6.8.9 Choosing Between Array Lists and Arrays
ONLINE EXAMPLE
A version of the
Scores program
using an array list.
For most programming tasks, array lists are easier to use than arrays. Array lists can
grow and shrink. On the other hand, arrays have a nicer syntax for element access and
initialization.
Which of the two should you choose? Here are some recommendations.
• If the size of a collection never changes, use an array.
• If you collect a long sequence of primitive type values and you are concerned
about efficiency, use an array.
• Otherwise, use an array list.
The following program shows how to mark the largest value in a sequence of values.
This program uses an array list. Note how the program is an improvement over the
array versiononpage 265 . This program can process input sequences of arbitrary length.
6.8 Array Lists 297
Table 3 Comparing Array and Array List Operations
Operation
Arrays
Array Lists
Get an element.
x = val ues [4] ;
x = values. get(4)
Replace an element.
values [4] = 35;
values. set(4, 35);
Number of elements.
val ues. length
values. size()
Number of filled elements.
currentSize
(companion variable, see
Section 6.1.3)
values. size()
Remove an element.
See Section 6.3.6
values. remove (4) ;
Add an element, growing
the collection.
See Section 6.3.7
values . add(35) ;
Initializing a collection.
int[] values = { 1, 4, 9 };
No initializer list syntax;
call add three times.
section_8/LargestlnArrayList.java
1 import java. util .ArrayList;
2 import java. util .Scanner;
3
4 /**
5 This program reads a sequence of values and prints them, marking the largest value.
6 */
7 public class LargestlnArrayList
8 {
9 public static void main(String[] args)
10 {
11 ArrayList<Double> values = new ArrayList<Double>() ;
12
13 // Read inputs
14
15 System. out. pri ntl n ('' 31 ease enter values, Q to quit: );
16 Scanner in = new Scanner(System.in) ;
17 while (in.hasNextDouble())
18 {
19 values. add(in. nextDoubleO) ;
20 }
21
22 // Find the largest value
23
24 double largest = values. get(O) ;
25 for (int i = 1; i < values. si ze () ; i++)
26 {
27 if (values. get(i) > largest)
28 {
29 largest = values. get(i) ;
30 }
31 }
32
33
34
// Print all values, marking the largest
298 Chapter 6 Arrays and Array Lists
for (double element : values)
36 {
37 System. out. print(element) ;
38 if (element == largest)
39 {
40 System. out. print( <== largest value");
41 }
42 System. out. printlnO ;
43 }
44 }
45 }
Program Run
Please enter values, Q to quit:
35 80 115 44.5 Q
35
80
115 <== largest value
44.5
39. Declare an array list pri mes of integers that contains the first five prime numbers
(2, 3, 5, 7, and 11).
40. Given the array list pri mes declared in Self Check 39, write a loop to print its ele¬
ments in reverse order, starting with the last element.
41 . What does the array list names contain after the following statements?
ArrayLi st<String> names = new ArrayList<String>;
names. add("Bob") ;
names. add(0, "Ann");
names . remove(l) ;
names. add("Cal") ;
42. What is wrong with this code snippet?
ArrayLi st<String> names;
names. add(Bob) ;
43. Consider this method that appends the elements of one array list to another,
public static void append(ArrayList<String> target, ArrayLi st<String> source)
{
for (int i = 0; i < source. size(); i++)
{
target. add(source.get(i)) ;
}
}
What are the contents of namesl and names2 after these statements?
ArrayLi st<String> namesl = new ArrayLi st<Stri ng>() ;
namesl. add("Emily") ;
namesl. add("Bob") ;
namesl. add ("Cindy");
ArrayLi st<String> names2 = new ArrayLi st<Stri ng>() ;
names2 . add("Dave") ;
append(namesl, names2);
44. Suppose you want to store the names of the weekdays. Should you use an array
list or an array of seven strings?
6.8 Array Lists 299
45. The section_8 directory of your source code contains an alternate implementa¬
tion of the problem solution in How To 6.1 on page 275. Compare the array and
array list implementations. What is the primary advantage of the latter?
Practice It Now you can try these exercises at the end of the chapter: R6.10, R6.34, P6.21,
P6.23.
Length and Size
Unfortunately, the Java syntax for determining the number of elements in an array, an array
list, and a string is not at all consistent.
Data Type
Number of Elements
Array
a. length
Array list
a.sizeO
String
a.lengthO
It is a common error to confuse these. You just have to remember the correct syntax for every
data type.
The Diamond Syntax in Java 7
Java 7 introduces a convenient syntax enhancement for declaring array lists and other generic
classes. In a statement that declares and constructs an array list, you need not repeat the type
parameter in the constructor. That is, you can write
ArrayList<String> names = new ArrayList<>() ;
instead of
ArrayList<String> names = new ArrayList<String>() ;
This shortcut is called the “diamond syntax” because the empty brackets <> look like a dia¬
mond shape.
VIDEO EXAMPLE 6.2
Game of Life
^WILEYO
rPLUS
Conway’s Game of Life simulates the growth of a population,
using only two simple rules. This Video Example shows you how
to implement this famous “game”.
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
300 Chapter 6 Arrays and Array Lists
CHAPTER SUMMARY
Use arrays for collecting values.
Li. i.
372 j 373 j J74
• An array collects a sequence of values of the same type.
• Individual elements in an array are accessed by an integer index i , using the
notation array [i ] .
• An array element can be used like any variable.
• An array index must be at least zero and less than the size of the array.
• A bounds error, which occurs if you supply an invalid array index, can cause your
program to terminate.
• Use the expression array. length to find the number of elements in an
array.
• An array reference specifies the location of an array. Copying the
reference yields a second reference to the same array.
• With a partially filled array, keep a companion variable for the
current size.
Know when to use the enhanced for loop.
• You can use the enhanced for loop to visit all elements of an array.
• Use the enhanced for loop if you do not need the index values in the loop body.
Know and use common array algorithms.
• When separating elements, don’t place a separator before the first element.
• A linear search inspects elements in sequence until a match is found.
• Before inserting an element, move elements to the end of the array starting with
the last one.
• Use a temporary variable when swapping two elements.
• Use the Arrays . copyOf method to copy the elements of an array into a new array.
Implement methods that process arrays.
• Arrays can occur as method arguments and return values.
Combine and adapt algorithms for solving a programming problem.
• By combining fundamental algorithms, you can solve complex programming
tasks.
• You should be familiar with the implementation of fundamental algorithms so
that you can adapt them.
Discover algorithms by manipulating physical objects.
• Use a sequence of coins, playing cards, or toys to visualize an array of values.
• You can use paper clips as position markers or counters.
Review Exercises 301
Use two-dimensional arrays for data that is arranged in rows and columns.
• Use a two-dimensional array to store tabular data.
• Individual elements in a two-dimensional array are
accessed by using two index values, array [i ] [ j ] -
Use array lists for managing collections whose size can change.
An array list stores a sequence of values whose size can change.
The ArrayList class is a generic class: Arrayl_ist<7ype> collects elements of the
specified type.
Use the si ze method to obtain the current size of an array list.
Use the get and set methods to access an array list element
at a given index.
Use the add and remove methods to add and remove array
list elements.
To collect numbers in array lists, you must use wrapper
classes.
STANDARD LIBRARY ITEMS INTRODUCED IN THIS CHAPTER
java. Tang. Boolean
java. lang. Double
java. lang. Integer
java. util .Arrays
copyOf
toStri ng
java. util .ArrayList<E>
add
get
remove
set
size
REVIEW EXERCISES
rite code that fills
an array val ues with each set of numbers below.
a. 1
2
3
4
5
6
7
8
9
10
b. 0
2
4
6
8
10
12
14
16
18 20
c. 1
4
9
16
25
36
49
64
81
100
d. 0
0
0
0
0
0
0
0
0
0
e. 1
4
9
16
9
7
4
9
11
f. 0
1
0
1
0
1
0
1
0
1
g- o
1
2
3
4
0
1
2
3
4
302 Chapter 6 Arrays and Array Lists
■ ■ R6.2 Consider the following array:
i nt [] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 };
What is the value of total after the following loops complete?
a. int total = 0;
for (int i = 0; i < 10; i++) { total = total + a[i]; }
b. int total = 0;
for (int i =0; i <10; i = i +2) { total = total + a [i ] ; }
C. int total = 0;
for (int i = 1; i < 10; i = i + 2) { total = total + a [ i ] ; }
d int total = 0;
for (int i =2; i <=10; i++) { total = total + a [i ] ; }
e, int total = 0;
for (int i = 1; i < 10; i = 2 * i) { total = total + a [ i ] ; }
f. int total = 0;
for (int i = 9; i >= 0; i — ) { total = total + a [i ] ; }
g int total = 0;
for (int i = 9; i >= 0; i = i - 2) { total = total + a [ i ] ; }
h int total = 0;
for (int i = 0; i < 10; i++) { total = a [i ] - total; }
■ ■ R6.3 Consider the following array:
i nt [] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 };
What are the contents of the array a after the following loops complete?
a. for (int i = 1; i < 10; i++) { a [i ] = a[i -1]; }
b. for (int i =9; i >0; i--) { a [i ] = a[i - 1] ; }
C. for (int i = 0; i < 9; i++) { a [i ] = a[i + 1] ; }
d. for (int i = 8; i >= 0; i--) { a [i ] = a[i + 1]; }
e. for (int i = 1; i < 10; i++) { a [i ] = a [i ] + a [i -1]; }
f. for (int i =1; i <10; i = i +2) { a [ i ] =0; }
g. for (int i =0; i <5; i++) { a[i +5] = a [i ] ; }
h. for (int i = 1; i < 5; i++) { a [i ] = a[9 - i ] ; }
■ ■ ■ R6.4 Write a loop that fills an array val ues with ten random numbers between 1 and 1 00.
Write code for two nested loops that fill val ues with ten different random numbers
between 1 and 100.
■ ■ R6.5 Write Java code for a loop that simultaneously computes both the maximum and
minimum of an array.
. R6.6 What is wrong with each of the following code segments?
a. i nt [] values = new int [10] ;
for (int i =1; i <=10; i++)
{
val ues [i] = i * i ;
}
b. i nt [] values;
for (int i = 0; i < values. length; i++)
{
val ues [i] = i * i ;
}
Review Exercises 303
■ R6.7 Write enhanced for loops for the following tasks.
a. Printing all elements of an array in a single row, separated by spaces.
b. Computing the product of all elements in an array.
c. Counting how many elements in an array are negative.
■ R6.8 Rewrite the following loops without using the enhanced for loop construct. Here,
val ues is an array of floating-point numbers.
a. for (double x : values) { total = total + x; }
b. for (double x : values) { if (x == target) { return true; } }
C. int i =0;
for (double x : values) { values[i] = 2 * x; i++; }
■ R6.9 Rewrite the following loops, using the enhanced for loop construct. Here, val ues is
an array of floating-point numbers.
a. for (int i =0; i < val ues. length; i++) { total = total + val ues [i]; }
b. for (int i = 1; i < values. length; i++) { total = total + values[i]; }
C. for (int i =0; i < val ues. length; i++)
{
if (val ues [i] == target) { return i; }
}
R6.10 What is wrong with each of the following code segments?
a. ArrayList<int> values = new ArrayList<int>() ;
b. ArrayLi st<Integer> values = new ArrayListO;
C. ArrayLi st<Integer> values = new ArrayLi st<Integer>;
d. ArrayLi st<Integer> values = new ArrayLi st<Integer>() ;
for (int i =1; i <=10; i++)
{
values. set(i - 1, i * i);
}
e. ArrayLi st<Integer> values;
for (int i =1; i <=10; i++)
{
val ues. add (i * i) ;
}
R6.ll What is an index of an array? What are the legal index values? What is a bounds
error?
R6. 1 2 Write a program that contains a bounds error. Run the program. What happens on
your computer?
R6. 1 3 Write a loop that reads ten numbers and a second loop that displays them in the
opposite order from which they were entered.
R6.14 Trace the flow of the linear search loop in Section 6.3.5, where values contains the
elements 80 90 100 120 1 10. Show two columns, for pos and found. Repeat the trace
when values contains 80 90 100 70.
R6.1 5 Trace both mechanisms for removing an element described in Section 6.3.6. Use an
array values with elements 1 10 90 100 120 80, and remove the element at index 2.
304 Chapter 6 Arrays and Array Lists
■ ■ R6. 1 6 For the operations on partially filled arrays below, provide the header of a method.
Do not implement the methods.
a. Sort the elements in decreasing order.
b. Print all elements, separated by a given string.
c. Count how many elements are less than a given value.
d. Remove all elements that are less than a given value.
e. Place all elements that are less than a given value in another array.
■ R6.1 7 Trace the flow of the loop in Section 6.3.4 with the given example. Show two col¬
umns, one with the value of i and one with the output.
■ R6. 1 8 Consider the following loop for collecting all elements that match a condition; in
this case, that the element is larger than 100.
Arrayl_ist<Double> matches = new ArrayList<Double>() ;
for (double element : values)
{
if (element > 100)
{
matches. add(element) ;
}
}
Trace the flow of the loop, where values contains the elements 110 90 100 120 80.
Show two columns, for el ement and matches.
■ R6.1 9 Trace the flow of the loop in Section 6.3.5, where values contains the elements 80
90 100 120 1 10. Show two columns, for pos and found. Repeat the trace when values
contains the elements 80 90 120 70.
■ ■ R6.20 Trace the algorithm for removing an element described in Section 6.3.6. Use an array
values with elements 110 90 100 120 80, and remove the element at index 2.
■ ■ R6.2 1 Give pseudocode for an algorithm that rotates the elements of an array by one posi¬
tion, moving the initial element to the end of the array, like this:
2 3 5 7 11 13
3 5 7 11 13 2
■ ■ R6.22 Give pseudocode for an algorithm that removes all negative values from an array,
preserving the order of the remaining elements.
■ ■ R6.23 Suppose val ues is a sorted array of integers. Give pseudocode that describes how
a new value can be inserted in its proper position so that the resulting array stays
sorted.
■ ■ ■ R6.24 A run is a sequence of adjacent repeated values. Give pseudocode for computing the
length of the longest run in an array. For example, the longest run in the array with
elements
12553124322223655631
has length 4.
Review Exercises 305
R6.2 5 What is wrong with the following method that aims to fill an array with random
numbers?
public static void fillWithRandomNumbers(double[] values)
{
doublet] numbers = new double[values. length] ;
for (int i = 0; i < numbers. length; i++)
{
numbers [i] = Math . randomO ;
}
values = numbers;
}
R6.26 You are given two arrays denoting x- andy-coordinates of a set of
points in the plane. For plotting the point set, we need to know the
x- and y-coordinates of the smallest rectangle containing the
points.
How can you obtain these values from the fundamental algorithms
in Section 6.3?
R6.2 7 Solve the problem described in Section 6.5 by sorting the array first. How do you
need to modify the algorithm for computing the total?
R6.28 Solve the task described in Section 6.6 using an algorithm that removes and inserts
elements instead of switching them. Write the pseudocode for the algorithm, assum¬
ing that methods for removal and insertion exist. Act out the algorithm with a
sequence of coins and explain why it is less efficient than the swapping algorithm
developed in Section 6.6.
R6.29 Develop an algorithm for finding the most frequently occurring value in an array of
numbers. Use a sequence of coins. Place paper clips below each coin that count how
many other coins of the same value are in the sequence. Give the pseudocode for an
algorithm that yields the correct answer, and describe how using the coins and paper
clips helped you find the algorithm.
R6.30 Write Java statements for performing the following tasks with an array declared as
int[][] values = new i nt [ROWS] [COLUMNS] ;
• Fill all entries with 0.
• Fill elements alternately with Os and Is in a checkerboard pattern.
• Fill only the elements at the top and bottom row with zeroes.
• Compute the sum of all elements.
• Print the array in tabular form.
R6.31 Write pseudocode for an algorithm that fills the first and last column as well as the
first and last row of a two-dimensional array of integers with -1 .
R6.32 Section 6.8.8 shows that you must be careful about updating the index value when
you remove elements from an array list. Show how you can avoid this problem by
traversing the array list backwards.
306 Chapter 6 Arrays and Array Lists
.. R6.33 True or false?
a. All elements of an array are of the same type.
b. Arrays cannot contain strings as elements.
c. Two-dimensional arrays always have the same number of rows and columns.
d. Elements of different columns in a two-dimensional array can have
different types.
e. A method cannot return a two-dimensional array.
f . A method cannot change the length of an array argument.
g. A method cannot change the number of columns of an argument that is a
two-dimensional array.
■ ■ R6.34 How do you perform the following tasks with array lists in Java?
a. Test that two array lists contain the same elements in the same order.
b. Copy one array list to another.
c. Fill an array list with zeroes, overwriting all elements in it.
d. Remove all elements from an array list.
■ R6.35 True or false?
a. All elements of an array list are of the same type.
b. Array list index values must be integers.
c. Array lists cannot contain strings as elements.
d. Array lists can change their size, getting larger or smaller.
e. A method cannot return an array list.
f . A method cannot change the size of an array list argument.
PROGRAMMING EXERCISES
■ ■ P6. 1 Write a program that initializes an array with ten random integers and then prints
four lines of output, containing
• Every element at an even index.
• Every even element.
• All elements in reverse order.
• Only the first and last element.
■ ■ P6.2 Write array methods that carry out the following tasks for an array of integers. For
each method, provide a test program.
a. Swap the first and last elements in the array.
b. Shift all elements by one to the right and move the last element into the first
position. For example, 1 4 9 16 25 would be transformed into 25 1 4 9 16.
c. Replace all even elements with 0.
d. Replace each element except the first and last by the larger of its two neighbors.
Programming Exercises 307
e. Remove the middle element if the array length is odd, or the middle two
elements if the length is even.
f . Move all even elements to the front, otherwise preserving the order of the
elements.
g. Return the second-largest element in the array.
h. Return true if the array is currently sorted in increasing order.
i. Return true if the array contains two adjacent duplicate elements.
j. Return true if the array contains duplicate elements (which need not be
adjacent).
■ P6.3 Modify the LargestlnArray . java program in Section 6.3 to mark both the smallest and
the largest elements.
■ P6.4 Write a method sumWi thoutSmal 1 est that computes the sum of an array of values,
except for the smallest one, in a single loop. In the loop, update the sum and the
smallest value. After the loop, return the difference.
■ P6.5 Write a method public static void removeMi n that removes the minimum value from a
partially filled array without calling other methods.
■ P6.6 Compute the alternating sum of all elements in an array. For example, if your pro¬
gram reads the input
1 4 9 16 9 7 4 9 11
then it computes
1-4 + 9- 16 + 9-7 + 4-9 + 11= -2
■ P6.7 Write a method that reverses the sequence of elements in an array. For example, if
you call the method with the array
I 4 9 16 9 7 4 9 11
then the array is changed to
II 9 4 7 9 16 9 4 1
■ P6.8 Write a method that implements the algorithm developed in Section 6.6.
■ P6.9 Write a method
public static boolean equals(int[] a, i n t [ ] b)
that checks whether two arrays have the same elements in the same order.
P6. 1 0 Write a method
public static boolean sameSet(int[] a, int[] b)
that checks whether two arrays have the same elements in some order, ignoring
duplicates. For example, the two arrays
1 4 9 16 9 7 4 9 11
and
11 11 7 9 16 4 1
would be considered identical. You will probably need one or more helper methods.
308 Chapter 6 Arrays and Array Lists
■ ■ ■ P6. 11 Write a method
public static boolean sameElements(int[] a, int[] b)
that checks whether two arrays have the same elements in some order, with the same
multiplicities. For example,
1 49 16 9749 11
and
11 1 4 9 16 9 7 4 9
would be considered identical, but
and
1 4 9 16 9 7 4 9 11
11 11 7 9 16 4 1 4 9
would not. You will probably need one or more helper methods.
■ ■ P6.12 A run is a sequence of adjacent repeated values. Write a program that generates a
sequence of 20 random die tosses in an array and that prints the die values, marking
the runs by including them in parentheses, like this:
1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1
Use the following pseudocode:
Set a boolean variable inRun to false.
For each valid index i in the array
If inRun
If values[i] is different from the preceding value
Print ).
inRun * false.
If not inRun
If values[i] is the same as the following value
Print (.
inRun = true.
Print valuesfi].
If inRun, print ).
■ ■ P6. 1 3 Write a program that generates a sequence of 20 random die tosses in an array and
that prints the die values, marking only the longest run, like this:
1 2 5 5 3 1 2 4 3 (2 2 2 2) 3 6 5 5 6 3 1
If there is more than one run of maximum length, mark the first one.
■ ■ P6. 1 4 Write a program that generates a sequence of 20 random values between 0 and 99 in
an array, prints the sequence, sorts it, and prints the sorted sequence. Use the sort
method from the standard Java library.
■ ■ ■ P6.1 5 Write a program that produces ten random permutations of the numbers 1 to 10. To
generate a random permutation, you need to fill an array with the numbers 1 to 10
so that no two entries of the array have the same contents. You could do it by brute
force, by generating random values until you have a value that is not yet in the array.
But that is inefficient. Instead, follow this algorithm.
Programming Exercises 309
Make a second array and fill it with the numbers 1 to 1 0.
Repeat 1 0 times
Pick a random element from the second array.
Remove it and append it to the permutation array.
P6.16 It is a well-researched fact that men in a restroom generally prefer to maximize
their distance from already occupied stalls, by occupying the middle of the longest
sequence of unoccupied places.
For example, consider the situation where ten stalls are empty.
The first visitor will occupy a middle position:
_ X _
The next visitor will be in the middle of the empty area at the left.
__X__X _
Write a program that reads the number of stalls and then prints out diagrams in the
format given above when the stalls become filled, one at a time. Hint: Use an array of
bool ean values to indicate whether a stall is occupied.
P6. 1 7 In this assignment, you will model the game of Bulgarian Solitaire. The game starts
with 45 cards. (They need not be playing cards. Unmarked index cards work just as
well.) Randomly divide them into some number of piles of random size. For exam¬
ple, you might start with piles of size 20, 5, 1, 9, and 10. In each round, you take one
card from each pile, forming a new pile with these cards. For example, the sample
starting configuration would be transformed into piles of size 19, 4, 8, 9, and 5. The
solitaire is over when the piles have size 1, 2, 3, 4, 5, 6, 7, 8, and 9, in some order. (It
can be shown that you always end up with such a configuration.)
In your program, produce a random starting configuration and print it. Then keep
applying the solitaire step and print the result. Stop when the solitaire final configu¬
ration is reached.
P6.18 Magic squares. An n x n matrix that is filled with the numbers 1, 2, 3, . . ., n2 is a
magic square if the sum of the elements in each row, in each column, and in the two
diagonals is the same value.
16
3
2
13
5
10
11
8
9
6
7
12
4
15
14
1
Write a program that reads in 16 values from the keyboard and tests whether they
form a magic square when put into a 4 x 4 array. You need to test two features:
1. Does each of the numbers 1,2, ..., 16 occur in the user input?
2. When the numbers are put into a square, are the sums of the rows, columns,
and diagonals equal to each other?
310 Chapter 6 Arrays and Array Lists
■ ■ ■ P6. 1 9 Implement the following algorithm to construct magic n x n squares; it works only if
n is odd.
Set row * h - 1, column * n / 1.
For k = 1 ... n * n
Place k at [row][column].
Increment row and column.
If the row or column is n, replace it with 0.
If the element at [row][column] has already been filled
Set row and column to their previous values,
decrement row.
Here is the 5x5 square that you get if you follow this method:
11
18
25
2
9
10
12
19
21
3
4
6
13
20
22
23
5
7
14
16
17
24
1
8
15
Write a program whose input is the number n and whose output is the magic square
of order n if n is odd.
■ ■ P6.20 Write a method that computes the average of the neighbors of a two-dimensional
array element in the eight directions shown in Figure 14.
public static double neighborAverage(int[] [] values, int row, int column)
However, if the element is located at the boundary of the array, only include the
neighbors that are in the array. For example, if row and col umn are both 0, there are
only three neighbors.
■ ■ P6.2 1 Write a program that reads a sequence of input values and displays a bar chart of the
values, using asterisks, like this:
**********************
****************************************
* * * * * * * * * * * * * ******** * * * * * * *
* * * * * * ****** * ******** * * * * *
**************
You may assume that all values are positive. First figure out the maximum value.
That value’s bar should be drawn with 40 asterisks. Shorter bars should use propor¬
tionally fewer asterisks.
■ ■ ■ P6.22 Improve the program of Exercise P6.21 to work correctly when the data set contains
negative values.
■ ■ P6.23 Improve the program of Exercise P6.21 by adding captions for each bar. Prompt the
user for the captions and data values. The output should look like this:
Egypt 4
France *
Japan *
Uruguay *
Switzerland *
**************** *
*****************
*****************
*****************
*************
****************
******
**********
********
Programming Exercises 311
P6.24 A theater seating chart is implemented as a two-dimensional array of ticket prices,
like this:
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 20 20 20 20 20 20 10 10
10 10 20 20 20 20 20 20 10 10
10 10 20 20 20 20 20 20 10 10
20 20 30 30 40 40 30 30 20 20
20 30 30 40 50 50 40 30 30 20
30 40 50 50 50 50 50 50 40 30
Write a program that prompts users to
pick either a seat or a price. Mark sold
seats by changing the price to 0. When
a user specifies a seat, make sure it is
available. When a user specifies a price,
find any seat with that price.
P6.2 5 Write a program that plays tic-tac-toe. The tic-tac-toe
game is played on a 3 x 3 grid as in the photo at right. The
game is played by two players, who take turns. The first
player marks moves with a circle, the second with a cross.
The player who has formed a horizontal, vertical, or diag¬
onal sequence of three marks wins. Your program should
draw the game board, ask the user for the coordinates of
the next mark, change the players after every successful
move, and pronounce the winner.
P6.26 Write a method
public static ArrayLi st<Integer> append(ArrayList<Integer> a, ArrayList<Integer> b)
that appends one array list after another. For example, if a is
and b is
1 4 9 16
9 7 4 9 11
then append returns the array list
1 4 9 16 9 7 4 9
11
P6.27 Write a method
public static ArrayLi st<Integer> merge(ArrayLi st<Integer> a, ArrayLi st<Integer> b)
that merges two array lists, alternating elements from both array lists. If one array
list is shorter than the other, then alternate as long as you can and then append the
remaining elements from the longer array list. For example, if a is
and b is
then merge returns the array list
1 9
1 4 9 16
9 7 4 9 11
4 7 9 4 16 9
11
312 Chapter 6 Arrays and Array Lists
■ ■ P6.28 Write a method
public static ArrayLi st<Integer> mergeSorted(ArrayList<Integer> a,
ArrayLi st<Integer> b)
that merges two sorted array lists, producing a new sorted array list. Keep an index
into each array list, indicating how much of it has been processed already. Each time,
append the smallest unprocessed element from either array list, then advance the
index. For example, if a is
14 9 16
and b is
4 7
then mergeSorted returns the array list
14 4 7
9
9
9 11
9 9 11
16
■ ■ Business P6.29 A pet shop wants to give a discount to its
clients if they buy one or more pets and
at least five other items. The discount is
equal to 20 percent of the cost of the other
items, but not the pets.
Implement a method
public static void discount(double[] prices, boolean!] isPet, int nltems)
The method receives information about a particular sale. For the ith item, pri ces [i ] is
the price before any discount, and isPet [i] is true if the item is a pet.
Write a program that prompts a cashier to enter each price and then a Y for a pet or N
for another item. Use a price of -1 as a sentinel. Save the inputs in an array. Call the
method that you implemented, and display the discount.
■ ■ Business P6.30 A supermarket wants to reward its best customer of each day, showing the custom¬
er’s name on a screen in the supermarket. For that purpose, the customer’s purchase
amount is stored in an ArrayLi st<Doubl e> and the customer’s name is stored in a cor¬
responding ArrayLi st<Stri ng>.
Implement a method
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayLi st<String> customers)
that returns the name of the customer with the largest sale.
Write a program that prompts the cashier to enter all prices and names, adds them to
two array lists, calls the method that you implemented, and displays the result. Use a
price of 0 as a sentinel.
■ ■ ■ Business P6.31 Improve the program of Exercise P6.30 so that it displays the top customers, that
is, the topN customers with the largest sales, where topN is a value that the user of the
program supplies.
Implement a method
public static ArrayLi st<String> nameOfBestCustomers(ArrayList<Double> sales,
ArrayLi st<String> customers, int topN)
If there were fewer than topN customers, include all of them.
Programming Exercises 313
Science P6.32 Sounds can be represented by an array of “sample
values” that describe the intensity of the sound at a
point in time. The program ch06/sound/SoundEffect.
java reads a sound file (in WAV format), calls a
method process for processing the sample values, and
saves the sound file. Your task is to implement the
process method by introducing an echo. For each
sound value, add the value from 0.2 seconds ago.
Scale the result so that no value is larger than 32767.
Science P6.33 You are given a two-dimensional array of values that give the height of a terrain at
different points in a square. Write a method
public static void floodMap(double[] [] heights, double waterLevel)
that prints out a flood map, showing which of the points in the terrain would be
flooded if the water level was the given value. In the flood map, print a * for each
flooded point and a space for each point that is not flooded.
Here is a sample map:
* * * * * *
***** * * *
* * * * * *
* * * * * *
* * * * * * * *
**********
* * * * *
* * * * * *
Then write a program that reads one hundred terrain height values and shows how
the terrain gets flooded when the water level increases in ten steps from the lowest
point in the terrain to the highest.
Science P6.34 Sample values from an experiment often need to be smoothed out. One simple
approach is to replace each value in an array with the average of the value and its
two neighboring values (or one neighboring value if it is at either end of the array).
Implement a method
public static void smooth (doublet] values, int size)
that carries out this operation. You should not create another array in your solution.
Science P6.35 Modify the ch06/animation/BlockAnimation. java program to show an animated sine
wave. In the z'th frame, shift the sine wave by i degrees.
Science P6.36 Write a program that models the movement of an object
with mass m that is attached to an oscillating spring. Unstretched
When a spring is displaced from its equilibrium posi- spring
tion by an amount x, Hooke’s law states that the restor¬
ing force is
F = -kx
where k is a constant that depends on the spring. (Use
10 N/m for this simulation.)
Start with a given displacement x (say, 0.5 meter). Set
the initial velocity v to 0. Compute the acceleration a
314 Chapter 6 Arrays and Array Lists
from Newton’s law ( F = ma) and Hooke’s law, using a mass of 1 kg. Use a small time
interval At = 0.01 second. Update the velocity — it changes by a At. Update the
displacement — it changes by vAt.
Every ten iterations, plot the spring displacement as a bar, where 1 pixel represents
1 cm. Use the technique in Special Topic 4.3 for creating an image.
■ ■ Graphics P6.37 Using the technique of Special Topic 4.3, generate the image of a checkerboard.
■ Graphics P6.38 Using the technique of Special Topic 4.3, generate the image of a sine wave. Draw a
line of pixels for every five degrees.
ANSWERS TO SELF-CHECK QUESTIONS
1. int[] primes = { 2, 3, 5, 7, 11};
2. 2, 3, 5, 3, 2
3. 3, 4, 6, 8, 12
4. values [0] = 10;
values [9] = 10;
or better: values [values, length - 1] = 10;
5. String [] words = new String [10];
6. String [] words = { "Yes", "No" };
7. No. Because you don’t store the values, you
need to print them when you read them. But
you don’t know where to add the <= until you
have seen all values.
8. It counts how many elements of val ues are
zero.
9. for (double x : values)
{
System. out. println(x) ;
}
10. double product = 1;
for (double f : factors)
{
product = product * f;
Answers to Self-Check Questions 315
}
1 1 . The loop writes a value into val ues [i ] . The
enhanced for loop does not have the index
variable i .
12. 20 <== largest value
10
20 <== largest value
13. int count = 0;
for (double x : values)
{
if (x == 0) { count++; }
}
1 4. If all elements of val ues are negative, then the
result is incorrectly computed as 0.
1 5. for (int i = 0; i < val ues. length; i++)
{
System . out .print (val ues [i ] ) ;
if (i < values. length - 1)
{
System. out. print(" | ");
}
}
Now you know why we set up the loop the
other way.
1 6. If the array has no elements, then the program
terminates with an exception.
1 7. If there is a match, then pos is incremented
before the loop exits.
1 8. This loop sets all elements to val ues [pos] .
19. int[] numbers = squares(5);
20. public static void fill (int[] values, int value)
{
for (int i = 0; i < val ues. length; i++)
{
val ues [i] = value; }
}
2 1 . The method returns an array whose length is
given in the first argument. The array is filled
with random integers between 0 and n - 1 .
22. The contents of scores is unchanged. The
reverse method returns a new array with the
reversed numbers.
values
result
T1
[1. 4. 9]
-[0rU<U
#
r
-I W
i
[9.4,1]
_
24. Use the first algorithm. The order of elements
does not matter when computing the sum.
25. Find the minimum value.
Calculate the sum.
Subtract the minimum value.
26. Use the algorithm for counting matches
(Section 4.7.2) twice, once for counting the
positive values and once for counting the
negative values.
2 7. You need to modify the algorithm in
Section 6.3.4.
boolean fi rst = true;
for (int i =0; i < val ues. length; i++)
{
if (val ues [i] >0))
{
if (first) { first = false; }
else { System. out. print(", "); }
}
System. out. print(values[i]) ;
}
Note that you can no longer use i > 0 as the
criterion for printing a separator.
28. Use the algorithm to collect all positive ele¬
ments in an array, then use the algorithm in
Section 6.3.4 to print the array of matches.
29. The paperclip for i assumes positions 0, 1, 2,
3. When i is incremented to 4, the condition
i < size / 1 becomes false, and the loop ends.
Similarly, the paperclip for j assumes positions
4, 5, 6, 7, which are the valid positions for the
second half of the array.
• 04
9 9
30. It reverses the elements in the array.
31. Here is one solution. The basic idea is to move
all odd elements to the end. Put one paper clip
at the beginning of the array and one at the
end. If the element at the first paper clip is odd,
swap it with the one at the other paper clip and
move that paper clip to the left. Otherwise,
move the first paper clip to the right. Stop
when the two paper clips meet. Here is the
pseudocode:
i = 0
j * size - 1
316 Chapter 6 Arrays and Array Lists
While (i < j)
If (a[i] is odd)
Swap elements at positions i and j.
j"
Else
i++
32. Here is one solution. The idea is to remove
all odd elements and move them to the end.
The trick is to know when to stop. Nothing is
gained by moving odd elements into the area
that already contains moved elements, so we
want to mark that area with another paper clip.
i * 0
moved = size
While (i < moved)
If (a[i] is odd)
Remove the element at position i and add it
at the end.
moved-
33. When you read inputs, you get to see values
one at a time, and you can’t peek ahead. Pick¬
ing cards one at a time from a deck of cards
simulates this process better than looking at a
sequence of items, all of which are revealed.
34. You get the total number of gold, silver, and
bronze medals in the competition. In our
example, there are four of each.
35. for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
board[i] [j] = (i + j) % 2;
}
36. String[] [] board = new String [3] [S] ;
37. board[0] [2] = "x";
38. board[0] [0], board[l] [1], board[2] [2]
39. ArrayList<Integer> primes =
new ArrayList<Integer>() ;
primes. add(2) ;
primes. add(3) ;
primes. add(5) ;
primes. add(7) ;
primes. add (11) ;
40. for (int i = primes. size() - 1; i >= 0; i — )
{
System . out . pri nt] n (pri mes . get (i ) ) ;
}
41. "Ann", "Cal"
42. The names variable has not been initialized.
43. namesl contains “Emily”, “Bob”, “Cindy”,
“Dave”; names2 contains “Dave”
44. Because the number of weekdays doesn’t
change, there is no disadvantage to using an
array, and it is easier to initialize:
String!] weekdayNames = { "Monday", "Tuesday",
"Wednesday", "Thursday", “Friday”,
"Saturday", "Sunday" };
45. Reading inputs into an array list is much easier.
}
CHAPTER
7
INPUT/OUTPUT
AND EXCEPTION
HANDLING
CHAPTER COALS
To read and write text files
To process command line arguments
To throw and catch exceptions
To implement programs that propagate checked exceptions
CHAPTER CONTENTS
7.1 READING AND WRITING TEXT
FILES 318
Common Error 7.1 : Backslashes in
File Names 32 1
Common Error 7.2 : Constructing a Scanner
with a String 321
Special Topic 7.1 : Reading Web Pages 321
Special Topic 7.2: File Dialog Boxes 321
Special Topic 7.3: Reading and Writing
Binary Data 322
7.2 TEXT INPUT AND OUTPUT 323
Special Topic 7.4: Regular Expressions 330
Video Example 7.1 : Computing a Document's
Readability ©
7.3 COMMAND LINE ARGUMENTS 330
How To 7. 1: Processing Text Files 333
Random Fact 7.1 : Encryption Algorithms 336
Worked Example 7.1 : Analyzing Baby Names ©
7.4 EXCEPTION HANDLING 337
Syntax 7.1 : Throwing an Exception 338
Syntax 7.2: Catching Exceptions 341
Syntax 7.3: The throws Clause 343
Syntax 7.4: The finally Clause 344
Programming Tip 7.1 : Throw Early,
Catch Late 345
Programming Tip 7.2: Do Not Squelch
Exceptions 345
Programming Tip 7.3: Do Not Use catch and
finally in the Same try Statement 346
Special Topic 7.5: Automatic Resource
Management in Java 7 346
Random Fact 7.2: TheAriane Rocket Incident 347
7.5 APPLICATION: HANDLING
INPUT ERRORS 347
Video Example 7.2: Detecting
Accounting Fraud ©
In this chapter, you will learn how to read and write
files — a very useful skill for processing real world data. As
an application, you will learn how to encrypt data. (The
Enigma machine shown at left is an encryption device used
by Germany in World War 1L Pioneering British computer
scientists broke the code and were able to intercept
encoded messages, which was a significant help in winning
the war.) The remainder of this chapter tells you how your
programs can report and recover from problems, such as
missing files or malformed content, using the exception¬
handling mechanism of the Java language.
7.1 Reading and Writing Text Files
Use the Scanner class
for reading text files.
When writing text
files, use the
PrintWriter class
and the print/
println/printf
methods.
We begin this chapter by discussing the common task of reading and writing files that
contain text. Examples of text files include not only files that are created with a simple
text editor, such as Windows Notepad, but also Java source code and HTML files.
In Java, the most convenient mechanism for reading text is to use the Scanner class.
You already know how to use a Scanner for reading console input. To read input from
a disk file, the Scanner class relies on another class, File, which describes disk files and
directories. (The Fi 1 e class has many methods that we do not discuss in this book; for
example, methods that delete or rename a file.)
To begin, construct a Fi 1 e object with the name of the input file:
File inputFile = new File("input.txt");
Then use the File object to construct a Scanner object:
Scanner in = new Scanner(inputFile);
This Scanner object reads text from the file i nput.txt. You can use the Scanner methods
(such as nextlnt, nextDoubl e, and next) to read data from the input file.
For example, you can use the following loop to process numbers in the input file:
while (in.hasNextDoubleO)
{
double value = in.nextDoubleO ;
Process value.
}
To write output to a file, you construct a Pri ntWri ter object with the desired file name,
for example
PrintWriter out = new Pri ntWri ter("output. txt") ;
If the output file already exists, it is emptied before the new data are written into it. If
the file doesn’t exist, an empty file is created.
The PrintWriter class is an enhancement of the PrintStream class that you already
know — System. out is a PrintStream object. You can use the familiar print, println, and
pri ntf methods with any Pri ntWri ter object:
out.println("Hello, World!");
out.printf("Total : %8.2f\n", total);
318
7.1 Reading and Writing Text Files 319
Close all files when
you are done
processing them.
If your program exits without closing the Pri ntWriter, some of the output may not be
written to the disk file.
The following program puts these concepts to work. It reads a file containing
numbers, and writes the numbers to another file, lined up in a column and followed
by their total.
For example, if the input file has the contents
32 54 67.5 29 35 80
115 44.5 100 65
then the output file is
32.00
54.00
67.50
29.00
35.00
80.00
115.00
44.50
100.00
65.00
Total: 622.00
There is one additional issue that we need to tackle. If the input or output file for a
Scanner doesn’t exist, a FileNotFoundException occurs when the Scanner object is con¬
structed. The compiler insists that we specify what the program should do when that
happens. Similarly, the Pri ntWriter constructor generates this exception if it cannot
open the file for writing. (This can happen if the name is illegal or the user does not
have the authority to create a file in the given location.) In our sample program, we
want to terminate the main method if the exception occurs. To achieve this, we label
the mai n method with a throws declaration:
public static void main(String[] args) throws FileNotFoundException
You will see in Section 7.4 how to deal with exceptions in a more professional way.
The File, Pri ntWriter, and FileNotFoundException classes are contained in the java.io
package.
section_l /Total.java
1 import java.io. File;
2 import java.io. FileNotFoundException;
3 import java.io.PrintWriter;
4 import java. util .Scanner;
5
6 /**
7 This program reads a file with numbers, and writes the numbers to another
8 file, lined up in a column and followed by their total.
9 */
10 public class Total
11 {
12 public static void main(String[] args) throws FileNotFoundException
13 {
When you are done processing a file, be sure to close the Scanner or Pri ntWriter:
in.closeO ;
out.closeQ ;
320 Chapter 7 Input/Output and Exception Handling
14 // Prompt for the input and output file names
15
16 Scanner console = new Scanner(System.in) ;
17 System. out. print("Input file: );
18 St ring inputFileName = console. next() ;
19 System. out. print("Output file: );
20 St ring outputFileName = consol e. next() ;
21
22 // Construct the Scanner and PrintWriter objects for reading and writing
23
24 File inputFile = new File(inputFileName) ;
25 Scanner in = new Scanner(inputFile);
26 PrintWriter out = new PrintWriter(outputFileName);
27
28 // Read the input and write the output
29
30 double total = 0;
31
32 while (in.hasNextDoubleO)
33 {
34 double value = in.nextDouble();
35 out.printf("%15.2f\n", value);
36 total = total + value;
37 }
38
39 out.printf( Total: %8.2f\n , total);
40
41 in.closeO;
42 out.closeO;
43 }
44 }
1 . What happens when you supply the same name for the input and output files to
the Total program? Try it out if you are not sure.
2. What happens when you supply the name of a nonexistent input file to the Total
program? Try it out if you are not sure.
3. Suppose you wanted to add the total to an existing file instead of writing a new
file. Self Check 1 indicates that you cannot simply do this by specifying the same
file for input and output. How can you achieve this task? Provide the pseudo¬
code for the solution.
4. How do you modify the program so that it shows the average, not the total, of
the inputs?
5. How can you modify the Total program so that it writes the values in two
columns, like this:
32.00 54.00
67.50 29.00
35.00 80.00
115.00 44.50
100.00 65.00
Total: 622.00
Practice It Now you can try these exercises at the end of the chapter: R7.1, R7.2, P7.1.
7.1 Reading and Writing Text Files 321
Backslashes in File Names
When you specify a file name as a string literal, and the name contains backslash characters (as
in a Windows file name), you must supply each backslash twice:
File inputFile = new File("c: \\homeworkWinput.dat") ;
A single backslash inside a quoted string is an escape character that is combined with the
following character to form a special meaning, such as \n for a newline character. The \\ com¬
bination denotes a single backslash.
When a user supplies a file name to a program, however, the user should not type the back¬
slash twice.
Constructing a Scanner with a String
When you construct a PrintWriter with a string, it writes to a file:
PrintWriter out = new PrintWriterCoutput.txt") ;
However, this does not work for a Scanner. The statement
Scanner in = new ScannerCinput.txt"); // Error?
does not open a file. Instead, it simply reads through the string: in. next () returns the string
"input.txt". (This is occasionally useful — see Section 7.2.4.)
You must simply remember to use File objects in the Scanner constructor:
Scanner in = new Scanner(new FileCinput.txt")); // OK
Reading Web Pages
You can read the contents of a web page with this sequence of commands:
String address = "http://horstmann.com/index.html";
URL pageLocation = new URL(address) ;
Scanner in = new Scanner(pageLocation.openStreamQ) ;
Now simply read the contents of the web page with the Scanner
in the usual way. The URL constructor and the openStream method
can throw an IOExcepti on, so you need to tag the mai n method with
throws IOExcepti on. (See Section 7.4.3 for more information on the
throws clause.)
The URL class is contained in the java.net package.
ONLINE EXAMPLE
Q A program that reads
data from a web page.
File Dialog Boxes
In a program with a graphical user interface, you will want to use a file dialog box (such as the
one shown in the figure below) whenever the users of your program need to pick a file. The
IFileChooser class implements a file dialog box for the Swing user-interface toolkit.
The 1 Fi 1 eChoose r class has many options to fine-tune the display of the dialog box, but in its
most basic form it is quite simple: Construct a file chooser object; then call the showOpenDialog
or showSaveDi alog method. Both methods show the same dialog box, but the button for select¬
ing a file is labeled “Open” or “Save”, depending on which method you call.
322 Chapter 7 Input/Output and Exception Handling
ONLINE EXAMPLE
© A program that
demonstrates how to
use a file chooser.
For better placement of the dialog box on the screen, you can specify the user-interface
component over which to pop up the dialog box. If you don’t care where the dialog box pops
up, you can simply pass null. The showOpenDialog and showSaveDialog methods return either
JFileChooser.APPROVE_OPTION, if the user has chosen a file, or ]FileChooser.CANCEL_OPTION, if the
user canceled the selection. If a file was chosen, then you call the getSelectedFile method to
obtain a Fi 1 e object that describes the file. Here is a complete example:
IFileChooser chooser = new JFileChooserO I
Scanner in = null;
if (chooser. showOpenDialog(null) == JFileChooser.APPROVEJDPTION)
I
File selectedFile = chooser. getSelectedFileO ;
in = new Scanner(selectedFi le) ;
}
Call with
showOpenDialog
method
I
j Open
Look In:
□ api
w G3 O' C3 [ o-p. | o—
index-files
J allclasses-noframe.html Q overview- summ;
n iava
_J constant-values.html
Q] overview-tree.hti
rl iavax
1 deprecated- listhtml
Q package- list
C3 org
Q help-dochtml
Q serialized-form.li
n resources
Q indexhtml
0 stylesheetcss
0 allclasses-frame.html
Q overview-frame.html
<
_ 12
File Name:
Files of Ivpe:
All Files
Button is “Save” when
showSaveDi al og method
is called
Open
Cancel
A JFileChooser Dialog Box
Reading and Writing Binary Data
You use the Scanner and PrintWriter classes to read and write text files. Text files contain
sequences of characters. Other files, such as images, are not made up of characters but of bytes.
A byte is a fundamental storage unit in a computer— a number consisting of eight binary dig¬
its. (A byte can represent unsigned integers between 0 and 255 or signed integers between-128
and 127.) The Java library has a different set of classes, called streams, for working with binary
files. While modifying binary files is quite challenging and beyond the scope of this book, we
give you a simple example of copying binary data from a web site to a file.
You use an InputStream to read binary data. For example,
URL imageLocation = new URL("http://horstmann . com/java4everyone/duke.gif") ;
InputStream in = imageLocation.openStreamO I
To write binary data to a file, use a FileOutputStream:
FileOutputStream out = new FileOutputStreamC'duke.gif") ;
7.2 Text Input and Output 323
The read method of an input stream reads a single byte and returns -1 when no further input is
available. The wri te method of an output stream writes a single byte.
The following loop copies all bytes from an input stream to an output stream:
boolean done = false;
while C ! done)
{
int input = in.readO; // -1 or a byte between 0 and 255
if (input == -1) { done = true; }
else { out.write(input) ; }
}
7.2 Text Input and Output
In the following sections, you will learn how to process text with complex contents,
and you will learn how to cope with challenges that often occur with real data.
7.2.1 Reading Words
The next method
reads a string that
is delimited by
white space.
The next method of the Scanner class reads the next string. Consider the loop
while (in.hasNextO)
{
String input = in.next();
System. out. println (input) ;
}
If the user provides the input:
Mary had a little lamb
this loop prints each word on a separate line:
Mary
had
a
little
lamb
However, the words can contain punctuation marks and other symbols. The next
method returns any sequence of characters that is not white space. White space
includes spaces, tab characters, and the newline characters that separate lines. For
example, the following strings are considered “words” by the next method:
snow.
1729
C++
(Note the period after snow— it is considered a part of the word because it is not white
space.)
Here is precisely what happens when the next method is executed. Input characters
that are white space are consumed— that is, removed from the input. However, they
do not become part of the word. The first character that is not white space becomes
the first character of the word. More characters are added until either another white
space character occurs, or the end of the input file has been reached. However, if the
end of the input file is reached before any character was added to the word, a “no such
element exception” occurs.
324 Chapter 7 Input/Output and Exception Handling
Sometimes, you want to read just the words and discard anything that isn’t a letter.
You achieve this task by calling the useDelimi ter method on your Scanner object:
Scanner in = new Scanner(. .
i n . useDel i mi ter(" [AA-Za-z] +") ;
Here, we set the character pattern that separates words to “any sequence of charac¬
ters other than letters”. (See Special Topic 7.4.) With this setting, punctuation and
numbers are not included in the words returned by the next method.
7.2.2 Reading Characters
Sometimes, you want to read a file one character at a time. You will see an example in
Section 7.3 where we encrypt the characters of a file. You achieve this task by calling
the useDelimi ter method on your Scanner object with an empty string:
Scanner in = new Scanner(. .
in.useDelimiterC"");
Now each call to next returns a string consisting of a single character. Here is how you
can process the characters:
while (in.hasNextO)
{
char ch = in.next() .charAt(O) ;
Process ch.
}
7.2.3 Classifying Characters
The Character class
has methods for
classifying
characters.
When you read a character, or when you analyze the characters in a word or line,
you often want to know what kind of character it is. The Character class declares sev¬
eral useful methods for this purpose. Each of them has an argument of type char and
returns a boolean value (see Table 1 ).
For example, the call
Character. isDigit(ch)
returns true if ch is a digit ('O' ... '9' or a digit in another writing system — see Random
Fact 2.2), fal se otherwise.
Table 1 Character Testing Methods
Method
Examples of
Accepted Characters
isDigit
0,1,2
is Letter
A, B, C, a, b, c
i sUpperCase
A, B, C
i sLowerCase
a, b, c
isWhiteSpace
space, newline, tab
7.2 Text Input and Output 325
The nextLine method
reads an entire line.
7.2.4 Reading Lines
When each line of a file is a data record, it is often best to read entire lines with the
nextLine method:
String line = in.nextLine() ;
The next input line (without the newline character) is placed into the string 1 i ne. You
can then take the line apart for further processing.
The hasNextLine method returns true if there is at least one more line in the input,
fal se when all lines have been read. To ensure that there is another line to process, call
the hasNextLi ne method before calling nextLi ne.
Here is a typical example of processing lines in a file. A file with population data
from the CIA Fact Book site (https://www.cia.gov/library/publications/the-world-
factbook/i ndex.html) contains lines such as the following:
China 13B0044605
India 1147995898
United States 303824646
Because some country names have more than one word, it would be tedious to read
this file using the next method. For example, after reading Uni ted, how would your pro¬
gram know that it needs to read another word before reading the population count?
Instead, read each input line into a string:
while (in.hasNextLineO)
{
String line = nextLi ne C) I
Process line.
}
Use the i sDi gi t and i sWhi teSpace methods introduced to find out where the name ends
and the number starts.
Locate the first digit:
int i = 0;
while ([Character. isDigit(line.charAt(i))) { i++; }
Then extract the country name and population:
String countryName = line.substring(0, i);
String population = line.substring(i);
However, the country name contains one or more spaces at the end. Use the trim
method to remove them:
countryName = countryName. trim() ;
i starts here
Use tri m to
remove this space. i ends here
U n
i t e d
S t
ate
s 3
0
3
8
2
4
6
4
6
0 1
V _
2 3 4 5
6 7 8
9 10 11
12 13 14
_
15
16
17
18
19
20
21
22
J
countryName population
The trim method returns the string with all white space at the beginning and end
removed.
326 Chapter 7 Input/Output and Exception Handling
There is one additional problem. The population is stored in a string, not a num¬
ber. In Section 7.2.6, you will see how to convert the string to a number.
7.2.5 Scanning a String
In the preceding section, you saw how to break a string into parts by looking at
individual characters. Another approach is occasionally easier. You can use a Scanner
object to read the characters from a string:
Scanner 1 i neScanner = new Scanner(line) ;
Then you can use 1i neScanner like any other Scanner object, reading words and
numbers:
String countryName = lineScanner.nextO ; // Read first word
// Add more words to countryName until number encountered
whi 1 e (Mi neScanner . hasNextlnt ())
{
countryName = countryName + " " + lineScanner.nextO;
}
int populationValue = 1 i neScanner. nextlnt() ;
7.2.6 Converting Strings to Numbers
If a string contains
the digits of a
number, you use the
Integer. parselnt or
Doubl e . parseDoubl e
method to obtain the
number value.
Sometimes you have a string that contains a number, such as the population string
in Section 7.2.4. For example, suppose that the string is the character sequence
"303824646". To get the integer value 303824646, you use the Integer, parselnt method:
int populationValue = Integer. parselnt(population) ;
// populationValue is the integer 303824646
To convert a string containing floating-point digits to its floating-point value, use the
Double. parseDoubl e method. For example, suppose input is the string "3.95".
double price = Double. parseDouble(input) ;
// price is the floating-point number 3.95
You need to be careful when calling the Integer, parselnt and Double. parseDoubl e meth¬
ods. The argument must be a string containing the digits of an integer, without any
additional characters. Not even spaces are allowed! In our situation, we happen to
know that there won’t be any spaces at the beginning of the string, but there might be
some at the end. Therefore, we use the tri m method:
int populationValue = Integer. parselnt(population.trimO) ;
How To 7.1 on page 333 continues this example.
7.2.7 Avoiding Errors When Reading Numbers
You have used the nextlnt and nextDouble methods of the Scanner class many times, but
here we will have a look at what happens in “abnormal” situations. Suppose you call
int value = in.nextlntO;
The nextlnt method recognizes numbers such as 3 or -21. However, if the input is not
a properly formatted number, an “input mismatch exception” occurs. For example,
consider an input containing the characters
7.2 Text Input and Output 327
21st century
White space is consumed and the word 21st is read. However, this word is not a prop¬
erly formatted number, causing an input mismatch exception in the nextlnt method.
If there is no input at all when you call nextlnt or nextDoubl e, a “no such element
exception” occurs. To avoid exceptions, use the hasNextlnt method to screen the input
when reading an integer. For example,
if (in.hasNextlntO)
{
int value = in.nextlnt();
}
Similarly, you should call the hasNextDouble method before calling nextDouble.
7.2.8 Mixing Number, Word, and Line Input
The nextlnt, nextDoubl e, and next methods do not consume the white space that follows
the number or word. This can be a problem if you alternate between calling nextlnt/
nextDoubl e/next and nextLine. Suppose a file contains country names and population
values in this format:
China
1330044605
India
1147995898
United States
303824646
Now suppose you read the file with these instructions:
while (in.hasNextLineO)
{
String countryName = in.nextLine();
int population = in.nextlnt();
Process the country name and population.
}
Initially, the input contains
Chi na\n 1330044605 \nlndi a\n
After the first call to the nextLi ne method, the input contains
1330044605 \nlndi a \n
After the call to nextlnt, the input contains
\n I n d i a \n
Note that the nextlnt call did not consume the newline character. Therefore, the sec¬
ond call to nextLi ne reads an empty string!
The remedy is to add a call to nextLi ne after reading the population value:
String countryName = i n. nextLi ne() ;
int population = in.nextlntO ;
i n. nextLi ne() ; // Consume the newline
The call to nextLi ne consumes any remaining white space and the newline character.
328 Chapter 7 Input/Output and Exception Handling
7.2.9 Formatting Output
When you write numbers or strings, you often want to control how they appear. For
example, dollar amounts are usually formatted with two significant digits, such as
Cookies: 3.20
You know from Section 2.3.2 how to achieve this output with the pri ntf method. In
this section, we discuss additional options of the pri ntf method.
Suppose you need to print a table of items and prices, each stored in an array, such
as this one:
Cookies: 3.20
Linguine: 2.95
Clams: 17.29
Note that the item strings line up to the left, whereas the numbers line up to the right.
By default, the pri ntf method lines up values to the right. To specify left alignment,
you add a hyphen (-) before the field width:
System. out. printf("X-10s%10.2f", items[i] + prices[i]);
Here, we have two format specifiers.
• %-10s formats a left-justified string. The string i terns [i ] + " : " is padded with spaces
so it becomes ten characters wide. The - indicates that the string is placed on the
left, followed by sufficient spaces to reach a width of 10.
• %10 . 2f formats a floating-point number, also in a field that is ten characters wide.
However, the spaces appear to the left and the value to the right.
A left-justified
string
width 10
width 10
-A.
/
\r
X
C 1
lams:
1 7 .
. 2 9
Two digits after
the decimal point
A construct such as %-10s or %10 . 2f is called a format specifier: it describes how a value
should be formatted.
Table 2 Format Flags
Flag
Meaning
Example
-
Left alignment
1.23 followed by spaces
0
Show leading zeroes
001.23
+
Show a plus sign for positive numbers
+1.23
(
Enclose negative numbers in parentheses
(1.23)
>
Show decimal separators
12,300
A
Convert letters to uppercase
1.23E+1
7.2 Text Input and Output 329
Table B Format Types
Code
Type
Example
d
Decimal integer
123
f
Fixed floating-point
12.30
e
Exponential floating-point
1.23e+l
9
General floating-point
(exponential notation is used for
very large or very small values)
12.3
s
String
Tax:
ONLINE EXAMPLE
A program that
processes a file
containing a mixture
of text and numbers.
A format specifier has the following structure:
• The first character is a %
• Next, there are optional “flags” that modify the format, such as - to indicate left
alignment. See Table 2 for the most common format flags.
• Next is the field width, the total number of characters in the field (including the
spaces used for padding), followed by an optional precision for floating-point
numbers.
• The format specifier ends with the format type, such as f for floating-point values
or s for strings. There are quite a few format types — Table 3 shows the most
important ones.
6. Suppose the input contains the characters Hello, World!. What are the values of
word and i nput after this code fragment?
String word = in.next();
String input = in.nextl_ine() ;
7. Suppose the input contains the characters 995.0 Fred. What are the values of
number and i nput after this code fragment?
int number = 0;
if (in.hasNextlntO) { number = in.nextlnt() ; }
String input = in.next();
8. Suppose the input contains the characters 6E6 6,995.00. What are the values of xl
and x2 after this code fragment?
double xl = in.nextDouble() ;
double x2 = in.nextDouble() ;
9. Your input file contains a sequence of numbers, but sometimes a value is not
available and is marked as N/A. How can you read the numbers and skip over the
markers ?
1 0. How can you remove spaces from the country name in Section 7.2.4 without
using the trim method?
Practice It
Now you can try these exercises at the end of the chapter: P7.2, P7.4, P7.5.
330 Chapter 7 Input/Output and Exception Handling
Regular Expressions
Regular expressions describe character patterns. For example, numbers have a simple form.
They contain one or more digits. The regular expression describing numbers is [0-9]+. The set
[0-9] denotes any digit between 0 and 9, and the + means “one or more”.
The search commands of professional programming editors understand regular expres¬
sions. Moreover, several utility programs use regular expressions to locate matching text. A
commonly used program that uses regular expressions is grep (which stands for “global regu¬
lar expression print”). You can run grep from a command line or from inside some compila¬
tion environments. Grep is part of the UNIX operating system, and versions are available for
Windows. It needs a regular expression and one or more files to search. When grep runs, it
displays a set of lines that match the regular expression.
Suppose you want to find all magic numbers (see Programming Tip 2.2) in a file.
grep [0-9]+ Homework. java
lists all lines in the file Homework, java that contain sequences of digits. That isn’t terribly useful;
lines with variable names xl will be listed. OK, you want sequences of digits that do not imme¬
diately follow letters:
grep [AA-Za-z] [0-9]+ Homework. java
The set [AA-Za-z] denotes any characters that are not in the ranges A to Z and a to z. This works
much better, and it shows only lines that contain actual numbers.
The useDel i mi ter method of the Scanner class accepts a regular expression to describe delim¬
iters— the blocks of text that separate words. As already mentioned, if you set the delimiter
pattern to [AA-Za-z]+, a delimiter is a sequence of one or more characters that are not letters.
For more information on regular expressions, consult one of the many tutorials on the
Internet by pointing your search engine to “regular expression tutorial”.
VIDEO EXAMPLE 7.1
Computing a Document’s Readability
fWILEYO
rPLUS
In this Video Example, we develop a program that computes the Flesch
Readability Index for a document.
7.3 Command Line Arguments
Depending on the operating system and Java development environment used, there
are different methods of starting a program — for example, by selecting “Run” in
the compilation environment, by clicking on an icon, or by typing the name of the
program at the prompt in a command shell window. The latter method is called
“invoking the program from the command line”. When you use this method, you
must of course type the name of the program, but you can also type in additional
information that the program can use. These additional strings are called command
line arguments. For example, if you start a program with the command line
java ProgramClass -v input.dat
then the program receives two command line arguments: the strings "-v" and "input,
dat". It is entirely up to the program what to do with these strings. It is customary to
interpret strings starting with a hyphen (-) as program options.
© Available online in WileyPLUS and at www.wiley.com/conege/horstmann.
7.3 Command Line Arguments 331
Programs that start
from the command
line receive the
command line
arguments in the
mat n method.
Should you support command line arguments for your programs, or should you
prompt users, perhaps with a graphical user interface? For a casual and infrequent
user, an interactive user interface is much better. The user interface guides the user
along and makes it possible to navigate the application without much knowledge. But
for a frequent user, a command line interface has a major advantage: it is easy to auto¬
mate. If you need to process hundreds of files every day, you could spend all your
time typing file names into file chooser dialog boxes. However, by using batch files or
shell scripts (a feature of your computer’s operating system), you can automatically
call a program many times with different command line arguments.
Your program receives its command line arguments in the args parameter of the
mai n method:
public static void main(String[] args)
In our example, args is an array of length 2, containing the strings
args[0]: "-v"
args[l] : "input.dat"
Let us write a program that encrypts a file — that is,
scrambles it so that it is unreadable except to those who
know the decryption method. Ignoring 2,000 years of
progress in the field of encryption, we will use a method
familiar to Julius Caesar, replacing A with a D, B with
an E, and so on (see Figure 1).
The program takes the following command line
arguments:
• An optional -d flag to indicate decryption instead of
encryption
• The input file name
• The output file name
For example,
java CaesarCipher input. txt encrypt.txt
encrypts the file input.txt and places the result into
encrypt.txt.
java CaesarCipher -d encrypt.txt output.txt
decrypts the file encrypt.txt and places the result into output.txt.
The emperor Julius Caesar
used a simple scheme to
encrypt messages.
Plain text
M
e
e
t
m
e
a
t
t
h
e
1
1
1
1
1
1
1
1
Encrypted text
P
h
h
w
p
h
d
w
w
k
h
Figure 1 CaesarCipher
section_3/CaesarCipher.java
1 import java. io. File;
2 import java.io.FileNotFoundException;
3 import java.io.PrintWriter;
4 import java. util .Scanner;
332 Chapter 7 Input/Output and Exception Handling
5
6 /**
7 This program encrypts a file using the Caesar cipher.
8 */
9 public class CaesarCipher
10 {
public static void main(String[] args) throws FileNotFoundException
12 {
13 final int DEFAULT_KEY = 3;
14 int key = DEFAULT_KEY ;
1 5 String inFile = ;
16 String outFile = ;
17 int files = 0; // Number of command line arguments that are files
18
19 for (int i =0; i < args. length; i++)
20 {
21 String arg = args [i ] ;
22 if (arg.charAt(O) == )
23 {
24 // It is a command line option
25
char option = arg.charAt(l);
27 if (option == 'd') { key = -key; }
28 else { usage(); return; }
29 }
30 else
31 {
32 // It is a file name
33
34 files++;
35 if (files == 1) { inFile = arg; }
36 else if (files == 2) { outFile = arg; }
37 }
38 }
39 if (files != 2) { usage(); return; }
40
41 Scanner in = new Scanner(new File(inFile)) ;
42 in.useDelimiter( ""); // Process individual characters
43 PrintWriter out = new PrintWriter(outFile) ;
44
45 while (in . hasNextO)
46 {
47 char from = in.nextO .charAt(O) ;
48 char to = encrypt(from, key);
49 out.print(to);
50 }
51 in.closeO;
52 out.closeO;
53 }
54
55 /**
56 Encrypts upper- and lowercase characters by shifting them
57 according to a key.
58 ©param ch the letter to be encrypted
59 ©param key the encryption key
60 ©return the encrypted letter
61 */
62 public static char encrypt(char ch, int key)
63 {
64
int base = 0;
7.3 Command Line Arguments 333
65 if ( A' <= ch && ch <= 'Z') { base = 'A'; }
66 else if ('a' <= ch && ch <= ' z ' ) { base = 'a'; }
67 el se { return ch; } // Not a letter
68 int offset = ch - base + key;
69 final int LETTERS = 26; // Number of letters in the Roman alphabet
70 if (offset > LETTERS) { offset = offset - LETTERS; }
71 else if (offset < 0) { offset = offset + LETTERS; }
72 return (char) (base + offset);
73 }
74
75 /**
76 Prints a message describing proper usage.
77 V
78 public static void usage()
79 {
80 System. out. println("Usage: java CaesarCipher [-d] infile outfile") ;
81 }
82 }
11. If the program is invoked with java CaesarCipher -d filel.txt, what are the
elements of args?
1 2. Trace the program when it is invoked as in Self Check 1 1 .
1 3. Will the program run correctly if the program is invoked with java CaesarCi pher
filel.txt file2.txt -d? If so, why? If not, why not?
1 4. Encrypt CAESAR using the Caesar cipher.
1 5. How can you modify the program so that the user can specify an encryption key
other than 3 with a -k option, for example
java CaesarCipher -kl5 input.txt output.txt
Practice It Now you can try these exercises at the end of the chapter: R7.4, P7.8, P7.9.
HOW TO 7. 1
Processing Text Files
Processing text files that contain real data can be
surprisingly challenging. This How To gives you step-
by-step guidance.
As an example, we will consider this task: Read
two country data files, worldpop.txt and worldarea.txt
(supplied with the book’s companion code). Both files
contain the same countries in the same order. Write a
file world_pop_density.txt that contains country names
and population densities (people per square km), with
the country names aligned left and the numbers aligned
>ht:
Afghani stan
50.56
Akroti ri
127.64
A1 bania
125.91
Algeria
14.18
American Samoa
288.92
Singapore is one of the most densely
populated countries in the world.
334 Chapter 7 Input/Output and Exception Handling
Step 1
Step 2
Step 3
Step 4
Step 5
Understand the processing task.
As always, you need to have a clear understanding of the task before designing a solution. Can
you carry out the task by hand (perhaps with smaller input files)? If not, get more information
about the problem.
One important aspect that you need to consider is whether you can process the data as it
becomes available, or whether you need to store it first. For example, if you are asked to write
out sorted data, you first need to collect all input, perhaps by placing it in an array list. How¬
ever, it is often possible to process the data “on the go”, without storing it.
In our example, we can read each file a line at a time and compute the density for each line
because our input files store the population and area data in the same order.
The following pseudocode describes our processing task.
While there are more lines to be read
Read a line from each file.
Extract the country name.
population = number following the country name in the line from the first file
area * number following the country name in the line from the second file
If area !* 0
density = population / area
Print country name and density.
Determine which files you need to read and write.
This should be clear from the problem. In our example, there are two input files, the popula¬
tion data and the area data, and one output file.
Choose a mechanism for obtaining the file names.
There are three options:
• Hard-coding the file names (such as "worldpop.txt").
• Asking the user:
Scanner in = new Scanner(System.in) ;
System. out. print("Enter filename: ") ;
String inFile = in.nextLineO ;
• Using command-line arguments for the file names.
In our example, we use hard-coded file names for simplicity.
Choose between line, word, and character-based input.
As a rule of thumb, read lines if the input data is grouped by lines. That is the case with tabular
data, such as in our example, or when you need to report line numbers.
When gathering data that can be distributed over several lines, then it makes more sense to
read words. Keep in mind that you lose all white space when you read words.
Reading characters is mostly useful for tasks that require access to individual characters.
Examples include analyzing character frequencies, changing tabs to spaces, or encryption.
With line-oriented input, extract the required data.
It is simple to read a line of input with the nextLi ne method. Then you need to get the data out
of that line. You can extract substrings, as described in Section 7.2.4.
Typically, you will use methods such as Character. isWhitespace and Character. isDi git to
find the boundaries of substrings.
If you need any of the substrings as numbers, you must convert them, using Integer . parselnt
or Doubl e . parseDoubl e.
7.3 Command Line Arguments 335
Step 6 Use methods to factor out common tasks.
Processing input files usually has repetitive tasks, such as skipping over white space or extract¬
ing numbers from strings. It really pays off to develop a set of methods to handle these tedious
operations.
In our example, we have two common tasks that call for helper methods: extracting the
country name and the value that follows. We will implement methods
public static String extractCountryCString line)
public static double extractVal ue(String line)
These methods are implemented as described in Section 7.2.4.
Here is the complete source code (how_to_l/Popul ati onDensi ty . j ava).
import java. io. Fi le;
import java. io. Fi leNot Found Exception;
import java.io.PrintWriter;
import java. util .Scanner;
/**
This program reads data files of country populations and areas and prints the
population density for each country.
V
public class PopulationDensity
{
public static void main(String[] args) throws FileNotFoundException
{
// Construct Scanner objects for input files
Scanner ini = new Scanner(new File("worldpop.txt")) ;
Scanner in2 = new Scanner(new File("worldarea.txt")) ;
// Construct PrintWriter for the output file
PrintWriter out = new PrintWriter("world_pop_density.txt") ;
// Read lines from each file
while (inl.hasNextLineO && in2.hasNextLine())
{
String linel = ini. nextLi ne() ;
String line2 = in2 . nextLineO ;
// Extract country and associated value
String country = extractCountryO i nel) ;
double population = extractVal ue(l i nel) ;
double area = extractValue(line2) ;
// Compute and print the population density
double density = 0;
if (area != 0) // Protect against division by zero
I
density = population / area;
}
out . pri ntf ("%-40s%15 . 2f\n" , country, density);
I
inl.closeO I
in2.close() ;
out.closeO ;
I
336 Chapter 7 Input/Output and Exception Handling
Extracts the country from an input line.
@param 1 i ne a line containing a country name, followed by a number
@return the country name
V
public static String extractCountryCStri ng line)
{
i nt i = 0 ; // Locate the start of the first digit
while (!Character.isDigit(line.charAt(i))) { i++; }
return line.substringCO, i).trim(); // Extract the country name
Extracts the value from an input line.
@param line a line containing a country name, followed by a value
©return the value associated with the country
V
public static double extractValue(String line)
{
i nt i = 0 ; // Locate the start of the first digit
while (!Character.isDigit(line.charAt(i))) { i++; }
// Extract and convert the value
return Double. parseDouble(line.substring(i) .trimO) ;
}
}
Random Fact 7.1 Encryption Algorithms
The exercises at the
end of this chapter
give a few algorithms for encrypting
text. Don’t actually use any of those
methods to send secret messages
to your lover. Any skilled cryptogra¬
pher can break these schemes in a
very short time — that is, reconstruct
the original text without knowing the
secret keyword.
In 1978, Ron Rivest, Adi Shamir,
and Leonard Adleman introduced an
encryption method that is much more
powerful. The method is called RSA
encryption , after the last names of its
inventors. The exact scheme is too
complicated to present here, but it is
not actually difficult to follow. You can
find the details in http://theory.lcs.
mi t . edu/~ri vest/ rsapaper . pdf .
RSA is a remarkable encryption
method. There are two keys: a pub¬
lic key and a private key. (See the fig¬
ure.) You can print the public key on
your business card (or in your e-mail
signature block) and give it to any¬
one. Then anyone can send you mes¬
sages that only you can decrypt. Even
though everyone else knows the public
key, and even if they intercept all the
messages coming to you, they cannot
break the scheme and actually read
the messages. In 1994, hundreds of
researchers, collaborating over the
Internet, cracked an RSA message
encrypted with a 129-digit key. Mes¬
sages encrypted with a key of 230 dig¬
its or more are expected to be secure.
The inventors of the algorithm
obtained a patent for it. A patent is a
deal that society makes with an inven¬
tor. For a period of 20 years, the inven¬
tor has an exclusive right for its com¬
mercialization, may collect royalties
from others wishing to manufacture
the invention, and may even stop com¬
petitors from using it altogether. In
return, the inventor must publish the
invention, so that others may learn
from it, and must relinquish all claim
to it after the monopoly period ends.
The presumption is that in the absence
of patent law, inventors would be
reluctant to go through the trouble of
inventing, or they would try to cloak
their techniques to prevent others
from copying their devices.
There has been some controversy
about the RSA patent. Had there not
been patent protection, would the
inventors have published the method
anyway, thereby giving the benefit to
society without the cost of the 20-year
monopoly? In this case, the answer is
probably yes. The inventors were aca¬
demic researchers, who live on sala¬
ries rather than sales receipts and are
usually rewarded for their discover¬
ies by a boost in their reputation and
careers. Would their followers have
been as active in discovering (and pat¬
enting) improvements? There is no
way of knowing, of course. Is an algo¬
rithm even patentable, or is it a math¬
ematical fact that belongs to nobody?
The patent office did take the latter
attitude for a long time. The RSA inven¬
tors and many others described their
7.4 Exception Handling 337
WORKED EXAMPLE 7.1
Analyzing Baby Names
In this Worked Example, you will use data from the
Social Security Administration to analyze the most
popular baby names.
7.4 Exception Handling
There are two aspects to dealing with program errors: detection and handling. For
example, the Scanner constructor can detect an attempt to read from a non-existent
file. However, it cannot handle that error. A satisfactory way of handling the error
might be to terminate the program, or to ask the user for another file name. The Scan¬
ner class cannot choose between these alternatives. It needs to report the error to
another part of the program.
In Java, exception handling provides a flexible mechanism for passing control from
the point of error detection to a handler that can deal with the error. In the following
sections, we will look into the details of this mechanism.
inventions in terms of imaginary elec¬
tronic devices, rather than algorithms,
to circumvent that restriction. Nowa¬
days, the patent office will award soft¬
ware patents.
There is another interesting aspect
to the RSA story. A programmer, Phil
Zimmermann, developed a program
called PGP (for Pretty Good Privacy)
that is based on RSA. Anyone can use
the program to encrypt messages, and
decryption is not feasible even with
the most powerful computers. You can
get a copy of a free PGP implementa¬
tion from the GNU project (http://www.
gnupg.org). The existence of strong
encryption methods bothers the
United States government to no end.
Criminals and foreign agents can send
communications that the police and
intelligence agencies cannot decipher.
The government considered charging
Zimmermann with breaching a law
that forbids the unauthorized export of
munitions, arguing that he should have
known that his program would appear
on the Internet. There have been seri- methods, or to keep the keys secret
ous proposals to make it illegal for pri- from law enforcement,
vate citizens to use these encryption
Alice
Public-Key Encryption
© Available online in WileyPLUS and at www.wiley.com/college/horstiriann.
338 Chapter 7 Input/Output and Exception Handling
To signal an
exceptional
condition, use the
throw statement
to throw an
exception object.
When you throw
an exception,
processing
continues in an
exception handler.
Syntax 7.1
7.4.1 Throwing Exceptions
When you detect an error condition, your job is really easy. You just throw an appro¬
priate exception object, and you are done. For example, suppose someone tries to
withdraw too much money from a bank account.
if (amount > balance)
{
// Now what?
}
First look for an appropriate exception class. The Java library provides many classes
to signal all sorts of exceptional conditions. Figure 2 shows the most useful ones.
(The classes are arranged as a tree-shaped hierarchy, with more specialized classes at
the bottom of the tree. We will discuss such hierarchies in more detail in Chapter 9.)
Look around for an exception type that might describe your situation. How about
the ArithmeficException? Is it an arithmetic error to have a negative balance? No— Java
can deal with negative numbers. Is the amount to be withdrawn illegal? Indeed it is. It
is just too large. Therefore, let’s throw an Illegal ArgumentExcepti on.
if (amount > balance)
{
throw new IllegalArgumentException("Amount exceeds balance");
}
When you throw an exception, execution does not
continue with the next statement but with an excep¬
tion handler. That is the topic of the next section.
When you throw an exception, the normal control flow
is terminated. This is similar to a circuit breaker that
cuts off the flow of electricity in a dangerous situation.
Throwing an Exception
Syntax throw
exceptionObject ;
A new
Most exception objects
can be constructed with
if (amount > balance) an error message.
{ /
_ throw new IllegalArgumentException( 'Amount exceeds balance');
exception object — "
is constructed,
then thrown.
}
balance = balance - amount;
This line is not executed when
the exception is thrown.
7.4
Exception Handling
339
Throwable
Error
Exception
IOException
Import from
j ava . i o
ClassNot
Found
Exception
FileNotFound
Excepti on
MalformedURL
Excepti on
UnknownHost
Exception
Runtime
Exception
Arithmetic
Exception
Cl assCast
Exception
Illegal
Argument
Exception
NumberFormat
Exception
IndexOut
- OfBounds
Exception
I
NoSuch
- Element
Exception
InputMi smatch
Excepti on
Nul I Poi nter
Exception
Import from
java. uti 1
Figure 2 A Part of the Hierarchy of Exception Classes
7.4.2 Catching Exceptions
Place the statements
that can cause an
exception inside a
try block, and the
handler inside a
catch clause.
Every exception should be handled somewhere in your program. If an exception has
no handler, an error message is printed, and your program terminates. Of course,
such an unhandled exception is confusing to program users.
You handle exceptions with the try/catch statement. Place the statement into a
location of your program that knows how to handle a particular exception. The try
block contains one or more statements that may cause an exception of the kind that
340 Chapter 7 Input/Output and Exception Handling
Ip*
frri@di.ra
Exception Handling
’ in
you are willing to handle. Each catch clause contains the handler for an exception
type. Here is an example:
try
{
String filename = . . . ;
Scanner in = new Scanner(new File(filename)) ;
String input = in.next();
int value = Integer. parselnt(input) ;
}
catch (IOException exception)
{
exception.printStackTrace() ;
}
catch (NumberFormatException exception)
{
System . out . pri ntl n(excepti on . getMessageO) ;
}
Three exceptions may be thrown in this try block:
• The Scanner constructor can throw a FileNotFoundException.
• Scanner . next can throw a NoSuchEl ementExcepti on.
• Integer .parselnt can throw a NumberFormatException.
If any of these exceptions is actually thrown, then the rest of the instructions in the
try block are skipped. Here is what happens for the various exception types:
• If a FileNotFoundException is thrown, then the catch clause for the IOException is
executed. (If you look at Figure 2, you will note that FileNotFoundException is a
descendant of IOExcepti on.) If you want to show the user a different message for a
FileNotFoundException, you must place the catch clause before the clause for an
IOException.
• If a NumberFormatException occurs, then the second catch clause is executed.
• A NoSuchEl ementExcepti on is not caught by any of the catch clauses. The exception
remains thrown until it is caught by another try block.
Each catch clause contains a handler. When the catch (IOException exception) block is
executed, then some method in the try block has failed with an IOException (or one of
its descendants).
In this handler, we produce a printout of the chain of method calls that led to the
exception, by calling
exception . pri ntStackTraceQ
You should only catch those exceptions
that you can handle.
7.4 Exception Handling 341
Syntax 7 Catching Exceptions
Syntax try
{
statement
statement
}
catch ( ExceptionClass exceptionObject )
{
statement
statement
}
This constructor can throw a
Fi 1 eNotFoundExcepti on.
try
{
When an IOException is thrown,
execution resumes here.
Additional catch clauses -
can appear here. Place
more specific exceptions
before more general ones.
Scanner in = new Scanner(new File("input.txt"));
String input = in.nextO;
process (i nput) ; This is the exception that was thrown.
} .
rate h (IOException exception)
-{
System. out. printin ("Could not open input file");
}
"catch (Exception except) A FileNotFoundException
{ is a special case of an IOExcepti on.
System . out . pri ntl n (except . getMessage) ;
}
In the second exception handler, we call exception .getMessage () to retrieve the message
associated with the exception. When the parselnt method throws a NumberFormatExcep-
tion, the message contains the string that it was unable to format. When you throw an
exception, you can provide your own message string. For example, when you call
throw new IllegalArgumentException("Amount exceeds balance");
the message of the exception is the string provided in the constructor.
In these sample catch clauses, we merely inform the user of the source of the prob¬
lem. Often, it is better to give the user another chance to provide a correct input— see
Section 7.5 for a solution.
7.4.3 Checked Exceptions
In Java, the exceptions that you can throw and catch fall into three categories.
• Internal errors are reported by descendants of the type Error. One example is the
OutOfMemoryError, which is thrown when all available computer memory has been
used up. These are fatal errors that happen rarely, and we will not consider them
in this book.
• Descendants of Runti meExcepti on, such as as IndexOutOfBoundsExcepti on or II 1 egal -
ArgumentExcepfion indicate errors in your code. They are called unchecked
exceptions.
342 Chapter 7 Input/Output and Exception Handling
Checked exceptions
are due to external
circumstances that
the programmer
cannot prevent.
The compiler
checks that your
program handles
these exceptions.
Add a throws clause
to a method that can
throw a checked
exception.
• All other exceptions are checked exceptions. These exceptions indicate that
something has gone wrong for some external reason beyond your control. In
Figure 2, the checked exceptions are shaded in a darker color.
Why have two kinds of exceptions? A checked exception describes a problem that
can occur, no matter how careful you are. For example, an IOException can be caused
by forces beyond your control, such as a disk error or a broken network connection.
The compiler takes checked exceptions very seriously and ensures that they are han¬
dled. Your program will not compile if you don’t indicate how to deal with a checked
exception.
The unchecked exceptions, on the other hand, are your fault. The compiler does
not check whether you handle an unchecked exception, such as an IndexOutOfBounds-
Exception. After all, you should check your index values rather than install a handler
for that exception.
If you have a handler for a checked exception in the same method that may throw
it, then the compiler is satisfied. For example,
try
{
File inFile = new File (filename) ;
Scanner in = new Scanner(inFile); // Throws FileNotFoundExcepti on
}
catch (FileNotFoundExcepti on exception) // Exception caught here
{
}
However, it commonly happens that the current method cannot handle the excep¬
tion. In that case, you need to tell the compiler that you are aware of this exception
and that you want your method to be terminated when it occurs. You supply a
method with a throws clause.
public static String readData(String filename) throws FileNotFoundException
{
File inFile = new File(filename) ;
Scanner in = new Scanner(inFile);
The throws clause signals the caller of your method that it may encounter a
FileNotFoundException. Then the caller needs to make the same decision— han¬
dle the exception, or declare that the exception may be thrown.
It sounds somehow irresponsible not to handle an exception when you
know that it happened. Actually, the opposite is true. Java provides an
exception handling facility so that an exception can be sent to the appropri¬
ate handler. Some methods detect errors, some methods handle them, and
some methods just pass them along. The throws clause simply ensures that no
exceptions get lost along the way.
Just as trucks with large or hazardous loads carry warning signs,
the throws clause warns the caller that an exception may occur.
7.4 Exception Handling 343
Syntax, The throws Clause
Syntax modifiers returnType methodName(parameterType parameterName, . . .)
throws ExceptionClass , ExceptionClass , . . .
public static String readData(String filename)
throws FileNotFoundException, NumberFormatException
You must specify all checked exceptions
that this method may throw.
You may also list unchecked exceptions.
7.4.4 The finally Clause
Once a try block
is entered, the
statements in a
finally clause are
guaranteed to be
executed, whether
or not an exception
is thrown.
ONLINE EXAMPLE
A program that
demonstrates
throwing and
catching exceptions.
Occasionally, you need to take some action whether or not an exception is thrown.
The f i nal 1 y construct is used to handle this situation. Here is a typical situation.
It is important to close a Pri ntWriter to ensure that all output is written to the file.
In the following code segment, we open a stream, call one or more methods, and then
close the stream:
Pri ntWriter out = new PrintWriter(filename) ;
writeData(out) ;
out.closeO; // May never get here
Now suppose that one of the methods before the last line throws an exception. Then
the call to close is never executed! You solve this problem by placing the call to close
inside a f i nail y clause:
Pri ntWriter out = new PrintWriter(filename) ;
try
{
writeData(out) ;
}
finally
{
out.closeO I
}
In a normal case, there will be no problem. When the
try block is completed, the finally clause is executed,
and the writer is closed. However, if an exception
occurs, the finally clause is also executed before the
exception is passed to its handler.
Use the finally clause whenever you need to do
some clean up, such as closing a file, to ensure that
the clean up happens no matter how the method
exits.
All visitors to a foreign country have to go through
passport control, no matter what happened on their
trip. Similarly, the code in a f i nail y clause is always
executed, even when an exception has occurred.
344 Chapter 7 Input/Output and Exception Handling
Syntax 7.4 The finally Clause
Syntax try
{
statement
statement
}
finally
{
statement
statement
}
This code may
This variable must be declared outside the try block
so that the f i nal 1 y clause can access it.
\
PrintWriter out = new PrintWriter(filename);
try
throw exceptions.
r i
This code is
writeData(out) ;
_ }
finally
“ {
out.closeO ;
always executed.
even if an exception occurs. ^
}
16. Suppose balance is 100 and amount is 200. What is the value of balance after these
statements?
if (amount > balance)
{
throw new IllegalArgumentException("Amount exceeds balance");
}
balance = balance - amount;
1 7. When depositing an amount into a bank account, we don’t have to worry about
overdrafts — except when the amount is negative. Write a statement that throws
an appropriate exception in that case.
1 8. Consider the method
public static void main(String[] args)
{
try
{
Scanner in = new Scanner(new File("input.txt"));
int value = in.nextlnt();
System . out . pri ntl n (val ue) ;
}
catch (IOException exception)
{
System. out. println("Error opening file.");
}
7.4 Exception Handling 345
Suppose the file with the given file name exists and has no contents. Trace the
flow of execution.
1 9. Why is an ArraylndexOutOfBoundsExcepfion not a checked exception?
20. Is there a difference between catching checked and unchecked exceptions?
2 1 . What is wrong with the following code, and how can you fix it?
public static void writeAll(String[] lines, String filename)
{
PrintWriter out = new PrintWriter(filename) ;
for (String line : lines)
{
out . pri ntl n (1 i ne . toUpperCase ()) ;
}
out.closeO ;
}
Practice It Now you can try these exercises at the end of the chapter: R7.7, R7.8, R7.9.
Throw Early, Catch Late
When a method detects a problem that it cannot solve, it is better
to throw an exception rather than try to come up with an imperfect
fix. For example, suppose a method expects to read a number from a
file, and the file doesn’t contain a number. Simply using a zero value
would be a poor choice because it hides the actual problem and per¬
haps causes a different problem elsewhere.
Conversely, a method should only catch an exception if it can
really remedy the situation. Otherwise, the best remedy is simply to have the exception propa¬
gate to its caller, allowing it to be caught by a competent handler.
These principles can be summarized with the slogan “throw early, catch late”.
Throw an exception
as soon as a
problem is detected.
Catch it only
when the problem
can be handled.
Do Not Squelch Exceptions
When you call a method that throws a checked exception and you haven’t specified a handler,
the compiler complains. In your eagerness to continue your work, it is an understandable
impulse to shut the compiler up by squelching the exception:
try
{
Scanner in = new Scanner(new File(filename)) ;
// Compiler complained about FileNotFoundException
}
catch (FileNotFoundException e) {} // So there!
The do-nothing exception handler fools the compiler into thinking that the exception has
been handled. In the long run, this is clearly a bad idea. Exceptions were designed to transmit
problem reports to a competent handler. Installing an incompetent handler simply hides an
error condition that could be serious.
346 Chapter 7 Input/Output and Exception Handling
Do Not Use catch and finally in the Same try Statement
It is possible to have a fi nal 1 y clause following one or more catch clauses. Then the code in the
fi nal 1 y clause is executed whenever the try block is exited in any of three ways:
1 . After completing the last statement of the try block
2. After completing the last statement of a catch clause, if this try block caught an
exception
3. When an exception was thrown in the try block and not caught
It is tempting to combine catch and finally clauses, but the resulting code can be hard to
understand, and it is often incorrect. Instead, use two statements:
• a t ry/f ■ i nail y statement to close resources
• a separate try/catch statement to handle errors
For example,
try
{
PrintWriter out = new PrintWriter(filename) ;
try
{
Write output.
}
finally
{
out . close!) ;
}
}
catch (IOException exception)
{
Handle exception.
}
Note that the nested statements work correctly if the Pri ntWri ter constructor throws an excep¬
tion, too.
Automatic Resource Management in Java 7
In Java 7, you can use a new form of the try block that automatically closes a PrintWriter or
Scanner object. Here is the syntax:
try (PrintWriter out = new PrintWriter(filename))
{
Write output to out .
}
The close method is automatically invoked on the out object when the try block ends, whether
or not an exception has occurred. A fi nal 1 y statement is not required.
7.5 Application: Handling Input Errors 34 7
Random Fact 7.2 The Ariane Rocket Incident
1 J The European Space
^ • B" Agency (ESA), Europe's
counterpart to NASA, had developed a
rocket model called Ariane that it had
successfully used several times to
launch satellites and scientific experi¬
ments into space. However, when a new
version, the Ariane 5, was launched on
June 4, 1 996, from ESA’s launch site
in Kourou, French Guiana, the rocket
veered off course about 40 seconds
after liftoff. Flying at an angle of more
than 20 degrees, rather than straight
up, exerted such an aerodynamic force
that the boosters separated, which trig¬
gered the automatic self-destruction
mechanism. The rocket blew itself up.
The ultimate cause of this accident
was an unhandled exception! The
rocket contained two identical devices
(called inertial reference systems) that
processed flight data from measuring
devices and turned the data into infor¬
mation about the rocket position.
The onboard computer used the posi¬
tion information for controlling the
boosters. The same inertial reference
systems and computer software had
worked fine on the Ariane 4.
However, due to design changes
to the rocket, one of the sensors mea¬
sured a larger acceleration force than
had been encountered in the Ariane 4.
That value, expressed as a floating¬
point value, was stored in a 16-bit
integer (like a short variable in Java).
Unlike Java, the Ada language, used
for the device software, generates an
exception if a floating-point number is
too large to be converted to an integer.
Unfortunately, the programmers of the
device had decided that this situation
would never happen and didn’t provide
an exception handler.
When the overflow did happen, the
exception was triggered and, because
there was no handler, the device shut
itself off. The onboard computer sensed
the failure and switched over to the
backup device. However, that device
had shut itself off for exactly the same
reason, something that the designers
of the rocket had not expected. They
figured that the devices might fail for
mechanical reasons, and the chance of
two devices having the same mechani¬
cal failure was considered remote. At
that point, the rocket was without reli¬
able position information and went off
course.
Perhaps it would have been better if
the software hadn’t been so thorough?
If it had ignored the overflow, the
device wouldn’t have been shut off. It
would have computed bad data. But
then the device would have reported
wrong position data, which could have
been just as fatal. Instead, a correct
implementation should have caught
overflow exceptions and come up with
some strategy to recompute the flight
data. Clearly, giving up was not a
reasonable option in this context.
The advantage of
the exception-handling
mechanism is that it
makes these issues
explicit to program¬
mers — something to
think about when you
curse the Java compiler
for complaining about
uncaught exceptions.
The Explosion of the Ariane Rocket
7.5 Application: Handling Input Errors
This section walks through an example program that includes exception handling.
The program, DataAnal yzer . j ava, asks the user for the name of a file. The file is expected
to contain data values. The first line of the file should contain the total number of val¬
ues, and the remaining lines contain the data. A typical input file looks like this:
3
1.45
-2.1
0.05
348 Chapter 7 Input/Output and Exception Handling
When designing a
program, ask your¬
self what kinds of
exceptions can occur.
For each exception,
you need to decide
which part of
your program
can competently
handle it.
What can go wrong? There are two principal risks.
• The file might not exist.
• The file might have data in the wrong format.
Who can detect these faults? The Scanner constructor will throw an exception when
the file does not exist. The methods that process the input values need to throw an
exception when they find an error in the data format.
What exceptions can be thrown? The Scanner constructor throws a FileNot-
FoundException when the file does not exist, which is appropriate in our situation.
When there are fewer data items than expected, or when the file doesn’t start with the
count of values, the program will throw an NoSuchEl ementExcepti on. Finally, when there
are more inputs than expected, an IOException should be thrown.
Who can remedy the faults that the exceptions report? Only the main method of
the DataAnal yzer program interacts with the user, so it catches the exceptions, prints
appropriate error messages, and gives the user another chance to enter a correct file:
// Keep trying until there are no more exceptions
boolean done = false;
while (!done)
{
try
{
Prompt user for file name.
doublet] data = readFile(filename) ;
Process data.
done = true;
}
catch (FileNotFoundException exception)
{
System. out. println("File not found.");
}
catch (NoSuchEl ementExcepti on exception)
{
System. out. println("File contents invalid.");
}
catch (IOException exception)
{
exception. printStackTrace() ;
}
}
The first two catch clauses in the mai n method give a human-readable error report if
bad data was encountered or the file was not found. However, if another IOException
occurs, then it prints a stack trace so that a programmer can diagnose the problem.
The following readFile method constructs the Scanner object and calls the readData
method. It does not handle any exceptions. If there is a problem with the input file, it
simply passes the exception to its caller.
public static doubl e [] readFile(String filename) throws IOException
{
File inFile = new File(filename) ;
Scanner in = new Scanner(inFile);
try
{
7.5 Application: Handling Input Errors 349
return readData(in) ;
}
finally
{
in.closeO ;
}
}
Note how the finally clause ensures that the file is closed even when an exception
occurs.
Also note that the throws clause of the readFile method need not include the File-
NotFoundExcepti on class because it is a special case of an IOExcepti on.
The readData method reads the number of values, constructs an array, and fills it
with the data values.
public static double [] readData(Scanner in) throws IOExcepti on
{
int numberOfValues = in.nextlnt(); // May throw NoSuchElementExcepti on
doublet] data = new double[numberOfValues] ;
for (int i = 0; i < numberOfValues; i++)
{
data[i] = in . nextDouble() ; // May throw NoSuchElementExcepti on
}
if (in.hasNextO)
{
throw new IOException("End of file expected");
}
return data;
}
As discussed in Section 7.2.7, the calls to the nextlnt and nextDouble methods can throw
a NoSuchElementExcepti on when there is no input at all or an InputMi smatchException if the
input is not a number. As you can see from Figure 2 on page 340, an InputMi smatch-
Excepti on is a special case of a NoSuchEl ementExcepti on.
You need not declare the NoSuchEl ementExcepti on in the throws clause because it is not
a checked exception, but you can include it for greater clarity.
There are three potential errors:
• The file might not start with an integer.
• There might not be a sufficient number of data values.
• There might be additional input after reading all data values.
In the first two cases, the Scanner throws a NoSuchEl ementExcepti on. Note again that this
is not a checked exception— we could have avoided it by calling hasNextlnt/hasNext-
Doubl e first. However, this method does not know what to do in this case, so it allows
the exception to be sent to a handler elsewhere.
When we find that there is additional unexpected input, we throw an IOExcepti on.
To see the exception handling at work, look at a specific error scenario.
1. main calls readFile.
2. readFile calls readData.
3. readData calls Scanner, nextlnt.
4. There is no integer in the input, and Scanner, nextlnt throws a NoSuchElement¬
Excepti on.
350 Chapter 7 Input/Output and Exception Handling
5 . readData has no catch clause. It terminates immediately.
6. readFi 1 e has no catch clause. It terminates immediately after executing the
f ■ i nail y clause and closing the file.
7. The first catch clause in mai n is for a FileNotFoundException. The exception that is
currently being thrown is a NoSuchElementException, and this handler doesn’t
apply.
8. The next catch clause is for a NoSuchElementException, and execution resumes
here. That handler prints a message to the user. Afterward, the user is given
another chance to enter a file name. Note that the statements for processing the
data have been skipped.
This example shows the separation between error detection (in the readData method)
and error handling (in the main method). In between the two is the readFi le method,
which simply passes the exceptions along.
section_5/DataAnalyzer.java
1 import java. io. File;
2 import java. io. FileNotFoundException;
3 import java.io.IOException;
4 import java. util .Scanner;
5 import java. util .NoSuchElementException;
6
7 /**
8 This program processes a file containing a count followed by data values.
9 If the file doesn’t exist or the format is incorrect, you can specify another file.
10 V
11 public class DataAnalyzer
12 {
13 public static void main(String[] args)
14 {
15 Scanner in = new Scanner(System.in) ;
16
17 // Keep trying until there are no more exceptions
18
19 boolean done = false;
20 while C ! done)
21 {
22 try
23 {
24 System. out. print( Please enter the file name; );
25 String filename = in.nextf);
26
27 double [] data = readFi 1 e (fi 1 ename) ;
28
29 // As an example for processing the data, we compute the sum
30
31 doubl e sum = 0;
32 for (double d : data) { sum = sum + d; }
33 System. out. println( 'The sum is + sum);
34
35 done = true;
36 }
37 catch (FileNotFoundException exception)
38 {
39
System. out. println("File not found. );
7.5 Application: Handling Input Errors 351
40 }
41 catch (NoSuchElementExcepti on exception)
42 {
43 System. out. println( File contents invalid );
44 }
45 catch (IOException exception)
46 {
47 exception. printStackTrace() ;
48 }
49 }
50 }
51
52 /**
53 Opens a file and reads a data set.
54 @param filename the name of the file holding the data
55 ©return the data in the file
56 */
57 public static double[] readFile(String filename) throws IOException
58 {
59 File inFile = new File(filename);
60 Scanner in = new Scanner(inFile);
61 try
62 {
63 return readData(in) ;
64 }
65 finally
66 {
67 in.closeO;
68 }
69 }
70
71 /**
72 Reads a data set.
73 ©param i n the scanner that scans the data
74 ©return the data set
75 */
76 public static double[] readData(Scanner in) throws IOException
77 {
78 int numberOfValues = in.nextlnt(); // May throw NoSuchElementExcepti on
79 doublet] data = new double[numberOfValues] ;
80
81 for (int i = 0; i < numberOfValues; i++)
82 {
83 data[i] = in .nextDoubleO ; // May throw NoSuchElementExcepti on
84 }
85
86 if (in.hasNextO)
87 {
88 th row new IOException(”End of file expected'1);
89 }
90 return data;
91 }
92 }
22. Why d oesn’t the readFi le method catch any exceptions?
23. Consider the try/fi nally statement in the readFi le method. Why was the in vari¬
able declared outside the try block?
352 Chapter 7 Input/Output and Exception Handling
24. Suppose the user specifies a file that exists and is empty. Trace the flow of execu¬
tion in the DataAnalyzer program.
25. Why didn’t the readData method call hasNextlnt/hasNextDouble to ensure that the
NoSuchElementException is not thrown?
Practice It Now you can try these exercises at the end of the chapter: R7.15, R7.16, P7.13.
VIDEO EXAMPLE 7.2
Detecting Accounting Fraud
Awileyo
'PLUS
In this Video Example, you will see how to detect accounting fraud
by analyzing digit distributions. You will learn how to read data
from the Internet and handle exceptional situations.
CHAPTER SUMMARY
Develop programs that read and write files.
• Use the Scanner class for reading text files.
• When writing text files, use the Pri ntWriter class and the pri nt/println/pn ntf
methods.
• Close all files when you are done processing them.
Be able to process text in files.
• The next method reads a string that is delimited by white space.
• The Character class has methods for classifying characters.
• The nextLi ne method reads an entire line.
• If a string contains the digits of a number, you use the Integer .parselnt or
DoubI e . parseDoubl e method to obtain the number value.
Process the command line arguments of a program.
• Programs that start from the command line receive the com¬
mand line arguments in the mai n method.
Use exception handling to transfer control from an error location to an error handler.
To signal an exceptional condition, use the throw statement to throw an exception
object.
When you throw an exception, processing continues in an exception handler.
Place the statements that can cause an exception inside a try
block, and the handler inside a catch clause.
© Available online in WileyPLUS and at www.wiIey.com/conege/horstmann.
Review Exercises 353
• Checked exceptions are due to external circumstances that the programmer
cannot prevent. The compiler checks that your program handles these exceptions.
• Add a throws clause to a method that can throw a checked exception.
• Once a t ry block is entered, the statements in a f i nail y clause are
guaranteed to be executed, whether or not an exception is
thrown.
• Throw an exception as soon as a problem is detected. Catch it
only when the problem can be handled.
Use exception handling in a program that processes input.
• When designing a program, ask yourself what kinds of exceptions can occur.
• For each exception, you need to decide which part of your program can compe¬
tently handle it.
STANDARD LIBRARY ITEMS INTRODUCED IN THIS CHAPTER
java. io. File
java.io.FileNot Found Excepti on
j ava .io. IOExcepti on
java.io.PrintWriter
close
j ava. lang. Character
isDigit
isLetter
isLowerCase
isUpperCase
isWhiteSpace
java. lang. Double
parseDouble
java. lang. Error
java. lang. Integer
parselnt
j ava. 1 ang . II 1 egal ArgumentExcepti on
java. 1 ang .Null Poi nterExcepti on
j ava . 1 ang . Number FormatExcepti on
j ava .lang. Runti me Except! on
java.lang.Throwable
getMessage
printStackTrace
java. net. URL
openStream
j ava . uti 1 . InputMi smatchExcepti on
j ava . uti 1 . NoSuchEl ementExcepti on
java. util .Scanner
close
hasNextLi ne
nextLi ne
useDelimiter
j avax . swi ng . 1 Fi 1 eChooser
getSelectedFile
showOpenDialog
showSaveDialog
REVIEW EXERCISES
■ ■ R7. 1 What happens if you try to open a file for reading that doesn’t exist? What happens if
you try to open a file for writing that doesn’t exist?
■ ■ R7.2 What happens if you try to open a file for writing, but the file or device is write-
protected (sometimes called read-only) ? Try it out with a short test program.
■ R7.3 How do you open a file whose name contains a backslash, like c: temp\output.dat?
■ R7.4 If a program Woozle is started with the command
java Woozle -Dname=piglet -I\eeyore -v heff.txt a.txt lump.txt
what are the values of args[0], args[l], and so on?
. R7.5 What is the difference between throwing an exception and catching an exception?
354 Chapter 7 Input/Output and Exception Handling
■ R7.6
• ■ R7.7
■ ■ R7.8
• ■ R7.9
■ ■ R7.10
■ ■ R7.11
. R7.12
.. R7.13
■ ■ R7.14
■ ■ R7.15
■ ■ R7.16
What is a checked exception? What is an unchecked exception? Give an example for
each. Which exceptions do you need to declare with the throws reserved word?
Why don’t you need to declare that your method might throw an IndexOutOfBounds-
Exception?
When your program executes a throw statement, which statement is executed next?
What happens if an exception does not have a matching catch clause?
What can your program do with the exception object that a catch clause receives?
Is the type of the exception object always the same as the type declared in the catch
clause that catches it? If not, why not?
What is the purpose of the fi nal 1 y clause? Give an example of how it can be used.
What happens when an exception is thrown, the code of a f ■ i nail y clause executes,
and that code throws an exception of a different kind than the original one? Which
one is caught by a surrounding catch clause? Write a sample program to try it out.
Which exceptions can the next and nextlnt methods of the Scanner class throw? Are
they checked exceptions or unchecked exceptions?
Suppose the program in Section 7.5 reads a file containing the following values:
1
2
S
4
What is the outcome? How could the program be improved to give a more accurate
error report?
Can the readFile method in Section 7.5 throw a Null PointerException? If so, how?
PROGRAMMING EXERCISES
■ P7.1 Write a program that carries out the following tasks:
Open a file with the name hello.txt.
Store the message "Hello, World!" in the file.
Close the file.
Open the same file again.
Read the message into a string variable and print it.
■ P7.2 Write a program that reads a file containing text. Read each line and send it to the
output file, preceded by line numbers. If the input file is
Mary had a little lamb
Whose fleece was white as snow.
And everywhere that Mary went,
The lamb was sure to go!
then the program produces the output file
/* 1 */ Mary had a little lamb
/* 2 */ Whose fleece was white as snow.
/* 3 */ And everywhere that Mary went,
/* 4 */ The lamb was sure to go!
Programming Exercises 355
The line numbers are enclosed in /* */ delimiters so that the program can be used for
numbering Java source files.
Prompt the user for the input and output file names.
P7.3 Repeat Exercise P7.2, but allow the user to specify the file name on the command-
line. If the user doesn’t specify any file name, then prompt the user for the name.
P7.4 Write a program that reads a file containing two columns of floating-point numbers.
Prompt the user for the file name. Print the average of each column.
P7.5 Write a program that asks the user for a file name and prints the number of charac¬
ters, words, and lines in that file.
P7.6 Write a program Fi nd that searches all files specified on the command line and prints
out all lines containing a specified word. For example, if you call
java Find ring report.txt address.txt Homework. java
then the program might print
report.txt: has broken up an international ring of DVD bootleggers that
address.txt: Kris Kringle, North Pole
address.txt: Homer Simpson, Springfield
Homework. java: String filename;
The specified word is always the first command line argument.
P7.7 Write a program that checks the spelling of all words in a file. It should read each
word of a file and check whether it is contained in a word list. A word list is avail¬
able on most Linux systems in the file /usr/share/dict/words. (If you don’t have access
to a Linux system, your instructor should be able to get you a copy.) The program
should print out all words that it cannot find in the word list.
P7.8 Write a program that replaces each line of a file with its reverse. For example, if you
run
java Reverse HelloPrinter. java
then the contents of HelloPrinter. java are changed to
retnirPolleH ssalc cilbup
{
)sgra ] [gnirtS(niam diov citats cilbup
{
wodniw elosnoc eht ni gniteerg a yalpsiD //
;)" ! dl roW ,olleH"(nltni rp.tuo.metsyS
}
}
Of course, if you run Reverse twice on the same file, you get back the original file.
P7.9 Write a program that reads each line in a file, reverses its lines, and writes them to
another file. For example, if the file i nput . txt contains the lines
Mary had a little lamb
Its fleece was white as snow
And everywhere that Mary went
The lamb was sure to go.
and you run
reverse input.txt output.txt
then output . txt contains
356 Chapter 7 Input/Output and Exception Handling
The lamb was sure to go.
And everywhere that Mary went
Its fleece was white as snow
Mary had a little lamb
■ ■ P7. 1 0 Get the data for names in prior decades from the Social Security Administration.
Paste the table data in files named babynames80s.txt, etc. Modify the worked_example_l/
BabyNames . java program so that it prompts the user for a file name. The numbers in
the files have comma separators, so modify the program to handle them. Can you
spot a trend in the frequencies?
■ ■ P7.1 1 Write a program that reads in worked_example_l/babynames. txt and produces two files,
boynames . txt and gi rl names . txt, separating the data for the boys and girls.
■ ■ ■ P7.12 Write a program that reads a file in the same format as worked_example_l/babynames . txt
and prints all names that are both boy and girl names (such as Alexis or Morgan).
■ ■ P7. 1 3 Write a program that asks the user to input a set of floating-point values. When the
user enters a value that is not a number, give the user a second chance to enter the
value. After two chances, quit reading input. Add all correctly specified values and
print the sum when the user is done entering data. Use exception handling to detect
improper inputs.
■ ■ P7.14 Using the mechanism described in Special Topic 7.1, write a program that reads all
data from a web page and writes them to a file. Prompt the user for the web page
URL and the file.
■ ■ P7.1 5 Using the mechanism described in Special Topic 7.1, write a program that reads all
data from a web page and prints all hyperlinks of the form
<a href ="link">link text</a>
Extra credit if your program can follow the links that it finds and find links in those
web pages as well. (This is the method that search engines such as Google use to find
web sites.)
■ ■ Business P7.16 A hotel salesperson enters sales in a text file. Each line contains the following,
separated by semicolons: The name of the client, the service sold (such as Dinner,
Conference, Lodging, and so on), the amount of the sale, and the date of that event.
Write a program that reads such a file and displays the total amount for each service
category. Display an error if the file does not exist or the format is incorrect.
■ ■ Business P7.1 7 Write a program that reads a text file as described in Exercise P7.f 6, and that writes a
separate file for each service category, containing the entries for that category. Name
the output files Dinner.txt, Conference.txt, and so on.
■ ■ Business P7.18 A store owner keeps a record of daily cash transactions in a text file. Each line
contains three items: The invoice number, the cash amount, and the letter P if the
amount was paid or R if it was received. Items are separated by spaces. Write a pro¬
gram that prompts the store owner for the amount of cash at the beginning and end
of the day, and the name of the file. Your program should check whether the actual
amount of cash at the end of the day equals the expected value.
Programming Exercises 35 7
Science P7. 1 9 After the switch in the figure below closes, the voltage (in volts) across the capacitor
is represented by the equation
v(t) = s( l-e-VCRC))
Suppose the parameters of the electric circuit are B- 12 volts, R = 500 Q, and
C = 0.25 pF. Consequently
v(t) = 12(l-e_0-008r)
where t has units of ps. Read a file params . txt containing the values for B, R, C, and
the starting and ending values for t. Write a file rc . txt of values for the time t and the
corresponding capacitor voltage v(t), where t goes from the given starting value to
the given ending value in 100 steps. In our example, if t goes from 0 to 1,000 ps, the
twelfth entry in the output file would be:
110 7.02261
Science P7.20 The figure below shows a plot of the capacitor voltage from the circuit shown in
Exercise P7.19. The capacitor voltage increases from 0 volts to B volts. The “rise
time” is defined as the time required for the capacitor voltage to change from
v1 = 0.05 x B tov2 = 0.95 x B.
The file rc . txt contains a list of values of time t and the corresponding capacitor
voltage v{t). A time in ps and the corresponding voltage in volts are printed on the
same line. For example, the line
110 7.02261
indicates that the capacitor voltage is 7.02261 volts when the time is 1 10 ps. The time
is increasing in the data file.
Write a program that reads the file rc . txt and uses the data to calculate the rise time.
Approximate B by the voltage in the last line of the file, and find the data points that
are closest to 0.05 x B and 0.95 x B.
358 Chapter 7 Input/Output and Exception Handling
■ ■ Science P7.21
Suppose a file contains bond energies and bond lengths for covalent bonds in the
following format:
Single, double,
or triple bond
Bond energy
(kj/mol)
Bond length
(nm)
C|C
370
0.154
C||C
680
0.13
C|||C
890
0.12
C|H
435
0.11
C|N
305
0.15
C|0
360
0.14
C|F
450
0.14
qci
340
0.18
0|H
500
0.10
0|0
220
0.15
0|Si
375
0.16
N|H
430
0.10
N|0
250
0.12
F|F
160
0.14
H|H
435
0.074
Write a program that accepts data from one column and returns the corresponding
data from the other columns in the stored file. If input data matches different rows,
then return all matching row data. For example, a bond length input of 0.12 should
return triple bond C|||C and bond energy 890 kj/mol and single bond N|0 and bond
energy 250 kj/mol.
Answers to Self-Check Questions 359
ANSWERS TO SELF-CHECK QUESTIONS
1 . When the PrintWriter object is created, the out¬
put file is emptied. Sadly, that is the same file as
the input file. The input file is now empty and
the while loop exits immediately.
2. The program throws a FileNotFoundException
and terminates.
3 . Open a scanner for the fi le.
For each number in the scanner
Add the number to an array.
Close the scanner.
Set total to 0.
Open a print writer for the file.
For each number in the array
Write the number to the print writer.
Add the number to total.
Write total to the print writer.
Close the print writer.
4. Add a variable count that is incremented when¬
ever a number is read. In the end, print the
average, not the total, as
out. printf ("Average: %8.2f\n", total / count);
Because the string "Average" is three characters
longer than "Total ", change the other output to
out.printf("%18.2f\n", value).
5. Add a variable count that is incremented when¬
ever a number is read. Only write a new line
when it is even.
count++;
out.printf("%8.2f", value);
if (count % 2 == 0) { out.printlnO ; }
At the end of the loop, write a new line if count
is odd, then write the total:
if (count % 2 == 1) { out.printlnO; }
out.printf("Total : %10.2f\n", total);
6. word is "Hello, " and i nput is "World ! "
7. Because 995.0 is not an integer, the call
i n. hasNextlntO returns false, and the call
i n. nextlntO is skipped. The value of number
stays 0, and input is set to the string "995.0".
8. xl is set to 6000000. Because a comma is not
considered a part of a floating-point number
in Java, the second call to nextDouble causes an
input mismatch exception and x2 is not set.
9. Read them as strings, and convert those strings
to numbers that are not equal to N/A:
String input = in.next();
if (!input.equals("N/A"))
{
double value = Double. parseDouble(input);
Process value.
}
1 0. Locate the last character of the country name:
int j = i - 1;
while ( ! Character . i sWhi teSpace(l i ne . charAt(j)))
{
j— ;
}
Then extract the country name:
String countryName = line.substring(0, j + 1) ;
T 1 . args[0] is "-d" and args[l] is "filel.txt"
key
mFile
outFile
i
arg /
*
null
^ 1
-3
filel.txt
r
filel.txt |
i
Then the program prints a message
Usage: java CaesarCipher [-d] infile outfile
1 3. The program will run correctly. The loop that
parses the options does not depend on the
positions in which the options appear.
14. FDHVDU
15. Add the lines
else if (option == ' k ' )
{
key = Integer. parselnt(
args[i] ,substring(2));
}
after line 27 and update the usage information.
16. It is still 100. The last statement was not
executed because the exception was thrown.
17. if (amount < 0)
{
throw new IllegalArgumentException(
"Negative amount") ;
}
360 Chapter 7 Input/Output and Exception Handling
18. The Scanner constructor succeeds because
the file exists. The nextlnt method throws
a NoSuchElementException. This is not an
IOException. Therefore, the error is not caught.
Because there is no other handler, an error
message is printed and the program terminates.
1 9. Because programmers should simply check
that their array index values are valid instead
of trying to handle an ArraylndexOutOfBounds-
Exception.
20. No. You can catch both exception types in the
same way, as you can see in the code example
on page 339.
2 1 . There are two mistakes. The Pri ntWriter con¬
structor can throw a FileNotFoundException. You
should supply a throws clause. And if one of the
array elements is null, a NullPointerException is
thrown. In that case, the out . close () statement
is never executed. You should use a t ry/f i nail y
statement.
22. The exceptions are better handled in the mai n
method.
23. If it had been declared inside the try block, its
scope would only have extended until the end
of the try block, and it would not have been
accessible in the f i nail y clause.
24. main calls readFile, which calls readData. The call
in.nextlntO throws a NoSuchElementException.
The readFi le method doesn’t catch it, so it
propagates back to mai n, where it is caught.
An error message is printed, and the user can
specify another file.
25. We want to throw that exception, so that
someone else can handle the problem of a bad
data file.
CHAPTER
8
OBJECTS AND
CLASSES
CHAPTER COALS
To understand the concepts of classes,
objects, and encapsulation
To implement instance variables, methods, and constructors
To be able to design, implement, and test your own classes
To understand the behavior of object references, static variables, and static methods
CHAPTER CONTENTS
8.1 OBJECT-ORIENTED
PROGRAMMING 362
8.2 IMPLEMENTING A SIMPLE CLASS 364
Syntax 8.1: Instance Variable Declaration 365
8.3 SPECIFYING THE PUBLIC INTERFACE
OF A CLASS 367
Special Topic 8.1 : Thejavadoc Utility 370
8.4 DESIGNING THE DATA
REPRESENTATION 371
8.5 IMPLEMENTING INSTANCE
METHODS 372
Syntax 8.2: Instance Methods 373
Programming Tip 8.1: All Instance Variables
Should Be Private; Most Methods Should
Be Public 374
8.6 CONSTRUCTORS 375
Syntax 8.3: Constructors 376
Common Error 8.1 : Forgetting to Initialize Object
References in a Constructor 378
Common Error 8.2: Trying to Call
a Constructor 379
Common Error 8.3: Declaring a Constructor
as void 379
Special Topic 8.2: Overloading 380
8.7 TESTING A CLASS 380
HowTo8. 1: Implementing a Class 382
Worked Example 8.1 : Implementing a Bank
Account Class ©
Video Example 8. 1 : Pay i ng Off a Loan ©
8.8 PROBLEM SOLVING:
TRACING OBJECTS 386
8.9 PROBLEM SOLVING: PATTERNS
FOR OBJECT DATA 388
Video Example 8.2: Modeling a Robot Escaping
from a Maze ©
Random Fact 8.1 : Electronic Voting Machines 394
8.10 OBJECT REFERENCES 395
Special Topic 8.3: Calling One Constructor
from Another 399
8. 1 1 STATIC VARIABLES AND
METHODS 400
Random Fact 8.2: Open Source and
Free Software 402
This chapter introduces you to object-oriented program¬
ming, an important technique for writing complex pro¬
grams. In an object-oriented program, you don’t simply
manipulate numbers and strings, but you work with objects
that are meaningful for your application. Objects with
the same behavior (such as the windmills to the left) are
grouped into classes. A programmer provides the desired
behavior by specifying and implementing methods for
these classes. In this chapter, you will learn how to discover,
specify, and implement your own classes, and how to use
them in your programs.
8.1 Object-Oriented Programming
A class describes a
set of objects with
the same behavior.
You have learned how to structure your programs by decomposing tasks into meth¬
ods. This is an excellent practice, but experience shows that it does not go far enough.
It is difficult to understand and update a program that consists of a large collection of
methods.
To overcome this problem, computer scientists invented object-oriented pro¬
gramming, a programming style in which tasks are solved by collaborating objects.
Each object has its own set of data, together with a set of methods that act upon the
data.
You have already experienced this programming style when you used strings, the
System. out object, or a Scanner object. Each of these objects has a set of methods. For
example, you can use the 1 ength and substri ng methods to work with Stri ng objects.
When you develop an object-oriented program, you create your own objects that
describe what is important in your application. For example, in a student database
you might work with Student and Course objects. Of course, then you must supply
methods for these objects.
In Java, a programmer doesn’t implement a single object. Instead, the program¬
mer provides a class. A class describes a set of objects with the same behavior. For
example, the Stri ng class describes the behavior of all strings. The class specifies how
A Car class describes passenger vehicles that can
carry 4-5 people and a small amount of luggage.
362
8.1 Object-Oriented Programming 363
Every class has a
public interface: a
collection of methods
through which the
objects of the class
can be manipulated.
Encapsulation is
the act of providing
a public interface and
hiding the implemen¬
tation details.
Encapsulation
enables changes in
the implementation
without affecting
users of a class.
a string stores its characters, which methods can be used with strings, and how the
methods are implemented.
In contrast, the PrintStream class describes the behavior of objects that can be used
to produce output. One such object is System, out, and you have seen in Chapter 7 how
to create PrintStream objects that send output to a file.
Each class defines a specific set of methods that you can use with its objects. For
example, when you have a Stri ng object, you can invoke the 1 ength method:
"Hello, World" . length()
We say that the length method is a method of the String class. The Pri ntStream class has
a different set of methods. For example, the call
System. out. 1 ength ()
would be illegal — the PrintStream class has no length method. However, PrintStream
has a println method, and the call
out.println("Hello, World!")
is legal.
The set of all methods provided by a class, together with a description of their
behavior, is called the public interface of the class.
When you work with an object of a class, you do not know how the object stores
its data, or how the methods are implemented. You need not know how a Stri ng orga¬
nizes a character sequence, or how a PrintWriter object sends data to a file. All you
need to know is the public interface — which methods you can apply, and what these
methods do. The process of providing a public interface, while hiding the implemen¬
tation details, is called encapsulation.
When you design your own classes, you will use encapsulation. That is, you will
specify a set of public methods and hide the implementation details. Other program¬
mers on your team can then use your classes without having to know their imple¬
mentations, just as you are able to make use of the Stri ng and Pri ntStream classes.
If you work on a program that is being developed over a long period of time, it is
common for implementation details to change, usually to make objects more efficient
or more capable. When the implementation is hidden, the improvements do not affect
the programmers that use the objects.
You cam drive a car by operating the
steering wheel and pedals, without
knowing how the engine works.
Similarly, you use an object through its
methods. The implementation is hidden.
364 Chapter 8 Objects and Classes
A driver of an electric car doesn’t
have to learn new controls even
though the car engine is very
different. Neither does the program¬
mer who uses an object with an
improved implementation — as long
as the same methods are used.
1. Is the method call "Hello, World" .println() legal? Why or why not?
2. When using a Stri ng object, you do not know how it stores its characters. How
can you access them?
3. Describe a way in which a String object might store its characters.
4. Suppose the providers of your Java compiler decide to change the way that a
String object stores its characters, and they update the String method implemen¬
tations accordingly. Which parts of your code do you need to change when you
get the new compiler?
Practice It
Now you can try these exercises at the end of the chapter: R8.1, R8.4.
8.2 Implementing a Simple Class
In this section, we look at the implementation of
a very simple class. You will see how objects store
their data, and how methods access the data of an
object. Knowing how a very simple class operates
will help you design and implement more com¬
plex classes later in this chapter.
Our first example is a class that models a tally
counter, a mechanical device that is used to count
people — for example, to find out how many peo¬
ple attend a concert or board a bus (see Figure 1).
Whenever the operator pushes a button, the
counter value advances by one. We model this
operation with a count method. A physical coun¬
ter has a display to show the current value. In our Figure 1 A Tally Counter
simulation, we use a getVal ue method instead.
8.2 Implementing a Simple Class 365
An object’s instance
variables store
the data required
for executing
its methods.
Here is an example of using the Counter class. First, we construct an object of the
class:
Counter tally = new CounterO;
In Java, you use the new operator to construct objects. We will discuss object con¬
struction in more detail in Section 8.6.
Next, we invoke methods on our object. First, we invoke the count method twice,
simulating two button pushes. Then we invoke the getValue method to check how
many times the button was pushed.
tally ,count() ;
tally ,count() ;
int result = tally. getValueO ; // Sets result to 2
We can invoke the methods again, and the result will be different.
tally ,count() ;
tally ,count() ;
result = tally. getValueO ; // Sets result to 4
As you can see, the tal 1 y object remembers the effect of prior method calls.
When implementing the Counter class, we need to specify how each counter object
stores its data. In this simple example, that is very straightforward. Each counter
needs a variable that keeps track of how many times the counter has been advanced.
An object stores its data in instance variables. An instance of a class is an object of
the class. Thus, an instance variable is a storage location that is present in each object
of the class.
You specify instance variables in the class declaration:
public class Counter
{
private int value;
}
An instance variable declaration consists of the following parts:
• An modifier (private)
• The type of the instance variable (such as i nt)
• The name of the instance variable (such as val ue)
Syntax 8.1
Instance Variable Declaration
Syntax public class ClassName
{
private typeName variableName ;
}
Instance variables should
always be private.
public class Counter Each object of this class
{ has a separate copy of
private int value; this instance variable.
}
Type of the variable
366 Chapter 8 Objects and Classes
Each object of a class
has its own set of
instance variables.
An instance method
can access the
instance variables
of the object on
which it acts.
A private instance
variable can only
be accessed by the
methods of its
own class.
ONLINE EXAMPLE
The complete
Counter class and a
CounterTester
program.
Each object of a class has its own set of instance variables. For example, if concert-
Counter and boardingCounter are two objects of the Counter class, then each object has its
own val ue variable (see Figure 2).
As you will see in Section 8.6, the instance variable value is set to 0 when a Counter
object is constructed.
Next, let us have a quick look at the implementation of the methods of the Counter
class. The count method advances the counter value by 1.
public void count()
{
value = value + 1;
}
We will cover the syntax of the method header in Section 8.3. For now, focus on the
body of the method inside the braces.
Note how the count method increments the instance variable val ue. Which instance
variable? The one belonging to the object on which the method is invoked. For exam¬
ple, consider the call
concertCounter.countO ;
This call advances the value variable of the concertCounter object.
The methods that you invoke on an object are called instance methods to distin¬
guish them from the static methods of Chapter 5.
Finally, look at the other instance method of the Counter class. The getVal ue method
returns the current value:
public int getVal ue()
{
return value;
}
This method is required so that users of the Counter class can find out how often a
particular counter has been clicked. A user cannot simply access the value instance
variable. That variable has been declared with the access specifier private.
The private specifier restricts access to the methods of the same class. For example,
the value variable can be accessed by the count and getVal ue methods of the Counter
class but not a method of another class. Those other methods need to use the getVal ue
method if they want to find out the counter’s value, or the count method if they want
to change it.
concertCounter
boardi ngCounter
Instance
variables
Figure 2 Instance Variables
8.B Specifying the Public Interface of a Class 36 7
These clocks have common behavior, but each of them has a different state. Similarly, objects of
a class can have their instance variables set to different values.
Private instance variables are an essential part of encapsulation. They allow a pro¬
grammer to hide the implementation of a class from a class user.
5. Supply the body of a method public voi d reset () that resets the counter back to
zero.
6. Consider a change to the implementation of the counter. Instead of using an
integer counter, we use a string of | characters to keep track of the clicks, just like
a human might do.
public class Counter
{
private String strokes =
public void count()
{
strokes = strokes +
}
}
How do you implement the getVal ue method with this data representation?
7. Suppose another programmer has used the original Counter class. What changes
does that programmer have to make in order to use the modified class?
8. Suppose you use a class Clock with private instance variables hours and minutes.
How can you access these variables in your program?
Practice It Now you can try these exercises at the end of the chapter: P8.1, P8.2.
8.3 Specifying the Public Interface of a Class
When designing a class, you start by specifying its public interface. The public inter¬
face of a class consists of all methods that a user of the class may want to apply to its
objects.
Let’s consider a simple example. We want to use obj ects that simulate cash registers.
A cashier who rings up a sale presses a key to start the sale, then rings up each item. A
display shows the amount owed as well as the total number of items purchased.
368 Chapter 8 Objects and Classes
You can use method
headers and method
comments to specify
the public interface
of a class.
In our simulation, we want to call the following methods on a cash register object:
• Add the price of an item.
• Get the total amount owed, and the count of
items purchased.
to start a new sale.
Here is an outline of the CashRe