Help With Simple JAVA Code
Define a utility class for displaying values of type double. Call the class DoubleOut. Include all the methods in the class DollarFormat, all the methods from the class OutputFormat , and a method called scienceWrite that displays a value of type double using e notation, such as 2 .13e-12. (This e notation is also called scientific notation, which explains the method name.) When displayed in e notation, the number should appear with exactly one nonzero digit before the decimal point-unless the number is exactly zero. The method scienceWrite will not advance to the next line. Also add a method called scienceWriteln that is the same as scienceWrite except that it does advance to the next line. All but the last two method definitions can simply be copied from the text (or more easily from the source code for this book that is available on the Web.). Note that you will be overloading the method names write and writeln.
Write a driver program to test your method scienceWriteln. This driver program should use a stub for the method scienceWri te. (Note that this means you can write and test scienceWriteln before you even write scienceWrite.) Then write a driver program to test the method sci enceWri te. Finally, write a program that is a sort of super driver program that takes a double value as input and then displays it using the two writeln methods and the scienceWriteln method. Use the number 5 for the number of digits after the decimal point when you need to specify such a number. This super driver program should allow the user to repeat this testing with additional numbers of type double until the user is ready to end the program.
Rubric
1. Completeness and Correctness of Code - 40 points
2. Correct Execution - 40 points
3. Comments - 10 points
Pseudocode - 10 points
Chapter 1 Compiling a Java program, p. 20 Writing an algorithm, p. 25 Recognizing a hidden error, p. 28 Another applet example, p. 38 Writing an algorithm for Project 5, p. 42
Chapter 2 Another sample program, p. 61 Writing arithmetic expressions and statements, p. 72 Processing strings, p. 87 Pitfalls involving nextLine(), p. 97 Solving a conversion problem, p. 130 Solution to Project 13, p. 132
Chapter 3 Using multibranch if-else statements, p. 159 Using switch statements, p. 177 Solution to Project 2, p. 190 Responding to user input, p. 190
Chapter 4 Using nested while loops, p. 213 Comparing loop statements, p. 221 Debugging a loop, p. 238 Solution to Project 9, p. 252 Nesting for statements, p. 253
Chapter 5 Writing and involving methods, p. 292 Investigating public and private access, p. 300 Objects and references, p. 326 Exploring parameters of class types, p. 345 Developing a solution to Project 8, p. 363 Solution to Project 12, p. 366
Chapter 6 Writing construction, p. 387 Using static and non-static methods, p. 396 Writing and invoking overloaded methods, p. 433 Solving a similar problem, p. 468 Solution to Project 12, p. 469
(Continued on Inside Back Cover)
Through the power of practice and immediate personalized
feedback, MyProgrammingLab improves your performance.
Learn more at www.myprogramminglab.com
get with the programming
www.myprogramminglab.com
This page intentionally left blank
An Introduction to Problem Solving & Programming
™
This page intentionally left blank
Prentice Hall Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
An Introduction to Problem Solving & Programming
Walter Savitch University of California, San Diego
Contributor
Kenrick Mock University of Alaska Anchorage
6th edition™
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on appropriate page within text.
Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other coun- tries. Screen shots and icons reprinted with permission from the Microsoft Corporation. This book is not spon- sored or endorsed by or affiliated with the Microsoft Corporation.
Copyright © 2012, 2009, 2005, 2004, 2001 Pearson Education, Inc., publishing as Prentice Hall, 1 Lake Street, Upper Saddle River, New Jersey, 07458. All rights reserved. Manufactured in the United States of America. This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduc- tion, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopy- ing, recording, or likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 1 Lake Street, Upper Saddle River, New Jersey, 07458
Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Library of Congress Cataloging-in-Publication Data LIBRARY OF CONGRESS CATALOGING-IN-PUBLICATION DATA ON FILE
10 9 8 7 6 5 4 3 2 1—EB—15 14 13 12 11
ISBN 10: 0-132-16270-9 ISBN 13: 978-0-132-16270-8
Editorial Director: Marcia Horton Editor-in-Chief: Michael Hirsch Acquisitions Editor: Matt Goldstein Editorial Assistant: Chelsea Bell Director of Marketing: Patrice Jones Marketing Manager: Yezan Alayan Marketing Coordinator: Kathryn Ferranti Managing Editor: Jeff Holcomb Production Project Manager: Heather McNally Senior Operations Supervisor: Alan Fischer Operations Specialist: Lisa McDowell Art Director: Kristine Carney
Text Designer: Jerilyn Bockorick, Nesbitt Graphics, Inc. Cover Designer: Rachael Cronin Manager, Rights and Permissions: Michael Joyce Text Permission Coordinator: Jennifer Kennett Cover Art: Aron Jungermann / Getty Images Media Director: Daniel Sandin Media Project Manager: Wanda Rockwell Full-Service Project Management: Rose Kernan, Nesbitt Graphics, Inc. Composition: Glyph International Ltd. Interior Printer/Bindery: Edwards Brothers Cover Printer: Coral Graphics
www.pearsonhighered.com
viivii
Preface for Instructors
Welcome to the sixth edition of Java: An Introduction to Problem Solving & Programming. This book is designed for a first course in programming and computer science. It covers programming techniques, as well as the basics of the Java programming language. It is suitable for courses as short as one quar- ter or as long as a full academic year. No previous programming experience is required, nor is any mathematics, other than a little high school algebra. The book can also be used for a course designed to teach Java to students who have already had another programming course, in which case the first few chapters can be assigned as outside reading.
Changes in This Edition
The following list highlights how this sixth edition differs from the fifth edition: ■ Updates have been made for Java version 7, including strings in switch
statements and the use of type inference in generic instance creation. ■ Additional case studies including unit testing, use of the Comparable inter-
face, processing comma-separated value files, and others. ■ Chapter 5 now begins with a simpler class to more gradually introduce how
classes are constructed. ■ Chapter 8 has been reorganized with a greater emphasis and more examples
on polymorphism and interfaces. ■ Chapter 2 describes how to create a Swing application using the JFrame
class so thereafter students have the option of implementing graphics in applets or in an application.
■ Chapter 12 includes an overview of the Java Collections Framework and examples using the HashMap and HashSet classes.
■ A description of System.out.printf has been added to Chapter 2. ■ A description of Math.random has been added to Chapter 6. ■ Twenty new programming projects have been added. ■ New VideoNotes added throughout the text to enhance student
understanding of programming concepts and techniques.
viii PREFACE FOR INSTRUCTORS
Latest Java Coverage
All of the code in this book has been tested using a pre-release version of Oracle’s Java SE Development Kit (JDK), version 7.0. Any imported classes are standard and in the Java Class Library that is part of Java. No additional classes or specialized libraries are needed.
Flexibility
If you are an instructor, this book adapts to the way you teach, rather than making you adapt to the book. It does not tightly prescribe the sequence in which your course must cover topics. You can easily change the order in which you teach many chapters and sections. The particulars involved in rearranging material are explained in the dependency chart that follows this preface and in more detail in the “Prerequisites” section at the start of each chapter.
Early Graphics
Graphics supplement sections end each of the first ten chapters. This gives you the option of covering graphics and GUI programming from the start of your course. The graphics supplement sections emphasize applets but also cover GUIs built using the JFrame class. Any time after Chapter 8, you can move on to the main chapters on GUI programming (Chapters 13 through 15), which are now on the Web. Alternatively, you can continue through Chapter 10 with a mix of graphics and more traditional programming. Instructors who prefer to postpone the coverage of graphics can postpone or skip the graphics supplement sections.
Coverage of Problem-Solving and Programming Techniques
This book is designed to teach students basic problem-solving and program- ming techniques and is not simply a book about Java syntax. It contains numerous case studies, programming examples, and programming tips. Ad- ditionally, many sections explain important problem-solving and program- ming techniques, such as loop design techniques, debugging techniques, style techniques, abstract data types, and basic object-oriented programming tech- niques, including UML, event-driven programming, and generic programming using type parameters.
Early Introduction to Classes
Any course that really teaches Java must teach classes early, since everything in Java involves classes. A Java program is a class. The data type for strings of characters is a class. Even the behavior of the equals operator (==) depends on whether it is comparing objects from classes or simpler data items. Classes cannot be avoided, except by means of absurdly long and complicated “magic formulas.” This book introduces classes fairly early. Some exposure to using classes is given in Chapters 1 and 2. Chapter 5 covers how to define classes. All
PREFACE FOR INSTRUCTORS ix
of the basic information about classes, including inheritance, is presented by the end of Chapter 8 (even if you omit Chapter 7). However, some topics regarding classes, including inheritance, can be postponed until later in the course.
Although this book introduces classes early, it does not neglect traditional programming techniques, such as top-down design and loop design tech- niques. These older topics may no longer be glamorous, but they are informa- tion that all beginning students need.
Generic Programming
Students are introduced to type parameters when they cover lists in Chapter 12. The class ArrayList is presented as an example of how to use a class that has a type parameter. Students are then shown how to define their own classes that include a type parameter.
Language Details and Sample Code
This book teaches programming technique, rather than simply the Java lan- guage. However, neither students nor instructors would be satisfied with an introductory programming course that did not also teach the programming language. Until you calm students’ fears about language details, it is often im- possible to focus their attention on bigger issues. For this reason, the book gives complete explanations of Java language features and lots of sample code. Programs are presented in their entirety, along with sample input and output. In many cases, in addition to the complete examples in the text, extra complete examples are available over the Internet.
Self-Test Questions
Self-test questions are spread throughout each chapter. These questions have a wide range of difficulty levels. Some require only a one-word answer, whereas others require the reader to write an entire, nontrivial program. Complete an- swers for all the self-test questions, including those requiring full programs, are given at the end of each chapter.
Exercises and Programming Projects
Completely new exercises appear at the end of each chapter. Since only you, and not your students, will have access to their answers, these exercises are suitable for homework. Some could be expanded into programming projects. However, each chapter also contains other programming projects, several of which are new to this edition.
Support Material
The following support materials are available on the Internet at www.pearsonhighered.com/irc:
www.pearsonhighered.com/irc
x PREFACE FOR INSTRUCTORS
For instructors only:
■ Solutions to most exercises and programming projects ■ PowerPoint slides ■ Lab Manual with associated code.
Instructors should click on the registration link and follow instructions to re- ceive a password. If you encounter any problems, please contact your local Pearson Sales Representative. For the name and number of your sales represen- tative, go to pearsonhighered.com/replocator.
For students: ■ Source code for programs in the book and for extra examples ■ Student lab manual ■ VideoNotes: video solutions to programming examples and exercises.
Visit www.pearsonhighered.com/savitch to access the student resources.
Online Practice and Assessment with MyProgrammingLab
MyProgrammingLab helps students fully grasp the logic, semantics, and syn- tax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of be- ginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages.
A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice problems organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong—and why. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review.
MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the makers of the CodeLab interactive programming exer- cise system. For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com.
VideoNotes
VideoNotes are Pearson’s new visual tool designed for teaching students key programming concepts and techniques. These short step-by-step videos demonstrate how to solve problems from design through coding. VideoNotes allow for self-placed instruction with easy navigation including the ability to select, play, rewind, fast-forward, and stop within each VideoNote exercise.
VideoNote
www.pearsonhighered.com/savitch
www.myprogramminglab.com
PREFACE FOR INSTRUCTORS xi
Margin icons in your textbook let you know when a VideoNote video is available for a particular concept or homework problem.
Integrated Development Environment Resource Kits
Professors who adopt this text can order it for students with a kit containing seven popular Java IDEs (the most recent JDK from Oracle, Eclipse, NetBeans, jGRASP, DrJava, BlueJ, and TextPad). The kit also includes access to a website containing written and video tutorials for getting started in each IDE. For ordering information, please contact your campus Pearson Education repre- sentative or visit www.pearsonhighered.com.
Contact Us
Your comments, suggestions, questions, and corrections are always welcome. Please e-mail them to savitch.programming.java@gmail.com.
www.pearsonhighered.com
Preface for Students
This book is designed to teach you the Java programming language and, even more importantly, to teach you basic programming techniques. It requires no previous programming experience and no mathematics other than some simple high school algebra. However, to get the full benefit of the book, you should have Java available on your computer, so that you can practice with the examples and techniques given. The latest version of Java is preferable, but a version as early as 5 will do.
If You Have Programmed Before
You need no previous programming experience to use this book. It was designed for beginners. If you happen to have had experience with some other programming language, do not assume that Java is the same as the programming language(s) you are accustomed to using. All languages are different, and the differences, even if small, are large enough to give you problems. Browse the first four chapters, reading at least the Recap portions. By the time you reach Chapter 5, it would be best to read the entire chapter.
If you have programmed before in either C or C++, the transition to Java can be both comfortable and troublesome. At first glance, Java may seem almost the same as C or C++. However, Java is very different from these lan- guages, and you need to be aware of the differences. Appendix 6 compares Java and C++ to help you see what the differences are.
Obtaining a Copy of Java
Appendix 1 provides links to sites for downloading Java compilers and pro- gramming environments. For beginners, we recommend Oracle’s Java JDK for your Java compiler and related software and TextPad as a simple editor envi- ronment for writing Java code. When downloading the Java JDK, be sure to obtain the latest version available.
Support Materials for Students ■ Source code for programs in the book and for extra examples ■ Student lab manual ■ VideoNotes: video solutions to programming examples and exercises.
Visit www.pearsonhighered.com/savitch to access the student resources.
xii
www.pearsonhighered.com/savitch
PREFACE FOR STUDENTS xiii
Learning Aids
Each chapter contains several features to help you learn the material:
■ The opening overview includes a brief table of contents, chapter objectives and prerequisites, and a paragraph or two about what you will study.
■ Recaps concisely summarize major aspects of Java syntax and other impor- tant concepts.
■ FAQs, or “frequently asked questions,” answer questions that other students have asked.
■ Remembers highlight important ideas you should keep in mind. ■ Programming Tips suggest ways to improve your programming skills. ■ Gotchas identify potential mistakes you could make—and should avoid—
while programming. ■ Asides provide short commentaries on relevant issues. ■ Self-Test Questions test your knowledge throughout, with answers given
at the end of each chapter. One of the best ways to practice what you are learning is to do the self-test questions before you look at the answers.
■ A summary of important concepts appears at the end of each chapter.
Online Practice with MyProgrammingLab
A self-study and practice tool, a MyProgrammingLab course consists of hundreds of small practice problems organized around the structure of this textbook. The system automatically detects errors in the logic and syntax of your code submissions and offers targeted hints that enable you to figure out what went wrong—and why. Visit www.myprogramminglab.com for more information.
VideoNotes
These short step-by-step videos demonstrate how to solve problems from design through coding. VideoNotes allow for self-placed instruction with easy navigation including the ability to select, play, rewind, fast-forward, and stop within each VideoNote exercise. Margin icons in your textbook let you know when a VideoNote video is available for a particular concept or homework problem.
This Text Is Also a Reference Book
In addition to using this book as a textbook, you can and should use it as a reference. When you need to check a point that you have forgotten or that you hear mentioned by somebody but have not yet learned yourself, just look in the index. Many index entries give a page number for a “recap.” Turn to that page. It will contain a short, highlighted entry giving all the essential points
VideoNote
www.myprogramminglab.com
xiv PREFACE FOR STUDENTS
on that topic. You can do this to check details of the Java language as well as details on programming techniques.
Recap sections in every chapter give you a quick summary of the main points in that chapter. Also, a summary of important concepts appears at the end of each chapter. You can use these features to review the chapter or to check details of the Java language.
Acknowledgments
We thank the many people who have made this sixth edition possible, in- cluding everyone who has contributed to the first five editions. We begin by recognizing and thanking the people involved in the development of this new edition. The comments and suggestions of the following reviewers were in- valuable and are greatly appreciated. In alphabetical order, they are:
Asa Ben-Hur—Colorado State University Joan Boone—University of North Carolina at Chapel Hill Dennis Brylow—Temple University Billie Goldstein—Temple University Helen H. Hu—Westminster College Tammy VanDeGrift—University of Portland
Many other reviewers took the time to read drafts of earlier editions of the book. Their advice continues to benefit this new edition. Thank you once again to:
Gerald Baumgartner—Louisiana State University Jim Buffenbarger—Idaho State University Robert P. Burton—Brigham Young University Mary Elaine Califf—Illinois State University Steve Cater—Kettering University Martin Chelten—Moorpark Community College Ashraful A. Chowdhury—Georgia Perimeter College Ping-Chu Chu—Fayetteville State University Michael Clancy—University of California, Berkeley Tom Cortina—State University of New York at Stony Brook Prasun Dewan—University of North Carolina Laird Dornan—Sun Microsystems, Inc. H. E. Dunsmore—Purdue University, Lafayette Adel Elmaghraby—University of Louisville Ed Gellenbeck—Central Washington University Adrian German—Indiana University Gobi Gopinath—Suffolk County Community College Le Gruenwald—University of Oklahoma Gopal Gupta—University of Texas, Dallas Ricci Heishman—North Virginia Community College Robert Herrmann—Sun Microsystems, Inc., Java Soft Chris Hoffmann—University of Massachusetts, Amherst
xv
xvi ACKNOWLEDGMENTS
Robert Holloway—University of Wisconsin, Madison Charles Hoot—Oklahoma City University Lily Hou—Carnegie Mellon University Richard A. Johnson—Missouri State University Rob Kelly—State University of New York at Stony Brook Michele Kleckner—Elon College Stan Kwasny—Washington University Anthony Larrain—Depaul University Mike Litman—Western Illinois University Y. Annie Liu—State University of New York at Stony Brook Michael Long—California State University Blayne Mayfield—Oklahoma State University Drew McDermott—Yale University Gerald H. Meyer—LaGuardia Community College John Motil—California State University, Northridge Michael Olan—Stockton State Richard Ord—University of California, San Diego James Roberts—Carnegie Mellon University Alan Saleski—Loyola University Chicago Dolly Samson—Hawaii Pacific University Nan C. Schaller—Rochester Institute of Technology Arijit Sengupta—Raj Sion College of Business, Wright State University Ryan Shoemaker—Sun Microsystems, Inc. Liuba Shrira—Brandeis University Ken Slonneger—University of Iowa Donald E. Smith—Rutgers University Peter Spoerri—Fairfield University Howard Straubing—Boston College Navabi Tadayon—Arizona State University Boyd Trolinger—Butte College Tom Van Drunen—Wheaton College Subramanian Vijayarangam—University of Massachusetts, Lowell Stephen F.Weiss—University of North Carolina, Chapel Hill Richard Whitehouse—Arizona State University Michael Young—University of Oregon
Last but not least, we thank the many students in classes at the University of California, San Diego (UCSD), who were kind enough to help correct pre- liminary versions of this text, as well as the instructors who class-tested these drafts. In particular, we extend a special thanks to Carole McNamee of Cali- fornia State University, Sacramento, and to Paul Kube of UCSD. These student comments and the detailed feedback and class testing of earlier editions of the book were a tremendous help in shaping the final book.
W. S. K. M.
Dependency Chart
This chart shows the prerequisites for the chapters in the book. If there is a line between two boxes, the material in the higher box should be covered before the material in the lower box. Minor varia- tions to this chart are discussed in the “Prerequisites” section at the start of each chapter. These variations usually provide more, rather than less, flexibility that what is shown on the chart.
* Note that some sections of these chapters can be covered sooner. Those sections are given in this chart. ** These chapters contain sections that can be covered sooner. See the chapter’s “Prerequisites” section for full details.
Chapter 1 Introduction
Chapter 2 Primitive Types, Strings
Chapter 3 Flow of Control: Branching
Chapter 4 Flow of Control: Loops
Section 7.1 Array Basics
Chapter 7* Arrays
Chapter 11** Recursion
Chapter 8** Inheritance
Chapter 13** Basic Swing
Chapter 14 Applets
Chapter 15 More Swing
Chapter 9* Exceptions
Section 9.1 Exception Basics
Section 10.1 Overview of Files
Section 10.2 Text Files
Section 10.3 Any Files
Section 10.4 Binary Files
Section 10.5 File I/O for Objects
Section 10.6 Files and Graphics
Chapter 12** Data Structures, Generics
Chapter 5 and 6 Classes and Methods
xviii
Recaps Summarize Java syntax and other important concepts.
Remembers Highlight important ideas that students should keep in mind.
Features of This Text RECAP Bytes and Memory Locations
A computer’s main memory is divided into numbered units called bytes. The number of a byte is called its address. Each byte can hold eight binary digits, or bits, each of which is either 0 or 1. To store a piece of data that is too large to fit into a single byte, the computer uses several adjacent bytes. These adjacent bytes are thought of as a single, larger memory location whose address is the address of the first of the adjacent bytes.
REMEMBER Syntactic Variables
When you see something in this book like Type, Variable_1, or Variable_2 used to describe Java syntax, these words do not literally appear in your Java code. They are syntactic variables, which are a kind of blank that you fill in with something from the category that they describe. For example, Type can be replaced by int, double, char, or any other type name. Variable_1 and Variable_2 can each be replaced by any variable name.
■ PROGRAMMING TIP Initialize Variables A variable that has been declared, but that has not yet been given a value by an assignment statement (or in some other way), is said to be uninitialized. If the variable is a variable of a class type, it literally has no value. If the variable has a primitive type, it likely has some default value. However, your program will be clearer if you explicitly give the variable a value, even if you are simply reassigning the default value. (The exact details on default values have been known to change and should not be counted on.)
One easy way to ensure that you do not have an uninitialized variable is to initialize it within the declaration. Simply combine the declaration and an assignment statement, as in the following examples:
int count = 0;
double taxRate = 0.075;
char grade = 'A';
int balance = 1000, newBalance;
Note that you can initialize some variables and not initialize others in a declaration. Sometimes the compiler may complain that you have failed to initialize a
variable. In most cases, that will indeed be true. Occasionally, though, the compiler is mistaken in giving this advice. However, the compiler will not compile your program until you convince it that the variable in question is initialized. To make the compiler happy, initialize the variable when you declare it, even if the variable will be given another value before it is used for anything. In such cases, you cannot argue with the compiler. ■
GOTCHA Hidden Errors
Just because your program compiles and runs without any errors and even produces reasonable-looking output does not mean that your program is correct. You should always run your program with some test data that gives predictable output. To do this, choose some data for which you can compute the correct results, either by using pencil and paper, by looking up the answer, or by some other means. Even this testing does not guarantee that your program is correct, but the more testing you do, the more confidence you can have in your program. ■
FAQ11 FAQ stands for “frequently asked question.” Why just 0s and 1s?
Computers use 0s and 1s because it is easy to make an electrical device that has only two stable states. However, when you are programming, you normally need not be concerned about the encoding of data as 0s and 1s. You can program as if the computer directly stored numbers, letters, or strings of characters in memory. There is nothing special about calling the states zero and one. We could just as well use any two names, such as A and B or true and false. The important thing is that the underlying physical device has two stable states, such as on and off or high voltage and low voltage. Calling these two states zero and one is simply a convention, but it’s one that is almost universally followed.
Programming Tips Give students helpful advice about programming in Java.
Gotchas Identify potential mistakes in programming that students might make and should avoid.
FAQs Provide students answers to frequently asked questions within the context of the chapter.
FEATURES OF THIS TEXT xix
VideoNotes Step-by-step video solutions to programming examples and homework exercises.
CASE STUDY Unit Testing So far we’ve tested our programs by running them, typing in some input, and visually checking the results to see if the output is what we expected. This is fine for small programs but is generally insufficient for large programs. In a large program there are usually so many combinations of interacting inputs that it would take too much time to manually verify the correct result for all inputs. Additionally, it is possible that code changes result in unintended side effects. For example, a fix for one error might introduce a different error. One way to attack this problem is to write unit tests. Unit testing is a methodology in which the programmer tests the correctness of individual units of code. A unit is often a method but it could be a class or other group of code.
The collection of unit tests becomes the test suite. Each test is generally automated so that human input is not required. Automation is important because it is desirable to have tests that run often and quickly. This makes it possible to run the tests repeatedly, perhaps once a day or every time code is changed, to make sure that everything is still working. The process of running tests repeatedly is called regression testing.
Let’s start with a simple test case for the Species class in Listing 5.19. Our first test might be to verify that the name, initial population, and growth rate is correctly set in the setSpecies method. We can accomplish this by creating
Writing arithmetic expressions and statements
VideoNote
Case Studies Take students from problem statement to algorithm development to Java code.
Listings Show students complete programs with sample output.
LISTING 1.2 Drawing a Happy Face
import javax.swing.JApplet;
import java.awt.Graphics;
public class HappyFace extends JApplet {
public void paint(Graphics canvas) {
canvas.drawOval(100, 50, 200, 200); canvas.fillOval(155, 100, 10, 20); canvas.fillOval(230, 100, 10, 20); canvas.drawArc(150, 160, 100, 50, 180, 180);
} } Applet Output
xx FEATURES OF THIS TEXT
Programming Examples Provide more examples of Java programs that solve specific problems.
PROGRAMMING EXAMPLE Nested Loops
The body of a loop can contain any sort of statements. In particular, you can have a loop statement within the body of a larger loop statement. For example, the program in Listing 4.4 uses a while loop to compute the average of a list of nonnegative scores. The program asks the user to enter all the scores followed by a negative sentinel value to mark the end of the data. This while loop is placed inside a do-while loop so that the user can repeat the entire process for another exam, and another, until the user wishes to end the program.
SELF-TEST QUESTIONS
28. Given the class Species as defined in Listing 5.19, why does the following program cause an error message?
public class SpeciesEqualsDemo {
public static void main(String[] args) { Species s1, s2; s1. setSpecies("Klingon ox", 10, 15); s2.setSpecies("Klingon ox", 10, 15);
if (s1 == s2) System.out.println("Match with ==.");
else System.out.println("Do Notmatchwith ==.") } }
29. After correcting the program in the previous question, what output does the program produce?
30. What is the biggest difference between a parameter of a primitive type and a parameter of a class type?
31. Given the class Species, as defined in Listing 5.19, and the class
Self-Test Questions Provide students with the opportunity to practice skills learned in the chapter. Answers at the end of each chapter give immediate feedback.