An introduction to problem solving programming tFb5zoX6JqpEG2czMEDX9paJ4DfUWIwg pdf

987 9 0
An introduction to problem solving   programming tFb5zoX6JqpEG2czMEDX9paJ4DfUWIwg pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

LOCATION OF VIDEONOTES IN THE TEXT Chapter 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 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 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 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 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 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) get with the programming Through the power of practice and immediate personalized feedback, MyProgrammingLab improves your performance Learn more at www.myprogramminglab.com This page intentionally left blank ™ An Introduction to Problem Solving & Programming This page intentionally left blank ™ 6th edition An Introduction to Problem Solving & Programming Walter Savitch University of California, San Diego Contributor Kenrick Mock University of Alaska Anchorage 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 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 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 countries Screen shots and icons reprinted with permission from the Microsoft Corporation This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation Copyright © 2012, 2009, 2005, 2004, 2001 Pearson Education, Inc., publishing as Prentice Hall, 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 reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 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 1—EB—15 14 13 12 11 ISBN 10: 0-132-16270-9 ISBN 13: 978-0-132-16270-8 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 quarter 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 interface, processing comma-separated value files, and others ■ Chapter now begins with a simpler class to more gradually introduce how classes are constructed ■ Chapter has been reorganized with a greater emphasis and more examples on polymorphism and interfaces ■ Chapter 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 ■ A description of Math.random has been added to Chapter ■ Twenty new programming projects have been added ■ New VideoNotes added throughout the text to enhance student understanding of programming concepts and techniques vii 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 programming techniques and is not simply a book about Java syntax It contains numerous case studies, programming examples, and programming tips Additionally, many sections explain important problem-solving and programming techniques, such as loop design techniques, debugging techniques, style techniques, abstract data types, and basic object-oriented programming techniques, 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 and Chapter covers how to define classes All 908 CHAPTER 12 / Dynamic Data Structures and Generics PROGRAMMING PROJECTS Visit www.myprogramminglab.com to complete many of these Programming Projects online and get instant feedback Revise the method selectionSort within the class ArraySorter, as shown in Listing 7.10 of Chapter 7, so that it sorts the strings in an instance of the class ArrayList into lexicographic order instead of sorting the integers in an array into ascending order For words, lexicographic order reduces to alphabetic order if all the words are in either lowercase or uppercase letters You can compare two strings to see which is lexicographically first by using the String method compareTo, as described in Figure 2.5 of Chapter 2 Repeat the previous programming project, but instead write a method bubbleSort that performs a bubble sort, as described in Programming Project of Chapter Repeat Programming Project 1, but instead write a method insertionSort that performs an insertion sort, as described in Programming Project of Chapter Write a program that creates Pet objects from data read from the keyboard Store these objects into an instance of ArrayList Then sort the Pet objects into alphabetic order by pet name, and finally display the data in the sorted Pet objects on the screen The class Pet is given in Chapter 6, Listing 6.1 Repeat the previous programming project, but sort the Pet objects by pet weight instead of by name After displaying the sorted data on the screen, write the number and percentage of pets that are under pounds, the number and percentage of pets that are to 10 pounds, and the number and percentage of pets that are over 10 pounds Repeat the previous programming project, but read the input data from a file and send the output to another file If you have covered binary files, use binary files; otherwise, use text files Read the file names from the user   6TFUIFDMBTT ClassObjectIODemo shown in Listing 10.10 of Chapter 10 to create a file of Species objects The class Species is given in Chapter 10, Listing 10.9 Then write a program that reads the Species objects from the file you created into an instance of ArrayList, sorts these instances alphabetically by Species name, and then writes the sorted data to both the screen and a file Read all file names from the user Define a variation on StringLinkedListSelfContained from Listing 12.7 that stores objects of type Species, rather than of type String Write a program that uses that linked-list class to create a linked list of Species objects, asks the user to enter a Species name, and then searches the linked list and displays one of the following messages, depending on whether the name is or is not on the list: 12.4 Generics 909 Species Species_Name is one of the Number_Of_Species_Names_On_List species on the list The data for Species_Name is as follows: Data_For_Species_Name or Species Species_Name is not a species on the list The user can enter more Species names until indicating an end to the program The class Species is given in Listing 5.19 of Chapter (If you prefer, you can use the serialized version of Species in Listing 10.9 of Chapter 10.) Repeat the previous programming project, but read the input data from a file and send the output to another file If you have covered binary files, use binary files; otherwise, use text files Read the file names from the user 10 Define a variation on StringLinkedListSelfContained from Listing 12.7 that stores objects of type Employee, rather than objects of type String Write a program that uses this linked-list class to create a linked list of Employee objects, asks the user to enter an employee’s Social Security number, and then searches the linked list and displays the data for the corresponding employee If no such employee exists, display a message that says so The user can enter more Social Security numbers until indicating an end to the program The class Employee is described in Programming Project of Chapter If you have not already done that project, you will need to define the class Employee as described there 11 Repeat the previous programming project, but read the input data from a file and send the output to another file If you have covered binary files, use binary files; otherwise, use text files Read the file names from the user 12 Write a parameterized class definition for a doubly linked list that has a QBSBNFUFSGPSUIFUZQFPGEBUBTUPSFEJOBOPEF.BLFUIFOPEFDMBTTBO inner class Choosing which methods to define is part of this project Also, write a program to thoroughly test your class definition 13 Create an application that will keep track of several groups of strings Each string will be a member of exactly one group We would like to be able to see whether two strings are in the same group as well as perform a union of two groups 6TF B MJOLFE TUSVDUVSF UP SFQSFTFOU B HSPVQ PG TUSJOHT &BDI OPEF JO the structure contains a string and a reference to another node in the group For example, the group {"a", "b", "d", "e"} is represented by the following structure: VideoNote Defining a circular linked list 910 CHAPTER 12 / Dynamic Data Structures and Generics a d b e One string in each group—"d" in our example—is in a node that has a null reference That is, it does not reference any other node in the structure This string is the representative string of the group Create the class GroupHolder to represent all of the groups and to perform operations on them It should have the private instance variable items to hold the nodes that belong to all of the groups The nodes within each HSPVQBSFMJOLFEUPHFUIFSBTEFTDSJCFEQSFWJPVTMZ.BLFitems an instance of ArrayList whose base type is GroupNode, where GroupNode is a private inner class of GroupHolder GroupNode has the following private instance variables: t data—a string t link—a reference to another node in the group, or null Define the following methods in the class GroupHolder: t addItem(s)— adds a string s to an empty group First search items for s; if you find s, nothing; if you not find s, create a new GroupNode object that has s as its string and null as its link and add it to items The new group will contain only the item s t getRepresentative(s)—returns the representative string for the group containing s To find the representative string, search items for s If you not find s, return null If you find s, follow links until you find a null reference The string in that node is the representative string for the group t getAllRepresentatives—returns an instance of ArrayList that contains the representative strings of all the groups in this instance of GroupHolder (A representative string is in an instance of GroupNode that contains a null reference.) t inSameGroup(s1, s2)—returns true if the representative string for s1 and the representative string for s2 are the same and not null, in which case the strings s1 and s2 are in the same group t union(s1, s2)—forms the union of the groups to which s1 and s2 belong (Hint: Find the representative strings for s1 and s2 If they are different and neither is null, make the link of the node containing s1’s representative string reference the node for s2’s representative string.) For example, suppose that we call addItem with each of the following strings as an argument: "a","b","c","d","e","f","g", and "h" Next, let’s form groups by using these union operations: union("a", "d"), union("b", "d"), union("e", "b"), union("h", "f") 12.4 Generics We will have four groups—{"a", "b", "d", "e"}, {"c"}, {"f", "h"}, and {"g"}—represented by the following structure: a b c d e f g h The representative strings for these four groups are "d","c","f", and "g", respectively Now the operation inSameSet("a", "e") would return true because both getRepresentative("a") and getRepresentative("e") return d Also, inSameSet("a", "f") would return false because getRepresentative("a") returns d and getRepresentative("f") returns f The operation union("a", "f") would make the node containing the representative string of the group to which "a" belongs—which is "d"— reference the node containing the representative string of the group to which "f" belongs, which is "f" This reference would be represented by an arrow from "d" to "f" in the previous diagram Your application should create an instance of GroupHolder and allow the user to add an arbitrary number of strings, each to its own group It should then perform an arbitrary number of union operations to form several groups Finally, it should demonstrate the other operations 14 For this project, we will create a data structure known as a queue A queue can be thought of as a line Items are added at the end of the line and are taken from the front of the line You will create a class LinkedQueue based on one of the linked-list classes given in this chapter It should have private attributes for t front—a reference to the first node in the linked list of queue items t count—the number of items in the queue and the following operations: t addToQueue(item)—adds item to the end of the queue (Add it at the end of the linked list.) t removeFromQueue()—removes the first item from the queue and returns it If the queue is empty, returns null t isEmpty—returns true if the queue contains no items; otherwise, returns false Create a program that demonstrates the methods of the LinkedQueue class 15 Repeat the previous programming project, but use a circular linked list to implement the queue Recall from Figure 12.10 that a circular linked list has one external reference, which is to the list’s last node 911 912 CHAPTER 12 / Dynamic Data Structures and Generics 16 Suppose that we would like to perform a bird survey to count the number of birds of each species in an area Create a class BirdSurvey that is like one of the linked-list classes given in this chapter (The linked list you use will affect what your new class can do, so give some thought to your choice.) PEJGZUIFJOOFSOPEFDMBTTUPBEESPPNGPSBDPVOU BirdSurvey should have the following operations: t add(bird)—adds the bird species bird to the end of the list, if it is not already there, and sets its count to 1; otherwise, adds to the count for bird t getCount(bird)—returns the count associated with the species bird If bird is not on the list, returns zero t getReport—displays the name and count for each bird species on the list Write a program that uses BirdSurvey to record the data from a recent CJSETVSWFZ6TFBMPPQUPSFBECJSEOBNFTVOUJMdone is entered Display a report when finished 17 Consider a text file of names, with one name per line, that has been compiled from several different sources A sample is shown below: Brooke Trout Dinah Soars Jed Dye Brooke Trout Jed Dye Paige Turner VideoNote Solution to Project 17 There are duplicate names in the file We would like to generate an invitation list but don’t want to send multiple invitations to the same person Write a program that eliminates the duplicate names by using a HashSet Read each name from the file, add it to the HashSet, and then output all names in the HashSet to generate the invitation list without duplicates 18 Write a program that uses a HashMap to compute a histogram of positive numbers entered by the user The HashMap’s key should be the number that is entered, and the value should be a counter of the number of times UIFLFZIBTCFFOFOUFSFETPGBS6TF¦BTBTFOUJOFMWBMVFUPTJHOBMUIF end of user input For example, if the user inputs: 12 5 21 -1 12.4 Generics Then the program should output the following (not necessarily in this order): The The The The number number number number occurs times occurs times 12 occurs times 21 occurs times Answers to Self-Test Questions aList.add("Hello"); aList.set(5, "Go"); No The index for set must be greater than or equal to and less than the size of the list Thus, you can replace any existing element, but you cannot place a new element at any higher index That is, you cannot add an element beyond the last-used index This situation is unlike that of an array If an array is partially filled to index 10, you can add an element at index 20, as long as the array is that large No The index for add must be greater than or equal to and less than or equal to the size of the list Thus, you can insert an element at any index that is currently holding an element, and you can insert an element immediately after the last element, but you cannot insert an element at any higher index Yes The method add can add an element right after the last element on the list, that is, at index size() However, the index position for set must be less than size() The seven elements of aList are at indices through A new element added at index is the eighth element and is at the end of the list "red", "blue", "orange", "green", "yellow" Yes The list can contain more than 20 elements The argument to the DPOTUSVDUPSNFSFMZHJWFTUIFJOJUJBMNFNPSZBMMPDBUJPOGPSUIFMJTU.PSF memory is automatically allocated when it is needed for (int index = 0; index < aList.size(); index++) System.out.println(aList.get(index)); 10 No, you cannot have an instance of ArrayList that has the base type int However, you can have one that has the base type Integer, and thanks to automatic boxing and unboxing, it can be used as if it were a list of ints 11 The method invocation list.size() returns the number of elements currently in list The capacity of list, however, is the number of elements for which memory has been allocated 913 914 CHAPTER 12 / Dynamic Data Structures and Generics 12 The new elements at indices 10 through 19 will have null for their values 13 HashSet colors = new HashSet(); 14 colors.add("red");colors.add("blue");System.out println(colors.contains("blue"));colors.remove("blue"); 15 HashMap studentids = new HashMap(); 16 studentIDs.put(5531, "George"); studentIDs.put(9102, "John"); System.out.println(studentIDs.get(9102)); 17 Replace ArrayList with LinkedList in the import statement and twice in the statement that invokes the constructor 18 You indicate the end of a linked list by setting the link instance variable of the last node to null 19 head should have the value null 20 public boolean isEmpty() { return length() == 0; } or public boolean isEmpty() { return head == null; } Since the first version invokes another method and the second one does not, the second method will execute faster 21 C B A 22 An inner class is a class defined within the definition of another class 23 They are not needed, because the methods in the linked-list class have access to the instance variables data and link of the nodes 24 Any variable that allows you to step through the collection one item at a time, such that each item is visited exactly once in one full iteration cycle Each item can have its data read and, if the data items allow it, can have the data changed For example, an int variable that holds an index value can serve as an iterator for an array To go to the next item in the array, your code needs only to increase the value of the int variable by 12.4 Generics 25 public String getDataAtCurrent() throws LinkedListException { if (current != null) return current.data; else throw new LinkedListException("Attempted data " + "access when current is not at any node."); } 26 public void setDataAtCurrent(String newData) throws LinkedListException { if (current != null) current.data = newData; else throw new LinkedListException("Attempted data " + "change when current is not at any node."); } 27 public void insertNodeAfterCurrent(String newData) throws LinkedListException { ListNode newNode = new ListNode(); newNode.data = newData; if (current != null) { newNode.link = current.link; current.link = newNode; } else if (head != null) { throw new LinkedListException("Inserting when " + "iterator is past all nodes or " + "is not initialized."); } else { throw new LinkedListException("Attempted insertion " + "into an empty list."); } } 28 public void deleteCurrentNode() throws LinkedListException { if ((current != null) && (previous != null)) { previous.link = current.link; current = current.link; 915 916 CHAPTER 12 / Dynamic Data Structures and Generics } else if ((current != null) && (previous == null)) { //At head node head = current.link; current = head; } else//current == null { throw new LinkedListException("Attempted deletion " + "from an empty list, or current is not initialized."); } } 29 The complete definition is given as the class ListNode2 in the source code available on the Web public class ListNode2 { private E data; private ListNode2 link; public ListNode2() { link = null; data = null; } public ListNode2(E newData, ListNode2linkValue) { data = newData; link = linkValue; } public void setData(E newData) { data = newData; } public E getData() { return data; } public void setLink(ListNode2newLink) { link = newLink; } public ListNode2 getLink() { return link; } } 30 ListNode2 node = new ListNode2(); APPENDIX Getting Java A number of Java compilers and integrated development environments (IDEs) are available free of charge for various operating systems The following list provides links to a selection of these resources ■ The Java SE Development Kit (JDK) Available from Oracle, the JDK for Linux, Solaris, and Windows includes the Java Runtime Environment (JRE) and command-line tools that you can use to write applications and applets http://www.oracle.com/technetwork/java/index.html ■ BlueJ BlueJ is an IDE developed at a university It was created specifically for beginning Java students and is available for MacOS, Windows, and other systems at www.bluej.org/download/download.html BlueJ requires that you already have Java installed Windows users should download and install the JDK from Oracle, as described previously MacOS users will already have Java installed by default ■ Eclipse Eclipse is an open-source IDE for Linux, MacOS, and Windows that is available at www.eclipse.org/downloads/ Eclipse requires that you already have Java installed Linux and Windows users should download and install the appropriate JDK from Sun, as described previously MacOS users will already have Java installed by default ■ NetBeans NetBeans is an open-source IDE for Linux, MacOS, Solaris, and Windows that is available at www.netbeans.info/downloads/index.php The website has a link to download the IDE by itself, in which case you must already have Java installed Alternately, there is a link to download the IDE bundled with the JDK MacOS users will already have Java installed by default Installation instructions for each of these resources are available at the given URLs 917 APPENDIX Running Applets As you know, applets are Java programs that are run from a Web page The document that defines any Web page is written in HTML, which is a language designed for this purpose Chapter 14, which is available on the book’s Web site, provides some details about writing an HTML document However, we can also use the Java tool appletviewer to run our applet This tool requires a simple HTML document that we can write without looking at the details given in Chapter 14 Note that if you are using an IDE, you likely can run an applet without any reference to HTML As we mentioned in Chapter 1, a typical IDE has a menu command such as Run Applet or something similar After you have written an applet, you should compile it Recall from Chapter that if your applet code is in the file MyApplet.java, for example, compiling this file produces another file—MyApplet.class—that contains the bytecode for the applet Next, to run the applet using appletviewer, you need to create another file for a simple HTML document Its contents have the following form: So for our MyApplet example, our HTML file could contain The number of lines we use for the HTML is irrelevant The name of the HTML file should be Applet_Name.html, in this case, MyApplet.html Now we are ready to run the applet using the command appletviewer MyApplet.html 918  Appendix RECAP Using appletviewer to Run an Applet To run an applet that is in the file Applet_Name.java, you take the following steps: ■ Create a file named Applet_Name.html that contains the following code: applet code = "Applet_Name.class" width = Applet_Width height = Applet_Height> ■ Give the following commands at your computer’s command line: javac Applet_Name.java appletviewer Applet_Name.html 919 APPENDIX Protected and Package Modifiers In this text, we always use the modifiers public and private before instance variables and method definitions Normally, these are the only modifiers you need, but there are two other possibilities that fall between the two extremes of public and private In this appendix, we discuss the modifier protected as well as the restriction that applies when you use no modifier at all If a method or instance variable is modified by protected rather than public or private, it can be accessed directly by name within t *UTPXODMBTTEFGJOJUJPO t "OZEFTDFOEBOUDMBTT t "OZNFUIPEEFGJOJUJPOGPSBOZDMBTTJOUIFTBNFQBDLBHF That is the extent of the access; the protected method or instance variable cannot be accessed by name within any other classes Thus, if a method is NBSLFE protected in class A, and class B is derived from class A, the method can be called inside any method definition in class B However, in a class that is OPUJOUIFTBNFQBDLBHFBTDMBTTA and is not derived from class A, the protected method behaves as if it were private The modifier protected imposes a peculiar sort of restriction, since it allows EJSFDUBDDFTTUPBOZQSPHSBNNFSXIPJTXJMMJOHUPHPUISPVHIUIFCPUIFSPGEFGJOJOHBTVJUBCMFEFSJWFEDMBTT5IVT JUJTMJLFTBZJOH i*MMNBLFJUEJGGJDVMUGPSZPV to use this item, but I will not forbid you to use it.” In practice, instance variables TIPVMEOFWFSCFNBSLFE protected; they should be private However, you can have protected accessor and mutator methods for such instance variables If you want an access level that is not public but not as restrictive as private access, an alternative is possible and often preferable You may have noticed UIBUJGZPVGPSHFUUPQMBDFPOFPGUIFNPEJGJFST public or private before an instance variable or method definition, your class definition will still compile In such cases, the instance variable or method can be accessed by name within UIFEFGJOJUJPOPGBOZDMBTTUIBUJTJOUIFTBNFQBDLBHF*UDBOOPU IPXFWFS CF BDDFTTFECZOBNFPVUTJEFPGUIFQBDLBHF5IJTUZQFPGBDDFTTJTDBMMFEpackage access, or default access.:PVVTFQBDLBHFBDDFTTXIFOZPVIBWFBQBDLBHFPG DPPQFSBUJOHDMBTTFTUIBUBDUBTBTJOHMFFODBQTVMBUFEVOJU/PUFUIBUQBDLBHF BDDFTTJTNPSFSFTUSJDUFEUIBOQSPUFDUFEBDDFTTBOEUIBUJUHJWFTNPSFDPOUSPMUP UIFQSPHSBNNFSEFGJOJOHUIFDMBTTFT*GZPVDPOUSPMUIFQBDLBHFEJSFDUPSZ ZPV DPOUSPMXIPJTBMMPXFEQBDLBHFBDDFTT 920 APPENDIX The DecimalFormat Class The class DecimalFormat is in the Java Class Library within the package java text Thus, you make it available to a Java program by including the following import statement at the beginning of a program: import java.text.DecimalFormat; You can use this class to convert decimal numbers to formatted strings that can be displayed on the screen or written to a text file Although the class defines a number of different methods, this appendix describes only one of them, namely, the method format Complete documentation for the class DecimalFormat is available on the Oracle Web site The general approach to using the method format requires you to create a String pattern that describes the desired format for decimal numbers For example, the pattern "00.000" means that there will be two digits before the decimal point and three digits after the decimal point If the value of the number is not consistent with the specified format pattern, the format will be violated so that no digits are lost on the left of the decimal point For example, the pattern "00.000" asks for only two digits before the decimal point, but the value 123.456 will be formatted as 123.456 Note, however, that the fractional portion is rounded when the pattern specifies fewer digits than are available in the actual number So, using the same pattern, the value 12.3456 will be formatted as 12.346 Once you have a pattern, you then create an object of the class DecimalFormat by writing a statement of the following form: SYNTAX: DecimalFormat Decimal_Format_Object_Name = DecimalFormat(Pattern); EXAMPLE: DecimalFormat formattingObject = new DecimalFormat("00.000"); You then can use the method format to convert a value of type double to a corresponding numeral String, as follows: 921 922 APPENDIX / The DecimalFormat Class SYNTAX: Decimal_Format_Object_Name.format(Double_Expression) The method returns a string that corresponds to Double_Expression EXAMPLE: System.out.println(formattingObject.format(12.3456)); If the object formattingObject is created with the pattern "00.000", as in our previous example, the output produced by the foregoing println statement is 12.346 Note that the method format returns a string that is an object of the class StringBuffer, not String StringBuffer is similar to String but has methods that can modify the value of its instances Other Pattern Symbols You can also create patterns such as "#0.##0", in which the character ‘0’ stands for a compulsory digit and the character ‘#’ stands for an optional digit If ‘#’ corresponds to a leading or trailing zero, the zero is omitted from the resulting string For example, the statements DecimalFormat formattingObject = new DecimalFormat("#0.0#"); System.out.println(formattingObject.format(3.5)); display 3.5, whereas DecimalFormat formattingObject = new DecimalFormat("00.00"); System.out.println(formattingObject.format(3.5)); display 03.50 The character '%' placed at the end of a pattern indicates that the number is to be expressed as a percentage The '%' causes the number to be multiplied by 100 and have a percent sign (%) appended to it For example, the statements DecimalFormat formattingObject = new DecimalFormat("##0.0%"); System.out.println(formattingObject.format(0.1234)); display 12.3% You can place a dollar sign and/or commas into a pattern to format currency or large values These two characters appear unchanged in the locations specified by the pattern Figure A4.1 includes some examples of such patterns Figure A4.1 Some Results of Formatting Decimal Numbers Value 3.5 3.5 1234.5678 123.45 12345.670 12345.678 Pattern #0.0# 00.00 ##.## 00000.000 ###,###.### $###,###.00 Result 3.5 03.50 1234.57 00123.450 12,345.67 $12,345.68 ... performance Learn more at www.myprogramminglab.com This page intentionally left blank ™ An Introduction to Problem Solving & Programming This page intentionally left blank ™ 6th edition An Introduction. .. 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. .. 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

Ngày đăng: 07/04/2021, 13:37

Mục lục

  • Cover

  • Title Page

  • Copyright Page

  • Preface for Instructors

  • Preface for Students

  • Acknowledgments

  • Dependency Chart

  • Features of This Text

  • TABLE OF CONTENTS

  • Chapter 1 Introduction to Computers and Java

    • 1.1 COMPUTER BASICS

      • Hardware and Memory

      • Programs

      • Programming Languages, Compilers, and Interpreters

      • Java Bytecode

      • Class Loader

      • 1.2 A SIP OF JAVA

        • History of the Java Language

        • Applications and Applets

        • A First Java Application Program

        • Writing, Compiling, and Running a Java Program

        • 1.3 PROGRAMMING BASICS

          • Object-Oriented Programming

          • Algorithms

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan