Introduction to Java Programming - Comprehensive Version

This book teaches programming in a problem-driven way that focuses on problem solving rather than syntax.


Y. Daniel Liang


1345 Pages

281678 Reads

67 Downloads

English

PDF Format

13.9 MB

Java Programming

Download PDF format


  • Y. Daniel Liang   
  • 1345 Pages   
  • 13 Feb 2015
  • Page - 1

    read more..

  • Page - 2

    INTRODUCTION TO JAVA PROGRAMMING COMPREHENSIVE VERSION Tenth Edition Y. Daniel Liang Armstrong Atlantic State University ® Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo read more..

  • Page - 3

    To Samantha, Michael, and Michelle Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the appropriate page within text. Microsoft® and W indows® 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 read more..

  • Page - 4

    iii PREFACE Dear Reader, Many of you have provided feedback on earlier editions of this book, and your comments and suggestions have greatly improved the book. This edition has been substantially enhanced in presentation, organization, examples, exercises, and supplements. The new edition: ■ Replaces Swing with JavaFX. JavaFX is a new framework for developing Java GUI pro- grams. read more..

  • Page - 5

    iv Preface with various levels of difficulty are provided for students to practice. For our programming courses, we assign programming exercises after each lecture. Our goal is to produce a text that teaches problem solving and programming in a broad context using a wide variety of interesting examples. If you have any comments on and sug- gestions for improving the book, read more..

  • Page - 6

    Preface v Pedagogical Features The book uses the following elements to help students get the most from the material: ■ The Objectives at the beginning of each chapter list what students should learn from the chapter. This will help them determine whether they have met the objectives after completing the chapter. ■ The Introduction opens the discussion with representative read more..

  • Page - 7

    vi Pr ef ace Chapter 39 Web Services Chapter 42 Testing Using JUnit Chapter 38 JavaServer Pages Chapter 25 Binary Search Trees Chapter 26 AVL Trees Chapter 29 Weighted Graphs and Applications Chapter 28 Graphs and Applications Chapter 21 Sets and Maps Chapter 22 Developping Efficient Algorithms Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Elementary Programming Chapter 5 read more..

  • Page - 8

    Preface vii Organization of the Book The chapters can be grouped into five parts that, taken together, form a comprehensive introduc- tion to Java programming, data structures and algorithms, and database and Web programming. Because knowledge is cumulative, the early chapters provide the conceptual basis for under- standing programming and guide students through simple examples and read more..

  • Page - 9

    viii Preface projects. Chapter 33 introduces modern Web application development using JavaServer Faces. Chapter 35 delves into advanced Java database programming. Chapter 36 covers the use of internationalization support to develop projects for international audiences. Chapters 37 and 38 introduce how to use Java servlets and JavaServer Pages to generate dynamic content from Web servers. read more..

  • Page - 10

    Preface ix ■ More than 100 additional programming exercises organized by chapters. These exercises are available only to the instructors. Solutions to these exercises are provided. ■ Web-based quiz generator. (Instructors can choose chapters to generate quizzes from a large database of more than two thousand questions.) ■ Sample exams. Most exams have four parts: ■ read more..

  • Page - 11

    x Preface Algorithm Animations We have provided numerous animations for algorithms. These are valuable pedagogical tools to demonstrate how algorithms work. Algorithm animations can be accessed from the Com- panion Website. Acknowledgments I would like to thank Armstrong Atlantic State University for enabling me to teach what I write and for supporting me in writing what I teach. read more..

  • Page - 12

    xi 1 Introduction to Computers, Programs, and Java 1 2 Elementary Programming 33 3 Selections 75 4 Mathematical Functions, Characters, and Strings 119 5 Loops 157 6 Methods 203 7 Single-Dimensional Arrays 245 8 Multidimensional Arrays 287 9 Objects and Classes 321 10 Object-Oriented Thinking 365 11 Inheritance and Polymorphism 409 12 Exception Handling and Text I/O 449 13 Abstract Classes read more..

  • Page - 13

    xii Chapter 1 Introduction to Computers, Programs, and Java 1 1.1 Introduction 2 1.2 What Is a Computer? 2 1.3 Programming Languages 7 1.4 Operating Systems 9 1.5 Java, the World Wide Web, and Beyond 10 1.6 The Java Language Specification, API, JDK, and IDE 11 1.7 A Simple Java Program 12 1.8 Creating, Compiling, and Executing a Java Program 15 1.9 Programming Style and read more..

  • Page - 14

    xiii 3.15 Operator Precedence and Associativity 104 3.16 Debugging 106 Chapter 4 Mathematical Functions, Characters, and Strings 119 4.1 Introduction 120 4.2 Common Mathematical Functions 120 4.3 Character Data Type and Operations 125 4.4 The String Type 130 4.5 Case Studies 139 4.6 Formatting Console Output 145 Chapter 5 Loops 157 5.1 Introduction 158 5.2 The while Loop 158 5.3 The read more..

  • Page - 15

    xiv Contents 8.3 Processing Two-Dimensional Arrays 291 8.4 Passing Two-Dimensional Arrays to Methods 293 8.5 Case Study: Grading a Multiple-Choice Test 294 8.6 Case Study: Finding the Closest Pair 296 8.7 Case Study: Sudoku 298 8.8 Multidimensional Arrays 301 Chapter 9 Objects and Classes 321 9.1 Introduction 322 9.2 Defining Classes for Objects 322 9.3 Example: Defining Classes and Creating Objects read more..

  • Page - 16

    Contents xv 12.3 Exception Types 455 12.4 More on Exception Handling 458 12.5 The finally Clause 466 12.6 When to Use Exceptions 467 12.7 Rethrowing Exceptions 468 12.8 Chained Exceptions 469 12.9 Defining Custom Exception Classes 470 12.10 The File Class 473 12.11 File Input and Output 476 12.12 Reading Data from the Web 482 12.13 Case Study: Web Crawler 484 Chapter 13 Abstract Classes and read more..

  • Page - 17

    xvi Contents 16.3 Button 632 16.4 CheckBox 634 16.5 RadioButton 637 16.6 TextField 639 16.7 TextArea 641 16.8 ComboBox 644 16.9 ListView 647 16.10 ScrollBar 651 16.11 Slider 654 16.12 Case Study: Developing a Tic-Tac-Toe Game 657 16.13 Video and Audio 662 16.14 Case Study: National Flags and Anthems 665 Chapter 17 Binary I/O 677 17.1 Introduction 678 17.2 How Is Text I/O Handled in Java? 678 17.3 Text read more..

  • Page - 18

    Contents xvii 20.9 Queues and Priority Queues 783 20.10 Case Study: Evaluating Expressions 786 Chapter 21 Sets and Maps 797 21.1 Introduction 798 21.2 Sets 798 21.3 Comparing the Performance of Sets and Lists 806 21.4 Case Study: Counting Keywords 809 21.5 Maps 810 21.6 Case Study: Occurrences of Words 815 21.7 Singleton and Unmodifiable Collections and Maps 816 Chapter 22 Developing Efficient read more..

  • Page - 19

    xviii Contents 26.4 Overriding the insert Method 970 26.5 Implementing Rotations 971 26.6 Implementing the delete Method 972 26.7 The AVLTree Class 972 26.8 Testing the AVLTree Class 978 26.9 AVL Tree Time Complexity Analysis 981 Chapter 27 Hashing 985 27.1 Introduction 986 27.2 What Is Hashing? 986 27.3 Hash Functions and Hash Codes 987 27.4 Handling Collisions Using Open Addressing 989 27.5 read more..

  • Page - 20

    Contents xix Chapter 31 Networking 1139 31.1 Introduction 1140 31.2 Client/Server Computing 1140 31.3 The InetAddress Class 1147 31.4 Serving Multiple Clients 1148 31.5 Sending and Receiving Objects 1151 31.6 Case Study: Distributed Tic-Tac-Toe Games 1156 Chapter 32 Java Database Programming 1173 32.1 Introduction 1174 32.2 Relational Database Systems 1174 32.3 SQL 1178 32.4 JDBC 1189 32.5 PreparedStatement read more..

  • Page - 21

    xx Contents APPENDIXES Appendix A Java Keywords 1263 Appendix B The ASCII Character Set 1266 Appendix C Operator Precedence Chart 1268 Appendix D Java Modifiers 1270 Appendix E Special Floating-Point Values 1272 Appendix F Number Systems 1273 Appendix G Bitwise Operations 1277 Appendix H Regular Expressions 1278 Appendix I Enumerated Types 1283 INDEX 1289 read more..

  • Page - 22

    xxi Chapter 1 Introduction to Computers, Programs, and Java 1 Your first Java program 12 Compile and run a Java program 17 NetBeans brief tutorial 23 Eclipse brief tutorial 25 Chapter 2 Elementary Programming 33 Obtain input 37 Use operators / and % 52 Software development process 59 Compute loan payments 60 Compute BMI 72 Chapter 3 Selections 75 Program addition quiz 77 Program subtraction read more..

  • Page - 23

    xxii VideoNotes Use shapes 560 Display a tictactoe board 578 Display a bar chart 580 Chapter 15 Event-Driven Programming and Animations 585 Handler and its registration 592 Anonymous handler 595 Move message using the mouse 602 Animate a rising flag 608 Flashing text 614 Simple calculator 621 Check mouse point location 622 Display a running fan 625 Chapter 16 JavaFX UI Controls and read more..

  • Page - 24

    INTRODUCTION TO COMPUTERS, PROGRAMS, AND JAVA Objectives ■ To understand computer basics, programs, and operating systems (§§1.2–1.4). ■ To describe the relationship between Java and the World Wide Web (§1.5). ■ To understand the meaning of Java language specification, API, JDK, and IDE (§1.6). ■ To write a simple Java program (§1.7). ■ To display output on the console read more..

  • Page - 25

    2 Chapter 1 Introduction to Computers, Programs, and Java 1.1 Introduction The central theme of this book is to learn how to solve problems by writing a program. This book is about programming. So, what is programming? The term programming means to create (or develop) software, which is also called a program. In basic terms, software contains the instructions that tell read more..

  • Page - 26

    1.2 What Is a Computer? 3 the bus is built into the computer’s motherboard, which is a circuit case that connects all of the parts of a computer together. 1.2.1 Central Processing Unit The central processing unit (CPU) is the computer’s brain. It retrieves instructions from memory and executes them. The CPU usually has two components: a control unit and an read more..

  • Page - 27

    4 Chapter 1 Introduction to Computers, Programs, and Java into a predetermined string of bits. In the popular ASCII encoding scheme, for example, the character C is represented as 01000011 in one byte. A computer’s storage capacity is measured in bytes and multiples of the byte, as follows: ■ A kilobyte (KB) is about 1,000 bytes. ■ A megabyte (MB) is read more..

  • Page - 28

    1.2 What Is a Computer? 5 actually uses them, to memory, which operates at much faster speeds than permanent storage devices can. There are three main types of storage devices: ■ Magnetic disk drives ■ Optical disc drives (CD and DVD) ■ USB flash drives Drives are devices for operating a medium, such as disks and CDs. A storage medium physically stores data read more..

  • Page - 29

    6 Chapter 1 Introduction to Computers, Programs, and Java The Insert, Delete, Page Up, and Page Down keys are used in word processing and other programs for inserting text and objects, deleting text and objects, and moving up or down through a document one screen at a time. The Mouse A mouse is a pointing device. It is used to move a graphical pointer (usually read more..

  • Page - 30

    1.3 Programming Languages 7 1.8 What unit is used to measure disk size? 1.9 What is the primary difference between memory and a storage device? 1.3 Programming Languages Computer programs, known as software, are instructions that tell a computer what to do. Computers do not understand human languages, so programs must be written in a language a computer can use. There are read more..

  • Page - 31

    8 Chapter 1 Introduction to Computers, Programs, and Java TABLE 1.1 Popular High-Level Programming Languages Language Description Ada Named for Ada Lovelace, who worked on mechanical general-purpose computers. The Ada language was developed for the Department of Defense and is used mainly in defense projects. BASIC Beginner’s All-purpose Symbolic Instruction Code. It was designed to be read more..

  • Page - 32

    1.4 Operating Systems 9 1.15 What is an interpreter? 1.16 What is a compiler? 1.17 What is the difference between an interpreted language and a compiled language? FIGURE 1.4 (a) An interpreter translates and executes a program one statement at a time. (b) A compiler translates the entire source program into a machine-language file for execution. Machine-Code File ... 0101100011011100 read more..

  • Page - 33

    10 Chapter 1 Introduction to Computers, Programs, and Java 1.4.1 Controlling and Monitoring System Activities Operating systems perform basic tasks, such as recognizing input from the keyboard, sending output to the monitor, keeping track of files and folders on storage devices, and controlling peripheral devices, such as disk drives and printers. An operating system must also ensure read more..

  • Page - 34

    1.6 The Java Language Specification, API, JDK, and IDE 11 interpreted, robust, secure, architecture neutral, portable, high performance, multi- threaded, and dynamic. For the anatomy of Java characteristics, see www.cs.armstrong.edu/ liang/JavaCharacteristics.pdf . Java is a full-featured, general-purpose programming language that can be used to develop robust mission-critical applications. Today, read more..

  • Page - 35

    12 Chapter 1 Introduction to Computers, Programs, and Java Java is a full-fledged and powerful language that can be used in many ways. It comes in three editions: ■ Java Standard Edition (Java SE) to develop client-side applications. The applica- tions can run standalone or as applets running from a Web browser. ■ Java Enterprise Edition (Java EE) to develop read more..

  • Page - 36

    1.7 A Simple Java Program 13 Line 1 defines a class. Every Java program must have at least one class. Each class has a name. By convention, class names start with an uppercase letter. In this example, the class name is Welcome. Line 2 defines the main method. The program is executed from the main method. A class may contain several methods. The main method read more..

  • Page - 37

    14 Chapter 1 Introduction to Computers, Programs, and Java conforms to the syntax rules. If your program violates a rule—for example, if the semicolon is missing, a brace is missing, a quotation mark is missing, or a word is misspelled—the Java compiler will report syntax errors. Try to compile the program with these errors and see what the compiler reports. Note You read more..

  • Page - 38

    1.8 Creating, Compiling, and Executing a Java Program 15 The multiplication operator in Java is *. As you can see, it is a straightforward process to translate an arithmetic expression to a Java expression. We will discuss Java expressions further in Chapter 2. 1.28 What is a keyword? List some Java keywords. 1.29 Is Java case sensitive? What is the case for Java keywords? read more..

  • Page - 39

    16 Chapter 1 Introduction to Computers, Programs, and Java in Figure 1.8a. The Java language is a high-level language, but Java bytecode is a low-level language. The bytecode is similar to machine instructions but is architecture neutral and can run on any platform that has a Java Virtual Machine (JVM), as shown in Figure 1.8b. Rather than a physical machine, the virtual machine is a program read more..

  • Page - 40

    1.8 Creating, Compiling, and Executing a Java Program 17 Figure 1.9 shows the javac command for compiling Welcome.java. The compiler gener- ates the Welcome.class file, and this file is executed using the java command. Note For simplicity and consistency, all source-code and class files used in this book are placed under c:\book unless specified otherwise. javac command java read more..

  • Page - 41

    18 Chapter 1 Introduction to Computers, Programs, and Java to ensure that the bytecode does not violate Java’s security restrictions. Java enforces strict security to make sure that Java class files are not tampered with and do not harm your computer. Pedagogical Note Your instructor may require you to use packages for organizing programs. For example, you may place all read more..

  • Page - 42

    1.9 Programming Style and Documentation 19 To see an example of a javadoc HTML file, check out www.cs.armstrong.edu/liang/javadoc/ Exercise1.html . Its corresponding Java code is shown in www.cs.armstrong.edu/liang/javadoc/ Exercise1.java . 1.9.2 Proper Indentation and Spacing A consistent indentation style makes programs clear and easy to read, debug, and maintain. Indentation is used to read more..

  • Page - 43

    20 Chapter 1 Introduction to Computers, Programs, and Java 1.10 Programming Errors Programming errors can be categorized into three types: syntax errors, runtime errors, and logic errors. 1.10.1 Syntax Errors Errors that are detected by the compiler are called syntax errors or compile errors. Syntax errors result from errors in code construction, such as mistyping a keyword, read more..

  • Page - 44

    1.10 Programming Errors 21 waiting for the user to enter a value, but the user enters a value that the program cannot handle. For instance, if the program expects to read in a number, but instead the user enters a string, this causes data-type errors to occur in the program. Another example of runtime errors is division by zero. This happens when the divisor is zero read more..

  • Page - 45

    22 Chapter 1 Introduction to Computers, Programs, and Java Common Error 1: Missing Braces The braces are used to denote a block in the program. Each opening brace must be matched by a closing brace. A common error is missing the closing brace. To avoid this error, type a closing brace whenever an opening brace is typed, as shown in the following example. public class read more..

  • Page - 46

    1.11 Developing Java Programs Using NetBeans 23 1.47 Identify and fix the errors in the following code: 1 public class Welcome { 2 public void Main(String[] args) { 3 System.out.println('Welcome to Java!); 4 } 5 } 1.11 Developing Java Programs Using NetBeans You can edit, compile, run, and debug Java Programs using NetBeans. NetBeans and Eclipse read more..

  • Page - 47

    24 Chapter 1 Introduction to Computers, Programs, and Java FIGURE 1.14 A New Java project named demo is created. FIGURE 1.15 The New Java Class dialog box is used to create a new Java class. FIGURE 1.13 The New Java Application dialog is for specifying a project name and location. 2. Type Welcome in the Class Name field and select the Source Packages in the read more..

  • Page - 48

    1.12 Developing Java Programs Using Eclipse 25 FIGURE 1.16 You can edit a program and run it in NetBeans. Edit pane Output pane 1.11.3 Compiling and Running a Class To run Welcome.java, right-click Welcome.java to display a context menu and choose Run File, or simply press Shift + F6. The output is displayed in the Output pane, as shown in Figure 1.16. The Run File read more..

  • Page - 49

    26 Chapter 1 Introduction to Computers, Programs, and Java FIGURE 1.17 The New Java Project dialog is for specifying a project name and properties. FIGURE 1.18 A New Java project named demo is created. 3. Check the option public static void main(String[] args). 4. Click Finish to generate the template for the source code Welcome.java, as shown in Figure 1.19. read more..

  • Page - 50

    1.12 Developing Java Programs Using Eclipse 27 FIGURE 1.19 The New Java Class dialog box is used to create a new Java class. FIGURE 1.20 You can edit a program and run it in Eclipse. Edit pane Output pane 1.12.3 Compiling and Running a Class To run the program, right-click the class in the project to display a context menu. Choose Run, Java Application in the read more..

  • Page - 51

    28 Chapter 1 Introduction to Computers, Programs, and Java Note The above terms are defined in this chapter. Supplement I.A, Glossary, lists all the key terms and descriptions in the book, organized by chapters. CHAPTER SUMMARY 1. A computer is an electronic device that stores and processes data. 2. A computer includes both hardware and software. 3. Hardware is the physical read more..

  • Page - 52

    8. A bit is a binary digit 0 or 1. 9. A byte is a sequence of 8 bits. 10. A kilobyte is about 1,000 bytes, a megabyte about 1 million bytes, a gigabyte about 1 billion bytes, and a terabyte about 1,000 gigabytes. 11. Memory stores data and program instructions for the CPU to execute. 12. A memory unit is an ordered sequence of bytes. 13. Memory is volatile, read more..

  • Page - 53

    30 Chapter 1 Introduction to Computers, Programs, and Java 30. Every statement in Java ends with a semicolon (;), known as the statement terminator. 31. Reserved words, or keywords, have a specific meaning to the compiler and cannot be used for other purposes in the program. 32. In Java, comments are preceded by two slashes (//) on a line, called a line comment, read more..

  • Page - 54

    1.7 (Approximatep) p can be computed using the following formula: p = 4 * ¢ 1 - 1 3 + 1 5 - 1 7 + 1 9 - 1 11 + c ≤ Write a program that displays the result of 4 * ¢ 1 - 1 3 + 1 5 - 1 7 + 1 9 - 1 11 ≤ and 4 * ¢ 1 - 1 3 + 1 5 - 1 7 + 1 9 - 1 11 + 1 13 ≤ . Use 1.0 instead of 1 in your program. 1.8 (Area and perimeter of a circle) Write read more..

  • Page - 55

    This page intentionally left blank read more..

  • Page - 56

    ELEMENTARY PROGRAMMING Objectives ■ To write Java programs to perform simple computations (§2.2). ■ To obtain input from the console using the Scanner class (§2.3). ■ To use identifiers to name variables, constants, methods, and classes (§2.4). ■ To use variables to store data (§§2.5–2.6). ■ To program with assignment statements and assignment expressions (§2.6). ■ To read more..

  • Page - 57

    34 Chapter 2 Elementary Programming 2.1 Introduction The focus of this chapter is on learning elementary programming techniques to solve problems. In Chapter 1 you learned how to create, compile, and run very basic Java programs. Now you will learn how to solve problems by writing programs. Through these problems, you will learn elementary programming using primitive data types, read more..

  • Page - 58

    2.2 Writing a Simple Program 35 // Step 3: Display the area } } The program needs to read the radius entered by the user from the keyboard. This raises two important issues: ■ Reading the radius. ■ Storing the radius in the program. Let’s address the second issue first. In order to store the radius, the program needs to declare a symbol called a read more..

  • Page - 59

    36 Chapter 2 Elementary Programming 7 radius = 20; // radius is now 20 8 9 // Compute area 10 area = radius * radius * 3.14159; 11 12 // Display results 13 System.out.println("The area for the circle of radius " + 14 radius + " is " + area); 15 } 16 } FIGURE 2.1 The program displays read more..

  • Page - 60

    2.3 Reading Input from the Console 37 2.1 Identify and fix the errors in the following code: 1 public class Test { 2 public void main(string[] args) { 3 double i = 50.0; 4 double k = i + 50.0; 5 double j = k + 1; 6 7 System.out.println("j is " + j + " and 8 k is " + k); 9 } 10 } 2.3 Reading read more..

  • Page - 61

    38 Chapter 2 Elementary Programming 16 System.out.println("The area for the circle of radius " + 17 radius + " is " + area); 18 } 19 } Enter a number for radius: 2.5 The area for the circle of radius 2.5 is 19.6349375 Enter a number for radius: 23 The area for the circle of radius 23.0 is 1661.90111 Line 9 read more..

  • Page - 62

    2.4 Identifiers 39 8 // Prompt the user to enter three numbers 9 System.out.print("Enter three numbers: "); 10 double number1 = input.nextDouble(); 11 double number2 = input.nextDouble(); 12 double number3 = input.nextDouble(); 13 14 // Compute average 15 double average = (number1 + number2 + number3) / 3; 16 17 // Display results 18 read more..

  • Page - 63

    40 Chapter 2 Elementary Programming ■ An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. ■ An identifier cannot be a reserved word. (See Appendix A for a list of reserved words.) ■ An identifier cannot be true, false, or null. ■ An identifier can be of any length. For example, $2, read more..

  • Page - 64

    2.6 Assignment Statements and Assignment Expressions 41 tells the compiler to allocate appropriate memory space for the variable based on its data type. The syntax for declaring a variable is datatype variableName; Here are some examples of variable declarations: int count; // Declare count to be an integer variable double radius; // Declare radius to be a double variable double read more..

  • Page - 65

    42 Chapter 2 Elementary Programming After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign (=) is used as the assignment operator. The syntax for assignment state- ments is as follows: variable = expression; An expression represents a computation involving values, variables, and operators that, taking them read more..

  • Page - 66

    2.7 Named Constants 43 illegal, because the data type of x is int. You cannot assign a double value (1.0) to an int variable without using type casting. Type casting is introduced in Section 2.15. 2.6 Identify and fix the errors in the following code: 1 public class Test { 2 public static void main(String[] args) { 3 int i = j = k = 2; 4 read more..

  • Page - 67

    44 Chapter 2 Elementary Programming 2.8 Naming Conventions Sticking with the Java naming conventions makes your programs easy to read and avoids errors. Make sure that you choose descriptive names with straightforward meanings for the variables, constants, classes, and methods in your program. As mentioned earlier, names are case sensi- tive. Listed below are the conventions for read more..

  • Page - 68

    2.9 Numeric Data Types and Operations 45 Note IEEE 754 is a standard approved by the Institute of Electrical and Electronics Engineers for representing floating-point numbers on computers. The standard has been widely adopted. Java uses the 32-bit IEEE 754 for the float type and the 64-bit IEEE 754 for the double type. The IEEE 754 standard also defines special read more..

  • Page - 69

    46 Chapter 2 Elementary Programming Here are examples for reading values of various types from the keyboard: 1 Scanner input = new Scanner(System.in); 2 System.out.print("Enter a byte value: "); 3 byte byteValue = input.nextByte(); 4 5 System.out.print("Enter a short value: "); 6 short shortValue = input.nextShort(); 7 8 System.out.print("Enter an int read more..

  • Page - 70

    2.9 Numeric Data Types and Operations 47 Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. Thus, you can use this property to determine whether a number is even or odd. If today is Saturday, it will be Saturday again in 7 days. Suppose you and your friends are going to meet in 10 read more..

  • Page - 71

    48 Chapter 2 Elementary Programming 2.9.4 Exponent Operations The Math.pow(a, b) method can be used to compute ab. The pow method is defined in the Math class in the Java API. You invoke the method using the syntax Math.pow(a, b) (e.g., Math.pow(2, 3)), which returns the result of ab (23). Here, a and b are parameters for the pow method and the numbers 2 read more..

  • Page - 72

    2.10 Numeric Literals 49 2.10.1 Integer Literals An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compile error will occur if the literal is too large for the variable to hold. The statement byte b = 128, for example, will cause a compile error, because 128 cannot be stored in a variable of the byte type. read more..

  • Page - 73

    50 Chapter 2 Elementary Programming Note The float and double types are used to represent numbers with a decimal point. Why are they called floating-point numbers? These numbers are stored in scientific nota- tion internally. When a number such as 50.534 is converted into scientific notation, such as 5.0534E+1, its decimal point is moved (i.e., floated) to a new position. read more..

  • Page - 74

    2.11 Evaluating Expressions and Operator Precedence 51 Here is an example of how an expression is evaluated: 3 + 4 * 4 + 5 * (4 + 3) - 1 3 + 4 * 4 + 5 * 7 – 1 3 + 16 + 5 * 7 – 1 3 + 16 + 35 – 1 19 + 35 – 1 54 – 1 53 (1) inside parentheses first (2) multiplication (3) multiplication (4) addition (5) read more..

  • Page - 75

    52 Chapter 2 Elementary Programming 2.12 Case Study: Displaying the Current Time You can invoke System.currentTimeMillis() to return the current time. The problem is to develop a program that displays the current time in GMT (Greenwich Mean Time) in the format hour:minute:second, such as 13:19:8. The currentTimeMillis method in the System class returns the current time in mil- read more..

  • Page - 76

    2.12 Case Study: Displaying the Current Time 53 11 12 // Obtain the total minutes 13 long totalMinutes = totalSeconds / 60; 14 15 // Compute the current minute in the hour 16 long currentMinute = totalMinutes % 60; 17 18 // Obtain the total hours 19 long totalHours = totalMinutes / 60; 20 21 // Compute the current hour 22 long currentHour = totalHours % 24; 23 24 // read more..

  • Page - 77

    54 Chapter 2 Elementary Programming 2.13 Augmented Assignment Operators The operators +, -, *, /, and % can be combined with the assignment operator to form augmented operators. Very often the current value of a variable is used, modified, and then reassigned back to the same variable. For example, the following statement increases the variable count by 1: count = count read more..

  • Page - 78

    2.14 Increment and Decrement Operators 55 System.out.println(a); a = 6; a /= 2; System.out.println(a); 2.14 Increment and Decrement Operators The increment operator (++) and decrement operator (– –) are for incrementing and decrementing a variable by 1. The ++ and —— are two shorthand operators for incrementing and decrementing a variable by 1. These are handy because read more..

  • Page - 79

    56 Chapter 2 Elementary Programming In this case, i is incremented by 1, then the old value of i is used in the multiplication. So newNum becomes 100. If i++ is replaced by ++i as follows, i is 11, newNum is 110 int i = 10; int newNum = 10 * (++i); System.out.print("i is " + i + ", newNum is " + newNum); Same effect as i = i + read more..

  • Page - 80

    2.15 Numeric Type Conversions 57 You can always assign a value to a numeric variable whose type supports a larger range of values; thus, for instance, you can assign a long value to a float variable. You cannot, however, assign a value to a variable of a type with a smaller range unless you use type casting. Casting is an operation that converts a value read more..

  • Page - 81

    58 Chapter 2 Elementary Programming LISTING 2.8 SalesTax.java 1 import java.util.Scanner; 2 3 public class SalesTax { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 7 System.out.print("Enter purchase amount: "); 8 double purchaseAmount = input.nextDouble(); 9 10 double tax = purchaseAmount * 0.06; read more..

  • Page - 82

    2.16 Software Development Process 59 2.16 Software Development Process The software development life cycle is a multistage process that includes requirements specification, analysis, design, implementation, testing, deployment, and maintenance. Developing a software product is an engineering process. Software products, no matter how large or how small, have the same life cycle: requirements read more..

  • Page - 83

    60 Chapter 2 Elementary Programming Testing ensures that the code meets the requirements specification and weeds out bugs. An independent team of software engineers not involved in the design and implementation of the product usually conducts such testing. Deployment makes the software available for use. Depending on the type of software, it may be installed on each user’s read more..

  • Page - 84

    2.16 Software Development Process 61 Stage 3: System Design During system design, you identify the steps in the program. Step 1. Prompt the user to enter the annual interest rate, the number of years, and the loan amount. (The interest rate is commonly expressed as a percentage of the principal for a period of one year. This is known as the annual interest rate.) Step read more..

  • Page - 85

    62 Chapter 2 Elementary Programming 27 double totalPayment = monthlyPayment * numberOfYears * 12; 28 29 // Display results 30 System.out.println("The monthly payment is $" + 31 (int)(monthlyPayment * 100) / 100.0); 32 System.out.println("The total payment is $" + 33 (int)(totalPayment * 100) / 100.0); 34 } 35 } read more..

  • Page - 86

    2.17 Case Study: Counting Monetary Units 63 2.32 How would you write the following arithmetic expression? -b + 2b2 - 4ac 2a 2.17 Case Study: Counting Monetary Units This section presents a program that breaks a large amount of money into smaller units. Suppose you want to develop a program that changes a given amount of money into smaller monetary units. The program lets read more..

  • Page - 87

    64 Chapter 2 Elementary Programming 21 remainingAmount = remainingAmount % 25; 22 23 // Find the number of dimes in the remaining amount 24 int numberOfDimes = remainingAmount / 10; 25 remainingAmount = remainingAmount % 10; 26 27 // Find the number of nickels in the remaining amount 28 int numberOfNickels = remainingAmount / 5; 29 read more..

  • Page - 88

    2.18 Common Errors and Pitfalls 65 is 11.56, then the initial remainingAmount is 1156. The division operator yields the inte- ger part of the division, so 1156 / 100 is 11. The remainder operator obtains the remainder of the division, so 1156 % 100 is 56. The program extracts the maximum number of singles from the remaining amount and obtains a new remaining read more..

  • Page - 89

    66 Chapter 2 Elementary Programming int value = -2147483648 - 1; // value will actually be 2147483647 Java does not report warnings or errors on overflow, so be careful when working with num- bers close to the maximum or minimum range of a given type. When a floating-point number is too small (i.e., too close to zero) to be stored, it causes underflow. Java read more..

  • Page - 90

    The code is not wrong, but inefficient. It creates two input objects unnecessarily and may lead to some subtle errors. You should rewrite the code as follows: Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int v1 = input.nextInt(); System.out.print("Enter a double value: "); double v2 = input.nextDouble(); 2.34 Can you declare a variable as read more..

  • Page - 91

    68 Chapter 2 Elementary Programming 4. There are two types of import statements: specific import and wildcard import. The specific import specifies a single class in the import statement; the wildcard import imports all the classes in a package. 5. In Java, the equal sign (=) is used as the assignment operator. 6. A variable declared in a method must be assigned a read more..

  • Page - 92

    PROGRAMMING EXERCISES Debugging TIP The compiler usually gives a reason for a syntax error. If you don’t know how to correct it, compare your program closely, character by character, with similar examples in the text. Pedagogical Note Instructors may ask you to document your analysis and design for selected exercises. Use your own words to analyze the problem, including the read more..

  • Page - 93

    70 Chapter 2 Elementary Programming 2.4 (Convert pounds into kilograms) Write a program that converts pounds into kilo- grams. The program prompts the user to enter a number in pounds, converts it to kilograms, and displays the result. One pound is 0.454 kilograms. Here is a sample run: Enter the time zone offset to GMT: −5 The current time is 4:50:34 Enter the number read more..

  • Page - 94

    Programming Exercises 71 2.9 (Physics: acceleration) Average acceleration is defined as the change of velocity divided by the time taken to make the change, as shown in the following formula: a = v1 - v0 t Write a program that prompts the user to enter the starting velocity v0 in meters/ second, the ending velocity v1 in meters/second, and the time span t in seconds, read more..

  • Page - 95

    72 Chapter 2 Elementary Programming **2.13 (Financial application: compound value) Suppose you save $100 each month into a savings account with the annual interest rate 5%. Thus, the monthly inter- est rate is 0.05/12 = 0.00417. After the first month, the value in the account becomes 100 * (1 + 0.00417) = 100.417 After the second month, the value in the account becomes read more..

  • Page - 96

    Programming Exercises 73 *2.17 (Science: wind-chill temperature) How cold is it outside? The temperature alone is not enough to provide the answer. Other factors including wind speed, rela- tive humidity, and sunshine play important roles in determining coldness outside. In 2001, the National Weather Service (NWS) implemented the new wind-chill temperature to measure the coldness using read more..

  • Page - 97

    74 Chapter 2 Elementary Programming Sections 2.13–2.17 *2.20 (Financial application: calculate interest) If you know the balance and the annual percentage interest rate, you can compute the interest on the next monthly pay- ment using the following formula: interest = balance * (annualInterestRate/1200) Write a program that reads the balance and the annual percentage interest rate and read more..

  • Page - 98

    SELECTIONS Objectives ■ To declare boolean variables and write Boolean expressions using relational operators (§3.2). ■ To implement selection control using one-way if statements (§3.3). ■ To implement selection control using two-way if-else statements (§3.4). ■ To implement selection control using nested if and multi-way if statements (§3.5). ■ To avoid common errors and read more..

  • Page - 99

    76 Chapter 3 Selections 3.1 Introduction The program can decide which statements to execute based on a condition. If you enter a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java, the program displays an invalid result. If the radius is negative, you don’t want the program to compute the area. How can you deal with this situation? Like all high-level read more..

  • Page - 100

    3.2 boolean Data Type 77 two  values: true or false. For example, the following statement assigns true to the variable lightsOn: boolean lightsOn = true; true and false are literals, just like a number such as 10. They are treated as reserved words and cannot be used as identifiers in the program. Suppose you want to develop a program to let a first-grader read more..

  • Page - 101

    78 Chapter 3 Selections 3.1 List six relational operators. 3.2 Assuming that x is 1, show the result of the following Boolean expressions: (x > 0 ) (x < 0 ) (x != 0) (x >= 0 ) (x != 1) 3.3 Can the following conversions involving casting be allowed? Write a test program to verify your answer. boolean b = true; i = (int)b; int i = 1; boolean b = (boolean)i; 3.3 read more..

  • Page - 102

    3.3 if Statements 79 if i > 0 { System.out.println("i is positive"); } (a) Wrong if (i > 0 ) { System.out.println("i is positive"); } (b) Correct The block braces can be omitted if they enclose a single statement. For example, the fol- lowing statements are equivalent. if (i > 0 ){ System.out.println("i is positive"); } (a) if (i > 0 read more..

  • Page - 103

    80 Chapter 3 Selections FIGURE 3.2 An if-else statement executes statements for the true case if the Boolean- expression evaluates to true; otherwise, statements for the false case are executed. Statement(s) for the true case Statement(s) for the false case boolean- expression true false Enter an integer: 4 HiEven Enter an integer: 30 HiFive HiEven The program prompts the user to enter read more..

  • Page - 104

    If the boolean-expression evaluates to true, the statement(s) for the true case are executed; otherwise, the statement(s) for the false case are executed. For example, consider the following code: if (radius >= 0 ) { area = radius * radius * PI; System.out.println("The area for the circle of radius " + radius + " is " + area); } else read more..

  • Page - 105

    82 Chapter 3 Selections The execution of this if statement proceeds as shown in Figure 3.4. The first condition (score >= 90.0) is tested. If it is true, the grade is A. If it is false, the second condition (score >= 80.0) is tested. If the second condition is true, the grade is B. If that condition is false, the third condition and the rest of the conditions read more..

  • Page - 106

    3.6 Common Errors and Pitfalls 83 The if statement in Figure 3.3a is equivalent to the if statement in Figure 3.3b. In fact, Figure 3.3b is the preferred coding style for multiple alternative if statements. This style, called multi-way if-else statements, avoids deep indentation and makes the program easy to read. 3.8 Suppose x = 3 and y = 2; show the output, if any, of the following read more..

  • Page - 107

    84 Chapter 3 Selections Common Error 2: Wrong Semicolon at the if Line Adding a semicolon at the end of an if line, as shown in (a) below, is a common mistake. if (radius >= 0 ) area = radius * radius * PI; System.out.println("The area " + " is " + area); (a) Wrong if (radius >= 0 ){ area = radius * radius * PI; read more..

  • Page - 108

    3.6 Common Errors and Pitfalls 85 However, the else clause actually matches the second if clause. This situation is known as the dangling else ambiguity. The else clause always matches the most recent unmatched if clause in the same block. So, the statement in (a) is equivalent to the code in (b). dangling else ambiguity int i = 1, j = 2, k = 3; if (i read more..

  • Page - 109

    86 Chapter 3 Selections Common Pitfall 1: Simplifying Boolean Variable Assignment Often, new programmers write the code that assigns a test condition to a boolean variable like the code in (a): if (number % 2 == 0) even = true; else even = false; (a) Equivalent boolean even = number % 2 == 0; (b) This is shorter This is not an error, but it should be read more..

  • Page - 110

    3.7 Generating Random Numbers 87 3.13 Are the following statements correct? Which one is better? if (age < 16) System.out.println ("Cannot get a driver's license"); if (age >= 16) System.out.println ("Can get a driver's license"); (a) if (age < 16) System.out.println ("Cannot get a driver's license"); else System.out.println read more..

  • Page - 111

    88 Chapter 3 Selections 12 number1 = number2; 13 number2 = temp; 14 } 15 16 // 3. Prompt the student to answer ”What is number1 – number2?” 17 System.out.print 18 ("What is " + number1 + " - " + number2 + "? "); 19 Scanner input = new Scanner(System.in); 20 int read more..

  • Page - 112

    3.8 Case Study: Computing Body Mass Index 89 3.8 Case Study: Computing Body Mass Index You can use nested if statements to write a program that interprets body mass index. Body Mass Index (BMI) is a measure of health based on height and weight. It can be cal- culated by taking your weight in kilograms and dividing it by the square of your height in meters. The read more..

  • Page - 113

    90 Chapter 3 Selections The constants KILOGRAMS_PER_POUND and METERS_PER_INCH are defined in lines 15–16. Using constants here makes programs easy to read. You should test the input that covers all possible cases for BMI to ensure that the program works for all cases. 3.9 Case Study: Computing Taxes You can use nested if statements to write a program for computing taxes. read more..

  • Page - 114

    3.9 Case Study: Computing Taxes 91 Your program computes the tax for the taxable income based on the filing status. The filing status can be determined using if statements outlined as follows: if (status == 0) { // Compute tax for single filers } else if (status == 1) { // Compute tax for married filing jointly or qualifying widow(er) } else if (status == 2) { read more..

  • Page - 115

    92 Chapter 3 Selections 33 else if (income <= 372950) 34 tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + 35 (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + 36 (income - 171550) * 0.33; 37 else 38 tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + 39 read more..

  • Page - 116

    3.10 Logical Operators 93 To test a program, you should provide the input that covers all cases. For this program, your input should cover all statuses (0, 1, 2, 3). For each status, test the tax for each of the six brackets. So, there are a total of 24 cases. Tip For all programs, you should write a small amount of code and test it before moving on to add read more..

  • Page - 117

    94 Chapter 3 Selections p1 p2 p1 && p2 Example (assume age = 24, weight = 140) false false false false true false (age > 28) && (weight <= 140) is true, because (age > 28) is false. true false false true true true (age > 18) && (weight >= 140) is true, because (age > 18) and (weight >= 140) are both true. TABLE 3.5 Truth Table for Operator read more..

  • Page - 118

    3.10 Logical Operators 95 15 if (number % 2 == 0 || number % 3 == 0) 16 System.out.println(number + " is divisible by 2 or 3."); 17 18 if (number % 2 == 0 ^ number % 3 == 0) 19 System.out.println(number + 20 " is divisible by 2 or 3, but not both."); 21 } 22 } or exclusive or Enter an integer: 4 read more..

  • Page - 119

    96 Chapter 3 Selections If one of the operands of an && operator is false, the expression is false; if one of the operands of an || operator is true, the expression is true. Java uses these properties to improve the performance of these operators. When evaluating p1 && p2, Java first evaluates p1 and then, if p1 is true, evaluates p2; if p1 is false, read more..

  • Page - 120

    3.11 Case Study: Determining Leap Year 97 3.26 Write a Boolean expression that evaluates to true if weight is greater than 50 pounds or height is greater than 60 inches. 3.27 Write a Boolean expression that evaluates to true if weight is greater than 50 pounds and height is greater than 60 inches. 3.28 Write a Boolean expression that evaluates to true if either weight is read more..

  • Page - 121

    98 Chapter 3 Selections 3.12 Case Study: Lottery The lottery program involves generating random numbers, comparing digits, and using Boolean operators. Suppose you want to develop a program to play lottery. The program randomly generates a lottery of a two-digit number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following read more..

  • Page - 122

    3.12 Case Study: Lottery 99 34 else 35 System.out.println("Sorry, no match"); 36 } 37 } Enter your lottery pick (two digits): 15 The lottery number is 15 Exact match: you win $10,000 Enter your lottery pick (two digits): 45 The lottery number is 54 Match all digits: you win $3,000 Enter your lottery pick: 23 The lottery number is 34 Match one read more..

  • Page - 123

    100 Chapter 3 Selections 3.13 switch Statements A switch statement executes statements based on the value of a variable or an expression. The if statement in Listing 3.5, ComputeTax.java, makes selections based on a single true or false condition. There are four cases for computing taxes, which depend on the value of status. To fully account for all the cases, nested if read more..

  • Page - 124

    case value2: statement(s)2; break; ... case valueN: statement(s)N; break; default: statement(s)-for-default; } The switch statement observes the following rules: ■ The switch-expression must yield a value of char, byte, short, int, or String type and must always be enclosed in parentheses. (The char and String types will be introduced in the next chapter.) ■ read more..

  • Page - 125

    102 Chapter 3 Selections LISTING 3.9 ChineseZodiac.java 1 import java.util.Scanner; 2 3 public class ChineseZodiac { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 7 System.out.print("Enter a year: "); 8 int year = input.nextInt(); 9 10 switch (year % 12) { 11 case 0: read more..

  • Page - 126

    3.14 Conditional Expressions 103 3.30 What is y after the following switch statement is executed? Rewrite the code using an if-else statement. x = 3; y = 3; switch (x + 3) { case 6: y = 1; default: y += 1; } 3.31 What is x after the following if-else statement is executed? Use a switch state- ment to rewrite it and draw the flowchart for the new read more..

  • Page - 127

    104 Chapter 3 Selections As you can see from these examples, conditional expressions enable you to write short and concise code. Note The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java. 3.33 Suppose that, when you run read more..

  • Page - 128

    3.15 Operator Precedence and Associativity 105 If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left associative. For example, since + and – are of the same precedence and are left associative, the expression operator associativity TABLE 3.8 Operator read more..

  • Page - 129

    106 Chapter 3 Selections 3.40 Is (x > 0 && x < 10) the same as ((x > 0) && (x < 10)) ? Is (x > 0 || x < 10) the same as ((x > 0) || (x < 10))? Is (x > 0 || x < 10 && y < 0) the same as (x > 0 || (x < 10 && y < 0))? 3.16 Debugging Debugging is the process of finding and fixing errors in a program. As read more..

  • Page - 130

    CHAPTER SUMMARY 1. A boolean type variable can store a true or false value. 2. The relational operators (<, <=, ==, !=, >, >=) yield a Boolean value. 3. Selection statements are used for programming with alternative courses of actions. There are several types of selection statements: one-way if statements, two-way if-else statements, nested if statements, multi-way read more..

  • Page - 131

    108 Chapter 3 Selections TEST QUESTIONS Answer the quiz for this chapter online at www.cs.armstrong.edu/liang/intro10e/quiz.html . PROGRAMMING EXERCISES Pedagogical Note For each exercise, carefully analyze the problem requirements and design strategies for solving the problem before coding. Debugging Tip Before you ask for help, read and explain the program to yourself, and trace it using read more..

  • Page - 132

    Sections 3.3–3.7 *3.3 (Algebra: solve 2 * 2 linear equations) A linear equation can be solved using Cramer’s rule given in Programming Exercise 1.13. Write a program that prompts the user to enter a, b, c, d, e, and f and displays the result. If ad - bc is 0, report that “The equation has no solution.” Enter a, b, c, d, e, f: 9.0 4.0 3.0 -5.0 -6.0 read more..

  • Page - 133

    110 Chapter 3 Selections *3.8 (Sort three integers) Write a program that prompts the user to enter three integers and display the integers in non-decreasing order. **3.9 (Business: check ISBN-10) An ISBN-10 (International Standard Book Number) consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum, which is calculated from the other nine digits using the read more..

  • Page - 134

    **3.15 (Game: lottery) Revise Listing 3.8, Lottery.java, to generate a lottery of a three- digit number. The program prompts the user to enter a three-digit number and determines whether the user wins according to the following rules: 1. If the user input matches the lottery number in the exact order, the award is $10,000. 2. If all digits in the user input match all read more..

  • Page - 135

    112 Chapter 3 Selections Comprehensive **3.21 (Science: day of the week) Zeller’s congruence is an algorithm developed by Christian Zeller to calculate the day of the week. The formula is h = ¢ q + 26(m + 1) 10 + k + k 4 + j 4 + 5j ≤ %7 where ■ h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday, 4: Wednesday, 5: Thursday, 6: Friday). ■ read more..

  • Page - 136

    **3.23 (Geometry: point in a rectangle?) Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the rectangle centered at (0, 0) with width 10 and height 5. For example, (2, 2) is inside the rectangle and (6, 4) is outside the rectangle, as shown in Figure 3.7b. ( Hint: A point is in the rectangle if its horizontal read more..

  • Page - 137

    114 Chapter 3 Selections Write a program that prompts the user to enter four points and displays the inter- secting point. Here are sample runs: Enter x1, y1, x2, y2, x3, y3, x4, y4: 2 2 5 -1.0 4.0 2.0 -1.0 -2.0 The intersecting point is at (2.88889, 1.1111) Enter x1, y1, x2, y2, x3, y3, x4, y4: 2 2 7 6.0 4.0 2.0 -1.0 -2.0 The two lines are parallel Enter an read more..

  • Page - 138

    **3.28 (Geometry: two rectangles) Write a program that prompts the user to enter the center x-, y-coordinates, width, and height of two rectangles and determines whether the second rectangle is inside the first or overlaps with the first, as shown in Figure 3.9. Test your program to cover all cases. Enter a point's x- and y-coordinates: 100.5 50.5 The point is not in the triangle read more..

  • Page - 139

    116 Chapter 3 Selections *3.30 (Current time) Revise Programming Exercise 2.8 to display the hour using a 12-hour clock. Here is a sample run: FIGURE 3.10 (a) A circle is inside another circle. (b) A circle overlaps another circle. (a) (b) (x1, y1) (x2, y2) r2 r1 (x1, y1) r1 (x2, y2) r2 Enter the time zone offset to GMT: -5 The current time is 4:50:34 AM Enter the exchange read more..

  • Page - 140

    *3.32 (Geometry: point position) Given a directed line from point p0(x0, y0) to p1(x1, y1), you can use the following condition to decide whether a point p2(x2, y2) is on the left of the line, on the right, or on the same line (see Figure 3.11): (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0) c 70 p2 is on the left side of the line =0p2isonthe same line 60 p2 is on read more..

  • Page - 141

    118 Chapter 3 Selections *3.34 (Geometry: point on line segment) Programming Exercise 3.32 shows how to test whether a point is on an unbounded line. Revise Programming Exercise 3.32 to test whether a point is on a line segment. Write a program that prompts the user to enter the three points for p0, p1, and p2 and displays whether p2 is on the line segment from p0 read more..

  • Page - 142

    MATHEMATICAL FUNCTIONS, CHARACTERS, AND  STRINGS Objectives ■ To solve mathematical problems by using the methods in the Math class (§4.2). ■ To represent characters using the char type (§4.3). ■ To encode characters using ASCII and Unicode (§4.3.1). ■ To represent special characters using the escape sequences (§4.4.2). ■ To cast a numeric value to a character and cast read more..

  • Page - 143

    120 Chapter 4 Mathematical Functions, Characters, and Strings 4.1 Introduction The focus of this chapter is to introduce mathematical functions, characters, string objects, and use them to develop programs. The preceding chapters introduced fundamental programming techniques and taught you how to write simple programs to solve basic problems using selection statements. This chapter intro- read more..

  • Page - 144

    4.2 Common Mathematical Functions 121 The parameter for sin, cos, and tan is an angle in radians. The return value for asin, acos, and atan is a degree in radians in the range between -p/2 and p/2. One degree is equal to p/180 in radians, 90 degrees is equal to p/2 in radians, and 30 degrees is equal to p/6 in radians. For example, Math.toDegrees(Math.PI read more..

  • Page - 145

    122 Chapter 4 Mathematical Functions, Characters, and Strings For example, Math.ceil(2.1) returns 4.0 Math.ceil(2.0) returns 2.0 Math.ceil(-2.0) returns -2.0 Math.ceil(-2.1) returns -2.0 Math.floor(2.1) returns 2.0 Math.floor(2.0) returns 2.0 Math.floor(-2.0) returns –2.0 Math.floor(-2.1) returns -4.0 Math.rint(2.1) returns 2.0 Math.rint(-2.0) returns –2.0 Math.rint(-2.1) returns -2.0 Math.rint(2.5) returns 2.0 read more..

  • Page - 146

    4.2 Common Mathematical Functions 123 4.2.6 Case Study: Computing Angles of a Triangle You can use the math methods to solve many computational problems. Given the three sides of a triangle, for example, you can compute the angles by using the following formula: A B C a b c x1, y1 x2, y2 x3, y3 A = acos((a * a - b * b - c * c) / (-2 * b * c)) B = acos((b read more..

  • Page - 147

    124 Chapter 4 Mathematical Functions, Characters, and Strings 35 Math.round(B * 100) / 100.0 + " " + 36 Math.round(C * 100) / 100.0); 37 } 38 } Enter three points: 1 1 6.5 1 6.5 2.5 The three angles are 15.26 90.0 74.74 The program prompts the user to enter three points (line 8). This prompting message is read more..

  • Page - 148

    4.3 Character Data Type and Operations 125 4.3 Character Data Type and Operations A character data type represents a single character. In addition to processing numeric values, you can process characters in Java. The character data type, char, is used to represent a single character. A character literal is enclosed in single quotation marks. Consider the following code: char read more..

  • Page - 149

    126 Chapter 4 Mathematical Functions, Characters, and Strings You can use ASCII characters such as 'X', '1', and '$' in a Java program as well as Unicodes. Thus, for example, the following statements are equivalent: char letter = 'A'; char letter = '\u0041'; // Character A's Unicode is 0041 Both statements assign character A to the char variable letter. Note The read more..

  • Page - 150

    4.3 Character Data Type and Operations 127 4.3.3 Casting between char and Numeric Types A char can be cast into any numeric type, and vice versa. When an integer is cast into a char, only its lower 16 bits of data are used; the other part is ignored. For example: char ch = (char)0XAB0041; // The lower 16 bits hex code 0041 is // assigned to ch read more..

  • Page - 151

    128 Chapter 4 Mathematical Functions, Characters, and Strings 4.3.4 Comparing and Testing Characters Two characters can be compared using the relational operators just like comparing two numbers. This is done by comparing the Unicodes of the two characters. For example, 'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98). 'a' < 'A' read more..

  • Page - 152

    4.3 Character Data Type and Operations 129 isLowerCase('a') is true isUpperCase('a') is false toLowerCase('T') is t toUpperCase('q') is Q 4.8 Use print statements to find out the ASCII code for '1', 'A', 'B', 'a', and 'b'. Use print statements to find out the character for the decimal codes 40, 59, 79, 85, and 90. Use print statements to find out the character for the read more..

  • Page - 153

    130 Chapter 4 Mathematical Functions, Characters, and Strings 4.4 The String Type A string is a sequence of characters. The char type represents only one character. To represent a string of characters, use the data type called String. For example, the following code declares message to be a string with the value "Welcome to Java". String message = "Welcome to read more..

  • Page - 154

    4.4 The String Type 131 displays The length of Welcome to Java is 15 Note When you use a string, you often know its literal value. For convenience, Java allows you to use the string literal to refer directly to strings without creating new variables. Thus, "Welcome to Java".length() is correct and returns 15. Note that "" denotes an empty string and read more..

  • Page - 155

    132 Chapter 4 Mathematical Functions, Characters, and Strings (e.g., a number), the nonstring value is converted into a string and concatenated with the other string. Here are some examples: // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; read more..

  • Page - 156

    4.4 The String Type 133 The next() method reads a string that ends with a whitespace character. You can use the nextLine() method to read an entire line of text. The nextLine() method reads a string that ends with the Enter key pressed. For example, the following statements read a line of text. Scanner input = new Scanner(System.in); System.out.println("Enter read more..

  • Page - 157

    134 Chapter 4 Mathematical Functions, Characters, and Strings How do you compare the contents of two strings? You might attempt to use the == operator, as follows: if (string1 == string2) System.out.println("string1 and string2 are the same object"); else System.out.println("string1 and string2 are different objects"); However, the == operator checks only whether string1 and read more..

  • Page - 158

    4.4 The String Type 135 "Welcome to Java".endsWith("v") returns false. "Welcome to Java".contains("to") returns true. "Welcome to Java".contains("To") returns false. Listing 4.2 gives a program that prompts the user to enter two cities and displays them in alphabetical order. LISTING 4.2 OrderTwoCities.java 1 import java.util.Scanner; 2 3 public class read more..

  • Page - 159

    136 Chapter 4 Mathematical Functions, Characters, and Strings Note If beginIndex is endIndex, substring(beginIndex, endIndex) returns an empty string with length 0. If beginIndex > endIndex, it would be a runtime error. 4.4.9 Finding a Character or a Substring in a String The String class provides several versions of indexOf and lastIndexOf methods to find a character or a read more..

  • Page - 160

    4.4 The String Type 137 For example, if s is Kim Jones, the following diagram illustrates how the first name and last name are extracted. Indices Message 012345678 K i m J ones s.substring (k + 1) is Jones k is 3 s.substring (0, k) is Kim 4.4.10 Conversion between Strings and Numbers You can convert a numeric string into a number. To convert a string into an int value, read more..

  • Page - 161

    138 Chapter 4 Mathematical Functions, Characters, and Strings 4.17 Suppose that s1 and s2 are two strings. Which of the following statements or expressions are incorrect? String s = "Welcome to Java"; String s3 = s1 + s2; String s3 = s1 - s2; s1 == s2; s1 >= s2; s1.compareTo(s2); int i = s1.length(); char c = s1(0); char c = s1.charAt(s1.length()); 4.18 Show read more..

  • Page - 162

    4.5 Case Studies 139 (o) Assign the index of the first occurrence of the character e in s1 to an int variable x . (p) Assign the index of the last occurrence of the string abc in s1 to an int variable x. 4.5 Case Studies Strings are fundamental in programming. The ability to write programs using strings is essential in learning Java programming. You will frequently use read more..

  • Page - 163

    140 Chapter 4 Mathematical Functions, Characters, and Strings 13 "10 11 14 15\n" + 14 "18 19 22 23\n" + 15 "26 27 30 31"; 16 17 String set3 = 18 " 4 5 6 7\n" + 19 "12 13 14 15\n" + 20 "20 21 22 23\n" + 21 "28 29 30 31"; 22 23 String set4 = 24 " 8 9 10 11\n" + 25 read more..

  • Page - 164

    4.5 Case Studies 141 73 if (answer == 1) 74 day += 8; 75 76 // Prompt the user to answer questions 77 System.out.print("\nIs your birthday in Set5?\n"); 78 System.out.print(set5); 79 System.out.print("\nEnter 0 for No and 1 for Yes: "); 80 answer = input.nextInt(); 81 82 if (answer == 1) 83 read more..

  • Page - 165

    142 Chapter 4 Mathematical Functions, Characters, and Strings This game is easy to program. You may wonder how the game was created. The mathematics behind the game is actually quite simple. The numbers are not grouped together by accident— the way they are placed in the five sets is deliberate. The starting numbers in the five sets are 1, 2, 4, 8, and 16, which read more..

  • Page - 166

    4.5 Case Studies 143 LISTING 4.4 HexDigit2Dec.java 1 import java.util.Scanner; 2 3 public class HexDigit2Dec { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 System.out.print("Enter a hex digit: "); 7 String hexString = input.nextLine(); 8 9 // Check if the hex string has exactly one read more..

  • Page - 167

    144 Chapter 4 Mathematical Functions, Characters, and Strings if ch is 'B', and so on. When two characters perform a numerical operation, the characters’ Unicodes are used in the computation. The program invokes the Character.isDigit(ch) method to check if ch is between '0' and '9' (line 22). If so, the corresponding decimal digit is the same as ch (lines 23–24). read more..

  • Page - 168

    4.6 Formatting Console Output 145 35 else 36 System.out.println("Sorry, no match"); 37 } 38 } Enter your lottery pick (two digits): 00 The lottery number is 00 Exact match: you win $10,000 Enter your lottery pick (two digits): 45 The lottery number is 54 Match all digits: you win $3,000 Enter your lottery pick: 23 The lottery number is 34 Match read more..

  • Page - 169

    146 Chapter 4 Mathematical Functions, Characters, and Strings Because the interest amount is currency, it is desirable to display only two digits after the decimal point. To do this, you can write the code as follows: double amount = 12618.98; double interestRate = 0.0013; double interest = amount * interestRate; System.out.println("Interest is $" + (int)(interest * read more..

  • Page - 170

    4.6 Formatting Console Output 147 Items must match the format specifiers in order, in number, and in exact type. For example, the format specifier for count is %d and for amount is %f. By default, a floating-point value is displayed with six digits after the decimal point. You can specify the width and precision in a format specifier, as shown in the examples in read more..

  • Page - 171

    148 Chapter 4 Mathematical Functions, Characters, and Strings Caution The items must match the format specifiers in exact type. The item for the format specifier %f or %e must be a floating-point type value such as 40.0, not 40. Thus, an int variable cannot match %f or %e. Tip The % sign denotes a format specifier. To output a literal % in the format string, read more..

  • Page - 172

    4.24 Show the output of the following statements. (a) System.out.printf("amount is %f %e\n", 32.32, 32.32); (b) System.out.printf("amount is %5.2%% %5.4e\n", 32.327, 32.32); (c) System.out.printf("%6b\n", (1 > 2)); (d) System.out.printf("%6s\n", "Java"); (e) System.out.printf("%-6b%s\n",(1 > 2), "Java"); (f) System.out.printf("%6b%-8s\n",(1 > read more..

  • Page - 173

    150 Chapter 4 Mathematical Functions, Characters, and Strings 10. You can get the length of a string by invoking its length() method, retrieve a char- acter at the specified index in the string using the charAt(index) method, and use the indexOf and lastIndexOf methods to find a character or a substring in a string. 11. You can use the concat method to read more..

  • Page - 174

    *4.2 (Geometry: great circle distance) The great circle distance is the distance between two points on the surface of a sphere. Let (x1, y1) and (x2, y2) be the geographi- cal latitude and longitude of two points. The great circle distance between the two points can be computed using the following formula: d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 read more..

  • Page - 175

    152 Chapter 4 Mathematical Functions, Characters, and Strings Here, s is the length of a side. Write a program that prompts the user to enter the number of sides and their length of a regular polygon and displays its area. Here is a sample run: Enter the number of sides: 5 Enter the side: 6.5 The area of the polygon is 74.69017017488385 *4.6 (Random points on a read more..

  • Page - 176

    *4.9 (Find the Unicode of a character) Write a program that receives a character and displays its Unicode. Here is a sample run: Programming Exercises 153 Enter a character: E The Unicode for the character E is 69 *4.10 (Guess birthday) Rewrite Listing 4.3, GuessBirthday.java, to prompt the user to enter the character Y for Yes and N for No rather than entering 1 for Yes and read more..

  • Page - 177

    154 Chapter 4 Mathematical Functions, Characters, and Strings *4.14 (Convert letter grade to number) Write a program that prompts the user to enter a letter grade A, B, C, D, or F and displays its corresponding numeric value 4, 3, 2, 1, or 0. Here is a sample run: Enter a letter grade: B The numeric value for grade B is 3 Enter a letter grade: T T is an invalid read more..

  • Page - 178

    Programming Exercises 155 *4.18 (Student major and status) Write a program that prompts the user to enter two characters and displays the major and status represented in the characters. The first character indicates the major and the second is number character 1, 2, 3, 4, which indicates whether a student is a freshman, sophomore, junior, or senior. Suppose the following read more..

  • Page - 179

    156 Chapter 4 Mathematical Functions, Characters, and Strings Enter string s1: ABCD Enter string s2: BDC BDC is not a substring of ABCD *4.23 (Financial application: payroll) Write a program that reads the following infor- mation and prints a payroll statement: Employee’s name (e.g., Smith) Number of hours worked in a week (e.g., 10) Hourly pay rate (e.g., 9.75) Federal tax read more..

  • Page - 180

    LOOPS Objectives ■ To write programs for executing statements repeatedly using a while loop (§5.2). ■ To follow the loop design strategy to develop loops (§§5.2.1–5.2.3). ■ To control a loop with a sentinel value (§5.2.4). ■ To obtain large input from a file using input redirection rather than typing from the keyboard (§5.2.5). ■ To write loops using do-while read more..

  • Page - 181

    158 Chapter 5 Loops 5.1 Introduction A loop can be used to tell a program to execute statements repeatedly. Suppose that you need to display a string (e.g., Welcome to Java!) a hundred times. It would be tedious to have to write the following statement a hundred times: Key Point problem System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); ... read more..

  • Page - 182

    In this example, you know exactly how many times the loop body needs to be executed because the control variable count is used to count the number of executions. This type of loop is known as a counter-controlled loop. Note The loop-continuation-condition must always appear inside the parentheses. The braces enclosing the loop body can be omitted only if the loop body read more..

  • Page - 183

    160 Chapter 5 Loops Note Make sure that the loop-continuation-condition eventually becomes false so that the loop will terminate. A common programming error involves infinite loops (i. e., the loop runs forever). If your program takes an unusually long time to run and does not stop, it may have an infinite loop. If you are running the program from the command window, press CTRL+C to stop it. read more..

  • Page - 184

    The loop in lines 15–19 repeatedly prompts the user to enter an answer when number1 + number2 != answer is true. Once number1 + number2 != answer is false, the loop exits. 5.2.1 Case Study: Guessing Numbers The problem is to guess what number a computer has in mind. You will write a program that randomly generates an integer between 0 and 100, inclusive. The read more..

  • Page - 185

    162 Chapter 5 Loops 17 else if (guess > number) 18 System.out.println("Your guess is too high"); 19 else 20 System.out.println("Your guess is too low"); 21 } 22 } When you run this program, it prompts the user to enter a guess only once. To let the user enter a guess repeatedly, you may wrap the code in lines 11–20 in read more..

  • Page - 186

    15 guess = input.nextInt(); 16 17 if (guess == number) 18 System.out.println("Yes, the number is " + number); 19 else if (guess > number) 20 System.out.println("Your guess is too high"); 21 else 22 System.out.println("Your guess is too low"); 23 } // End of loop 24 } 25 } enter read more..

  • Page - 187

    164 Chapter 5 Loops 5.2.3 Case Study: Multiple Subtraction Quiz The Math subtraction learning tool program in Listing 3.3, SubtractionQuiz.java, generates just one question for each run. You can use a loop to generate questions repeatedly. How do you write the code to generate five questions? Follow the loop design strategy. First identify the statements that need to be repeated. read more..

  • Page - 188

    43 } 44 45 long endTime = System.currentTimeMillis(); 46 long testTime = endTime - startTime; 47 48 System.out.println("Correct count is " + correctCount + 49 "\nTest time is " + testTime / 1000 + " seconds\n" + output); 50 } 51 } end loop get end time test time display result What is 9 – 2? 7 You are correct! What is 3 – read more..

  • Page - 189

    166 Chapter 5 Loops LISTING 5.5 SentinelValue.java 1 import java.util.Scanner; 2 3 public class SentinelValue { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a Scanner 7 Scanner input = new Scanner(System.in); 8 9 // Read an initial data 10 System.out.print( 11 "Enter an integer (the input ends if it is read more..

  • Page - 190

    Caution Don’t use floating-point values for equality checking in a loop control. Because floating- point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1: double item = 1; double sum = 0; while (item != 0) { // No guarantee item read more..

  • Page - 191

    168 Chapter 5 Loops 5.2 What is wrong if guess is initialized to 0 in line 11 in Listing 5.3? 5.3 How many times are the following loop bodies repeated? What is the output of each loop? int i = 1; while (i < 10) if (i % 2 == 0) System.out.println(i); (a) int i = 1; while (i < 10) if (i % 2 == 0) System.out.println(i++); (b) int read more..

  • Page - 192

    loop terminates. The difference between a while loop and a do-while loop is the order in which the loop-continuation-condition is evaluated and the loop body executed. You can write a loop using either the while loop or the do-while loop. Sometimes one is a more convenient choice than the other. For example, you can rewrite the while loop in Listing 5.5 using a read more..

  • Page - 193

    170 Chapter 5 Loops Tip Use a do-while loop if you have statements inside the loop that must be executed at least once, as in the case of the do-while loop in the preceding TestDoWhile program. These statements must appear before the loop as well as inside it if you use a while loop. 5.6 Suppose the input is 2 3 4 5 0. What is the output of the following read more..

  • Page - 194

    A for loop can be used to simplify the preceding loop as: for (i = initialValue; i < endValue; i++) // Loop body ... } In general, the syntax of a for loop is: for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; Statement(s); } The flowchart of the for loop is shown in Figure 5.3a. for loop FIGURE 5.3 A for read more..

  • Page - 195

    172 Chapter 5 Loops tests whether the control variable has reached a termination value. For example, the following for loop prints Welcome to Java! a hundred times: int i; for (i = 0; i < 100 ; i++) { System.out.println("Welcome to Java!"); } The flowchart of the statement is shown in Figure 5.3b. The for loop initializes i to 0, then repeatedly executes read more..

  • Page - 196

    5.8 Do the following two loops result in the same value in sum? ✓ Point ✓Check Equivalent Equivalent for ( ; ; ) { // Do something } (a) for ( ; true; ) { // Do something } (b) while (true) { // Do something } (c) This is better for (int i = 0; i < 10; ++i) { sum += i; } (a) for (int i = 0; i < 10; i++) { sum += i; } read more..

  • Page - 197

    174 Chapter 5 Loops 5.5 Which Loop to Use? You can use a for loop, a while loop, or a do-while loop, whichever is convenient. The while loop and for loop are called pretest loops because the continuation condition is checked before the loop body is executed. The do-while loop is called a posttest loop because the condition is checked after the loop body is read more..

  • Page - 198

    5.5 Which Loop to Use? 175 Similarly, the loop in (c) is also wrong. (c) is equivalent to (d). Both are incorrect. int i = 0; while (i < 10); { System.out.println("i is " + i); i++; } (c) Error int i = 0; while (i < 10) { }; { System.out.println("i is " + i); i++; } (d) Empty body These errors often occur when you use the read more..

  • Page - 199

    176 Chapter 5 Loops 5.18 What is wrong with the following programs? 1 public class ShowErrors { 2 public static void main(String[] args) { 3 int i = 0; 4 do { 5 System.out.println(i + 4); 6 i++; 7 } 8 while (i < 10) 9 } 10 } (a) 1 public class ShowErrors { 2 public static void main(String[] args) { read more..

  • Page - 200

    5.6 Nested Loops 177 The program displays a title (line 5) on the first line in the output. The first for loop (lines 9–10) displays the numbers 1 through 9 on the second line. A dashed (-) line is displayed on the third line (line 12). The next loop (lines 15–22) is a nested for loop with the control variable i in the outer loop and j in the read more..

  • Page - 201

    178 Chapter 5 Loops 5.7 Minimizing Numeric Errors Using floating-point numbers in the loop continuation condition may cause numeric errors. Numeric errors involving floating-point numbers are inevitable, because floating-point num- bers are represented in approximation in computers by nature. This section discusses how to minimize such errors through an example. Listing 5.8 presents an example summing read more..

  • Page - 202

    5.8 Case Studies 179 sum += currentValue; currentValue += 0.01; } After this loop, sum is 50.50000000000003. This loop adds the numbers from smallest to biggest. What happens if you add numbers from biggest to smallest (i.e., 1.0, 0.99, 0.98, . . . , 0.02, 0.01 in this order) as follows: double currentValue = 1.0; for (int count = 0; count < 100 ; read more..

  • Page - 203

    180 Chapter 5 Loops LISTING 5.9 GreatestCommonDivisor.java 1 import java.util.Scanner; 2 3 public class GreatestCommonDivisor { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a Scanner 7 Scanner input = new Scanner(System.in); 8 9 // Prompt the user to enter two integers 10 System.out.print("Enter first integer: read more..

  • Page - 204

    5.8 Case Studies 181 This revision is wrong. Can you find the reason? See Checkpoint Question 5.21 for the answer. 5.8.2 Case Study: Predicting the Future Tuition Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every year. In how many years will the tuition be doubled? Before you can write a program to solve this problem, first read more..

  • Page - 205

    182 Chapter 5 Loops 5.8.3 Case Study: Converting Decimals to Hexadecimals Hexadecimals are often used in computer systems programming (see Appendix  F for an introduction to number systems). How do you convert a decimal number to a hexadecimal number? To convert a decimal number d to a hexadecimal number is to find the hexadecimal digits hn, hn - 1, hn - 2, c , h2, read more..

  • Page - 206

    5.8 Case Studies 183 24 decimal = decimal / 16; 25 } 26 27 System.out.println("The hex number is " + hex); 28 } 29 } get a hex char get a letter Enter a decimal number: 1234 The hex number is 4D2 line# decimal hex hexValue hexDigit 14 1234 "" 17 2 iteration 1 23 "2" 2 24 77 17 13 iteration 2 23 "D2" read more..

  • Page - 207

    184 Chapter 5 Loops 5.9 Keywords break and continue The break and continue keywords provide additional controls in a loop. Pedagogical Note Two keywords, break and continue, can be used in loop statements to provide addi- tional controls. Using break and continue can simplify programming in some cases. Overusing or improperly using them, however, can make programs difficult read more..

  • Page - 208

    4 int number = 0; 5 6 while (number < 20) { 7 number++; 8 if (number ==10 || number == 11) 9 continue; 10 sum += number; 11 } 12 13 System.out.println("The sum is " + sum); 14 } 15 } continue 5.9 Keywords break and continue 185 The sum is 189 The program in Listing 5.13 adds integers read more..

  • Page - 209

    186 Chapter 5 Loops found = true; else factor++; } System.out.println("The smallest factor other than 1 for " + n + " is " + factor); Obviously, the break statement makes this program simpler and easier to read in this case. However, you should use break and continue with caution. Too many break and con- tinue statements will produce a loop read more..

  • Page - 210

    5.10 Case Study: Checking Palindromes 187 5.27 After the break statement in (a) is executed in the following loop, which statement is executed? Show the output. After the continue statement in (b) is executed in the following loop, which statement is executed? Show the output. for (int i = 1; i < 4 ; i++) { for (int j = 1; j < 4 ; j++) { if (i * read more..

  • Page - 211

    188 Chapter 5 Loops 26 low++; 27 high--; 28 } 29 30 if (isPalindrome) 31 System.out.println(s + " is a palindrome"); 32 else 33 System.out.println(s + " is not a palindrome"); 34 } 35 } update indices Enter a string: noon noon is a palindrome Enter a string: moon moon is not a read more..

  • Page - 212

    5.11 Case Study: Displaying Prime Numbers 189 while (count < NUMBER_OF_PRIMES) { Test whether number is prime; if number is prime { Display the prime number and increase the count; } Increment number by 1; } To test whether a number is prime, check whether it is divisible by 2, 3, 4, and so on up to number/2. If a divisor is found, the read more..

  • Page - 213

    190 Chapter 5 Loops 33 } 34 35 // Check if the next number is prime 36 number++; 37 } 38 } 39 } KEY TERMS break statement 184 continue statement 184 do-while loop 168 for loop 171 infinite loop 160 input redirection 167 iteration 158 loop 158 loop body 158 nested loop 176 off-by-one error 160 output redirection 167 posttest loop 174 pretest read more..

  • Page - 214

    CHAPTER SUMMARY 1. There are three types of repetition statements: the while loop, the do-while loop, and the for loop. 2. The part of the loop that contains the statements to be repeated is called the loop body. 3. A one-time execution of a loop body is referred to as an iteration of the loop. 4. An infinite loop is a loop statement that executes infinitely. 5. read more..

  • Page - 215

    192 Chapter 5 Loops Sections 5.2–5.7 *5.1 (Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the read more..

  • Page - 216

    Miles Kilometers | Kilometers Miles 1 1.609 | 20 12.430 2 3.218 | 25 15.538 ... 9 14.481 | 60 37.290 10 16.090 read more..

  • Page - 217

    194 Chapter 5 Loops *5.18 (Display four patterns using loops) Use nested loops that display the following patterns in four separate programs: Pattern A Pattern B Pattern C Pattern D 1 1 2 3 4 5 6 1 1 2 3 4 5 6 1 2 read more..

  • Page - 218

    number of years, and interest rate and displays the amortization schedule for the loan. Here is a sample run: Programming Exercises 195 Loan Amount: 10000 Number of Years: 1 Annual Interest Rate: 7 Monthly Payment: 865.26 Total Payment: 10383.21 Payment# Interest Principal Balance 1 58.33 806.93 read more..

  • Page - 219

    196 Chapter 5 Loops **5.25 (Compute p) You can approximate p by using the following series: p = 4 ¢ 1 - 1 3 + 1 5 - 1 7 + 1 9 - 1 11 + g + ( -1)i + 1 2i - 1 ≤ Write a program that displays the p value for i = 10000, 20000, …, and 100000. **5.26 (Compute e) You can approximate e using the following series: e = 1 + 1 1! + 1 2! + 1 3! + 1 4! + g read more..

  • Page - 220

    *5.30 (Financial application: compound value) Suppose you save $100 each month into a savings account with the annual interest rate 5%. So, the monthly interest rate is 0.05 / 12 = 0.00417. After the first month, the value in the account becomes 100 * (1 + 0.00417) = 100.417 After the second month, the value in the account becomes (100 + 100.417) * (1 + 0.00417) = read more..

  • Page - 221

    198 Chapter 5 Loops **5.32 (Game: lottery) Revise Listing 3.8, Lottery.java, to generate a lottery of a two- digit number. The two digits in the number are distinct. (Hint: Generate the first digit. Use a loop to continuously generate the second digit until it is different from the first digit.) **5.33 (Perfect number) A positive integer is called a perfect number if it is equal to read more..

  • Page - 222

    Your goal is to earn $30,000 a year. Write a program that finds the minimum sales you have to generate in order to make $30,000. 5.40 (Simulation: heads or tails) Write a program that simulates flipping a coin one million times and displays the number of heads and tails. *5.41 (Occurrence of max numbers) Write a program that reads integers, finds the larg- est of read more..

  • Page - 223

    200 Chapter 5 Loops you how tightly all the various data are clustered around the mean in a set of data. For example, what is the average age of the students in a class? How close are the ages? If all the students are the same age, the deviation is 0. Write a program that prompts the user to enter ten numbers, and displays the mean and standard deviations read more..

  • Page - 224

    Programming Exercises 201 Enter a string: Programming is fun The number of vowels is 5 The number of consonants is 11 Enter a string: Welcome to Java The number of uppercase letters is 2 *5.49 (Count vowels and consonants) Assume letters A, E, I, O, and U as the vowels. Write a program that prompts the user to enter a string and displays the number of vowels and read more..

  • Page - 225

    This page intentionally left blank read more..

  • Page - 226

    METHODS Objectives ■ To define methods with formal parameters (§6.2). ■ To invoke methods with actual parameters (i.e., arguments) (§6.2). ■ To define methods with a return value (§6.3). ■ To define methods without a return value (§6.4). ■ To pass arguments by value (§6.5). ■ To develop reusable code that is modular, easy to read, easy to debug, and easy to read more..

  • Page - 227

    204 Chapter 6 Methods 6.1 Introduction Methods can be used to define reusable code and organize and simplify coding. Suppose that you need to find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively. You may write the code as follows: int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to read more..

  • Page - 228

    6.2 Defining a Method 205 Let’s look at a method defined to find the larger between two integers. This method, named max, has two int parameters, num1 and num2, the larger of which is returned by the method. Figure 6.1 illustrates the components of this method. FIGURE 6.1 A method definition consists of a method header and a method body. Define a method Invoke read more..

  • Page - 229

    206 Chapter 6 Methods Note We say “define a method” and “declare a variable.” We are making a subtle distinction here. A definition defines what the defined item is, but a declaration usually involves allocating memory to store data for the declared item. 6.3 Calling a Method Calling a method executes the code in the method. In a method definition, you define what read more..

  • Page - 230

    6.3 Calling a Method 207 This program contains the main method and the max method. The main method is just like any other method except that it is invoked by the JVM to start the program. The main method’s header is always the same. Like the one in this example, it includes the modifiers public and static, return value type void, method name main, and a read more..

  • Page - 231

    208 Chapter 6 Methods To fix this problem, delete if (n < 0) in (a), so the compiler will see a return statement to be reached regardless of how the if statement is evaluated. Note Methods enable code sharing and reuse. The max method can be invoked from any class, not just TestMax. If you create a new class, you can invoke the max method using read more..

  • Page - 232

    6.4 void Method Example A void method does not return a value. The preceding section gives an example of a value-returning method. This section shows how to define and invoke a void method. Listing 6.2 gives a program that defines a method named printGrade and invokes it to print the grade for a given score. LISTING 6.2 TestVoidMethod.java 1 public class read more..

  • Page - 233

    210 Chapter 6 Methods 7 public static char getGrade(double score) { 8 if (score >= 90.0) 9 return 'A'; 10 else if (score >= 80.0) 11 return 'B'; 12 else if (score >= 70.0) 13 return 'C'; 14 else if (score >= 60.0) 15 return 'D'; 16 else 17 return 'F'; 18 } 19 } getGrade method The grade is C The grade is F The getGrade method defined in lines read more..

  • Page - 234

    6.1 What are the benefits of using a method? 6.2 How do you define a method? How do you invoke a method? 6.3 How do you simplify the max method in Listing 6.1 using the conditional operator? 6.4 True or false? A call to a method with a void return type is always a statement itself, but a call to a value-returning method cannot be a statement by itself. 6.5 What read more..

  • Page - 235

    212 Chapter 6 Methods 6.5 Passing Arguments by Values The arguments are passed by value to parameters when invoking a method. The power of a method is its ability to work with parameters. You can use println to print any string and max to find the maximum of any two int values. When calling a method, you need to provide arguments, which must be given in the read more..

  • Page - 236

    6.5 Passing Arguments by Values 213 Listing 6.5 gives another program that demonstrates the effect of passing by value. The pro- gram creates a method for swapping two variables. The swap method is invoked by passing two arguments. Interestingly, the values of the arguments are not changed after the method is invoked. LISTING 6.5 TestPassByValue.java 1 public class read more..

  • Page - 237

    214 Chapter 6 Methods Note For simplicity, Java programmers often say passing x to y, which actually means passing the value of argument x to parameter y. 6.11 How is an argument passed to a method? Can the argument have the same name as its parameter? 6.12 Identify and correct the errors in the following program: 1 public class Test { 2 public static void main(String[] read more..

  • Page - 238

    6.6 Modularizing Code 215 6.14 For (a) in the preceding question, show the contents of the activation records in the call stack just before the method max is invoked, just as max is entered, just before max is returned, and right after max is returned. 6.6 Modularizing Code Modularizing makes the code easy to maintain and debug and enables the code to be reused. read more..

  • Page - 239

    216 Chapter 6 Methods 15 System.out.println("The greatest common divisor for " + n1 + 16 " and " + n2 + " is " + gcd(n1, n2)); 17 } 18 19 /** Return the gcd of two integers */ 20 public static int gcd(int n1, int n2) { 21 int gcd = 1; // Initial gcd is 1 22 int k = 2; // Possible gcd 23 24 while (k <= n1 && read more..

  • Page - 240

    6.7 Case Study: Converting Hexadecimals to Decimals 217 18 if (count % NUMBER_OF_PRIMES_PER_LINE == 0) { 19 // Print the number and advance to the new line 20 System.out.printf("%-5s\n", number); 21 } 22 else 23 System.out.printf("%-5s", number); 24 } 25 26 // Check whether the next read more..

  • Page - 241

    218 Chapter 6 Methods A brute-force approach is to convert each hex character into a decimal number, multiply it by 16i for a hex digit at the i’s position, and then add all the items together to obtain the equiva- lent decimal value for the hex number. Note that hn * 16n + hn - 1 * 16n - 1 + hn - 2 * 16n - 2 + c + h1 * 161 + h0 * 160 = ( c((hn read more..

  • Page - 242

    6.8 Overloading Methods 219 22 } 23 24 return decimalValue; 25 } 26 27 public static int hexCharToDecimal(char ch) { 28 if (ch >= 'A' && ch <= 'F') 29 return 10 + ch - 'A'; 30 else // ch is '0', '1', ..., or '9' 31 return ch - '0'; 32 } 33 } hex char to decimal check uppercase Enter a hex number: AB8C The decimal value read more..

  • Page - 243

    220 Chapter 6 Methods Listing 6.9 is a program that creates three methods. The first finds the maximum integer, the second finds the maximum double, and the third finds the maximum among three double values. All three methods are named max. LISTING 6.9 TestMethodOverloading.java 1 public class TestMethodOverloading { 2 /** Main method */ 3 public static void main(String[] read more..

  • Page - 244

    6.8 Overloading Methods 221 You may be wondering why the method max(double, double) is not invoked for the call max(3, 4). Both max(double, double) and max(int, int) are possible matches for max(3, 4). The Java compiler finds the method that best matches a method invocation. Since the method max(int, int) is a better matches for max(3, 4) than max(double, double), read more..

  • Page - 245

    222 Chapter 6 Methods return y; } } 6.17 Given two method definitions, public static double m(double x, double y) public static double m(int x, double y) tell which of the two methods is invoked for: a. double z = m(4, 5); b. double z = m(4, 5.4); c. double z = m(4.5, 5.4); 6.9 The Scope of Variables The scope of a variable is the part of the read more..

  • Page - 246

    6.10 Case Study: Generating Random Characters 223 Caution Do not declare a variable inside a block and then attempt to use it outside the block. Here is an example of a common mistake: for (int i = 0; i < 10; i++) { } System.out.println(i); The last statement would cause a syntax error, because variable i is not defined outside of the for loop. 6.18 What is a read more..

  • Page - 247

    224 Chapter 6 Methods As discussed in Section 4.3.3, all numeric operators can be applied to the char operands. The char operand is cast into a number if the other operand is a number or a character. Therefore, the preceding expression can be simplified as follows: 'a' + Math.random() * ('z' - 'a' + 1) and a random lowercase letter is (char)('a' + Math.random() read more..

  • Page - 248

    6.11 Method Abstraction and Stepwise Refinement 225 9 char ch = RandomCharacter.getRandomLowerCaseLetter(); 10 if ((i + 1) % CHARS_PER_LINE == 0) 11 System.out.println(ch); 12 else 13 System.out.print(ch); 14 } 15 } 16 } lower-case letter gmjsohezfkgtazqgmswfclrao pnrunulnwmaztlfjedmpchcif lalqdgivxkxpbzulrmqmbhikr lbnrjlsopfxahssqhwuuljvbe read more..

  • Page - 249

    226 Chapter 6 Methods Let us use this example to demonstrate the divide-and-conquer approach. 6.11.1 Top-Down Design How would you get started on such a program? Would you immediately start coding? Begin- ning programmers often start by trying to work out the solution to every detail. Although details are important in the final program, concern for detail in the early stages may read more..

  • Page - 250

    6.11 Method Abstraction and Stepwise Refinement 227 as shown in Figure 6.9b. For example, December 2013 has 31 days, and December 1, 2013, is a Sunday. How would you get the start day for the first date in a month? There are several ways to do so. For now, we’ll use an alternative approach. Assume you know that the start day for January 1, 1800, was a read more..

  • Page - 251

    228 Chapter 6 Methods let printMonth display the year and the month in the stub. Thus, your program may begin like this: public class PrintCalendar { /** Main method */ public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter year System.out.print("Enter full year (e.g., 2012): "); int read more..

  • Page - 252

    6.11 Method Abstraction and Stepwise Refinement 229 /** A stub for getMonthName may look like this */ public static String getMonthName(int month) { return "January"; // A dummy value } /** A stub for getStartDay may look like this */ public static int getStartDay(int year, int month) { return 1; // A dummy value } /** A stub for read more..

  • Page - 253

    230 Chapter 6 Methods LISTING 6.12 PrintCalendar.java 1 import java.util.Scanner; 2 3 public class PrintCalendar { 4 /** Main method */ 5 public static void main(String[] args) { 6 Scanner input = new Scanner(System.in); 7 8 // Prompt the user to enter year 9 System.out.print("Enter full year (e.g., 2012): "); read more..

  • Page - 254

    6.11 Method Abstraction and Stepwise Refinement 231 59 public static void printMonthBody(int year, int month) { 60 // Get start day of the week for the first date in the month 61 int startDay = getStartDay(year, month) 62 63 // Get number of days in the month 64 int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month); 65 66 // Pad space before the read more..

  • Page - 255

    232 Chapter 6 Methods 119 120 return 0; // If month is incorrect 121 } 122 123 /** Determine if it is a leap year */ 124 public static boolean isLeapYear(int year) { 125 return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0); 126 } 127 } The program does not validate user input. For instance, if the user enters either a month read more..

  • Page - 256

    Chapter Summary 233 CHAPTER SUMMARY 1. Making programs modular and reusable is one of the central goals in software engineer- ing. Java provides many powerful constructs that help to achieve this goal. Methods are one such construct. 2. The method header specifies the modifiers, return value type, method name, and param- eters of the method. The static modifier is used for read more..

  • Page - 257

    234 Chapter 6 Methods QUIZ Answer the quiz for this chapter online at www.cs.armstrong.edu/liang/intro10e/quiz.html . PROGRAMMING EXERCISES Note A common error for the exercises in this chapter is that students don’t implement the methods to meet the requirements even though the output from the main pro- gram is correct. For an example of this type of error see www.cs.armstrong.edu/liang/ read more..

  • Page - 258

    Programming Exercises 235 Write a test program that prompts the user to enter three numbers and invokes the method to display them in increasing order. *6.6 (Display patterns) Write a method to display a pattern as follows: 1 2 1 3 2 1 ... n n-1 ... 3 2 1 The method header is public read more..

  • Page - 259

    236 Chapter 6 Methods Write a test program that invokes these methods to display the following tables: Celsius Fahrenheit | Fahrenheit Celsius 40.0 104.0 | 120.0 48.89 39.0 102.2 | 110.0 43.33 ... 32.0 89.6 | 40.0 4.44 31.0 87.8 | 30.0 -1.11 Feet Meters | Meters Feet 1.0 0.305 | 20.0 65.574 2.0 0.610 | 25.0 81.967 ... 9.0 2.745 | 60.0 196.721 10.0 3.050 | 65.0 213.115 6.9 (Conversions between read more..

  • Page - 260

    Programming Exercises 237 6.12 (Display characters) Write a method that prints characters using the following header: public static void printChars(char ch1, char ch2, int numberPerLine) This method prints the characters between ch1 and ch2 with the specified num- bers per line. Write a test program that prints ten characters per line from 1 to Z. Characters are separated read more..

  • Page - 261

    238 Chapter 6 Methods Use this method to write a program that prints a tax table for taxable income from $50,000 to $60,000 with intervals of $50 for all the following statuses: Taxable Income Single Married Joint or Qualifying Widow(er) Married Separate Head of a House 50000 8688 6665 8688 7353 50050 8700 6673 8700 7365 ... 59950 11175 8158 11175 9840 60000 11188 8165 11188 9853 Enter n: read more..

  • Page - 262

    Programming Exercises 239 /** Return the area of the triangle. */ public static double area( double side1, double side2, double side3) Write a test program that reads three sides for a triangle and computes the area if the input is valid. Otherwise, it displays that the input is invalid. The formula for computing the area of a triangle is given in Programming read more..

  • Page - 263

    240 Chapter 6 Methods For example, count("Welcome", 'e') returns 2. Write a test program that prompts the user to enter a string followed by a character and displays the number of occurrences of the character in the string. Sections 6.10–6.12 **6.24 (Display current date and time) Listing 2.7, ShowCurrentTime.java, displays the current time. Improve this example to display read more..

  • Page - 264

    Programming Exercises 241 **6.30 (Game: craps) Craps is a popular dice game played in casinos. Write a program to play a variation of the game, as follows: Roll two dice. Each die has six faces representing values 1, 2, …, and 6, respec- tively. Check the sum of the two dice. If the sum is 2, 3, or 12 (called craps), you lose; if the sum is 7 or 11 (called read more..

  • Page - 265

    242 Chapter 6 Methods 2. Now add all single-digit numbers from Step 1. 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37 3. Add all digits in the odd places from right to left in the card number. 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38 4. Sum the results from Step 2 and Step 3. 37 + 38 = 75 5. If the result from Step 4 is divisible by 10, the card number is read more..

  • Page - 266

    Programming Exercises 243 **6.34 (Print calendar) Programming Exercise 3.21 uses Zeller’s congruence to calcu- late the day of the week. Simplify Listing 6.12, PrintCalendar.java, using Zeller’s algorithm to get the start day of the month. 6.35 (Geometry: area of a pentagon) The area of a pentagon can be computed using the following formula: Area = 5 * s2 4 * tan ¢p 5 ≤ read more..

  • Page - 267

    244 Chapter 6 Methods returns the string representation for the number. For example, format(34, 1) returns 34. Write a test program that prompts the user to enter a number and its width and displays a string returned by invoking format(number, width). *6.38 (Generate random characters) Use the methods in RandomCharacter in Listing 6.10 to print 100 uppercase letters and then 100 read more..

  • Page - 268

    SINGLE-DIMENSIONAL ARRAYS Objectives ■ To describe why arrays are necessary in programming (§7.1). ■ To declare array reference variables and create arrays (§§7.2.1–7.2.2). ■ To obtain array size using arrayRefVar.length and know default values in an array (§7.2.3). ■ To access array elements using indexes (§7.2.4). ■ To declare, create, and initialize an array using an read more..

  • Page - 269

    246 Chapter 7 Single-Dimensional Arrays 7.1 Introduction A single array variable can reference a large collection of data. Often you will have to store a large number of values during the execution of a program. Suppose, for instance, that you need to read 100 numbers, compute their average, and find out how many numbers are above the average. Your program first reads read more..

  • Page - 270

    7.2 Array Basics 247 array variable is declared, you can create an array by using the new operator and assign its reference to the variable with the following syntax: arrayRefVar = new elementType[arraySize]; This statement does two things: (1) it creates an array using new elementType[arraySize]; (2) it assigns the reference of the newly created array to the variable read more..

  • Page - 271

    248 Chapter 7 Single-Dimensional Arrays Note An array variable that appears to hold an array actually contains a reference to that array. Strictly speaking, an array variable and an array are different, but most of the time the distinction can be ignored. Thus it is all right to say, for simplicity, that myList is an array, instead of stating, at greater length, that read more..

  • Page - 272

    7.2 Array Basics 249 myList[2] = 3.4; myList[3] = 3.5; Caution The new operator is not used in the array-initializer syntax. Using an array initializer, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. Thus, the next statement is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5}; 7.2.6 Processing Arrays read more..

  • Page - 273

    250 Chapter 7 Single-Dimensional Arrays 5. Finding the largest element: Use a variable named max to store the largest element. Initially max is myList[0]. To find the largest element in the array myList, compare each element with max, and update max if the element is greater than max. double max = myList[0]; for (int i = 1; i < myList.length; i++) { if read more..

  • Page - 274

    7.2 Array Basics 251 accessed simply via the index. The following code prompts the user to enter a month number and displays its month name: String[] months = {"January", "February", ..., "December" }; System.out.print("Enter a month number (1 to 12): "); int monthNumber = input.nextInt(); System.out.println("The month is " + months[monthNumber - 1]); read more..

  • Page - 275

    252 Chapter 7 Single-Dimensional Arrays 7.3 What is the output of the following code? int x = 30; int[] numbers = new int[x]; x = 60; System.out.println("x is " + x); System.out.println("The size of numbers is " + numbers.length); 7.4 Indicate true or false for the following statements: ■ Every element in an array has the same type. ■ The array size read more..

  • Page - 276

    7.3 Case Study: Analyzing Numbers 253 4 for (int i = 1; i < list.length; i++) 5 list[i] = list[i - 1]; 6 7 for (int i = 0; i < list.length; i++) 8 System.out.print(list[i] + " "); 9 } 10 } 7.3 Case Study: Analyzing Numbers The problem is to write a program that finds the number of items above the read more..

  • Page - 277

    254 Chapter 7 Single-Dimensional Arrays each number in the array with the average to count the number of values above the average (lines 17–20). 7.4 Case Study: Deck of Cards The problem is to create a program that will randomly select four cards from a deck of cards. Say you want to write a program that will pick four cards at random from a deck of 52 read more..

  • Page - 278

    7.4 Case Study: Deck of Cards 255 Listing 7.2 gives the solution to the problem. LISTING 7.2 DeckOfCards.java 1 public class DeckOfCards { 2 public static void main(String[] args) { 3 int[] deck = new int[52]; 4 String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"}; 5 String[] ranks = {"Ace", "2", read more..

  • Page - 279

    256 Chapter 7 Single-Dimensional Arrays With suits = {"Spades", "Hearts", "Diamonds", "Clubs"} created in an array, suits[deck / 13] gives the suit for the deck. Using arrays greatly simplifies the solution for this program. 7.12 Will the program pick four random cards if you replace lines 22–27 in Listing 7.2 DeckOfCards.java with the following read more..

  • Page - 280

    7.6 Passing Arrays to Methods 257 You can write a loop to copy every element from the source array to the corresponding element in the target array. The following code, for instance, copies sourceArray to targetArray using a for loop. int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArray.length; i++) { read more..

  • Page - 281

    258 Chapter 7 Single-Dimensional Arrays Note The preceding statement creates an array using the following syntax: new elementType[]{value0, value1, ..., valuek}; There is no explicit reference variable for the array. Such array is called an anonymous array. Java uses pass-by-value to pass arguments to a method. There are important differences between passing the values of variables read more..

  • Page - 282

    7.6 Passing Arrays to Methods 259 Note Arrays are objects in Java (objects are introduced in Chapter  9). The JVM stores the objects in an area of memory called the heap, which is used for dynamic memory allocation. Listing 7.3 gives another program that shows the difference between passing a primitive data type value and an array reference variable to a method. The program contains two read more..

  • Page - 283

    260 Chapter 7 Single-Dimensional Arrays As shown in Figure 7.6, the two elements are not swapped using the swap method. However, they are swapped using the swapFirstTwoInArray method. Since the parameters in the swap method are primitive type, the values of a[0] and a[1] are passed to n1 and n2 inside the method when invoking swap(a[0], a[1]). The memory locations for n1 read more..

  • Page - 284

    7.8 Case Study: Counting the Occurrences of Each Letter 261 7.15 Suppose the following code is written to reverse the contents in an array, explain why it is wrong. How do you fix it? int[] list = {1, 2, 3, 5, 4}; for (int i = 0, j = list.length - 1; i < list.length; i++, j--) { // Swap list[i] with list[j] int temp = list[i]; list[i] = list[j]; read more..

  • Page - 285

    262 Chapter 7 Single-Dimensional Arrays 11 // Count the occurrences of each letter 12 int[] counts = countLetters(chars); 13 14 // Display counts 15 System.out.println(); 16 System.out.println("The occurrences of each letter are:"); 17 displayCounts(counts); 18 } 19 20 /** Create an array of characters */ 21 public static char[] createArray() { 22 // Declare read more..

  • Page - 286

    7.8 Case Study: Counting the Occurrences of Each Letter 263 The createArray method (lines 21–32) generates an array of 100 random lowercase let- ters. Line 5 invokes the method and assigns the array to chars. What would be wrong if you rewrote the code as follows? char[] chars = new char[100]; chars = createArray(); You would be creating two arrays. The first line read more..

  • Page - 287

    264 Chapter 7 Single-Dimensional Arrays 7.16 True or false? When an array is passed to a method, a new array is created and passed to the method. 7.17 Show the output of the following two programs: ✓ Point ✓Check FIGURE 7.8 (a) An array of 100 characters is created when executing createArray. (b) This array is returned and assigned to the variable chars in the main method. Array read more..

  • Page - 288

    7.10 Searching Arrays 265 Java treats a variable-length parameter as an array. You can pass an array or a variable number of arguments to a variable-length parameter. When invoking a method with a vari- able number of arguments, Java creates an array and passes the arguments to it. Listing 7.5 contains a method that prints the maximum value in a list of an unspecified read more..

  • Page - 289

    266 Chapter 7 Single-Dimensional Arrays of the element in the array that matches the key. If no match is found, the search returns -1. The linearSearch method in Listing 7.6 gives the solution. LISTING 7.6 LinearSearch.java linear search animation on Companion Website list key Compare key with list[i] for i = 0, 1, … [0] [1] [2] … 1 public class LinearSearch { 2 read more..

  • Page - 290

    7.10 Searching Arrays 267 You now know how the binary search works. The next task is to implement it in Java. Don’t rush to give a complete implementation. Implement it incrementally, one step at a time. You may start with the first iteration of the search, as shown in Figure 7.10a. It compares the key with the middle element in the list whose low index is 0 and read more..

  • Page - 291

    268 Chapter 7 Single-Dimensional Arrays The complete program is given in Listing 7.7. LISTING 7.7 BinarySearch.java 1 public class BinarySearch { 2 /** Use binary search to find the key in the list */ 3 public static int binarySearch(int[] list, int key) { 4 int low = 0; 5 int high = list.length - 1; 6 7 while (high >= low) { 8 int mid = read more..

  • Page - 292

    7.11 Sorting Arrays 269 7.21 If high is a very large integer such as the maximum int value 2147483647, (low + high) / 2 may cause overflow. How do you fix it to avoid overflow? 7.22 Use Figure 7.9 as an example to show how to apply the binary search approach to a search for key 10 and key 12 in list {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}. 7.23 If the read more..

  • Page - 293

    270 Chapter 7 Single-Dimensional Arrays The solution can be described as follows: for (int i = 0; i < list.length - 1; i++) { select the smallest element in list[i..list.length-1]; swap the smallest with list[i], if necessary; // list[i] is in its correct position. // The next iteration applies on list[i+1..list.length-1] } Listing 7.8 implements the solution. LISTING read more..

  • Page - 294

    7.12 The Arrays Class 271 The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, filling array elements, and returning a string representation of the array. These methods are overloaded for all primitive types. You can use the sort or parallelSort method to sort a whole array or a partial array. For example, the read more..

  • Page - 295

    272 Chapter 7 Single-Dimensional Arrays You can also use the toString method to return a string that represents all elements in the array. This is a quick and simple way to display all elements in the array. For example, the following code int[] list = {2, 4, 7, 10}; System.out.println(Arrays.toString(list)); displays [2, 4, 7, 10]. 7.26 What types of array can be sorted read more..

  • Page - 296

    7.13 Command-Line Arguments 273 It starts the program with three strings: First num, alpha, and 53. Since First num is a string, it is enclosed in double quotes. Note that 53 is actually treated as a string. You can use "53" instead of 53 in the command line. When the main method is invoked, the Java interpreter creates an array to hold the com- read more..

  • Page - 297

    274 Chapter 7 Single-Dimensional Arrays The program is shown in Listing 7.9. LISTING 7.9 Calculator.java 1 public class Calculator { 2 /** Main method */ 3 public static void main(String[] args) { 4 // Check number of strings passed 5 if (args.length != 3) { 6 System.out.println( 7 "Usage: java Calculator operand1 operator operand2"); 8 read more..

  • Page - 298

    Chapter Summary 275 public static void main(String x[]) static void main(String x[]) 7.30 Show the output of the following program when invoked using 1. java Test I have a dream 2. java Test “1 2 3” 3. java Test public class Test { public static void main(String[] args) { System.out.println("Number of strings is " + args.length); for (int i read more..

  • Page - 299

    276 Chapter 7 Single-Dimensional Arrays 7. When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, \u0000 for char types, and false for boolean types. 8. Java has a shorthand notation, known as the array initializer, which combines declaring an array, creating an array, and initializing an array in one read more..

  • Page - 300

    **7.3 (Count occurrence of numbers) Write a program that reads the integers between 1 and 100 and counts the occurrences of each. Assume the input ends with 0. Here is a sample run of the program: Programming Exercises 277 Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0 2 occurs 2 times 3 occurs 1 time 4 occurs 1 time 5 occurs 2 times 6 occurs read more..

  • Page - 301

    278 Chapter 7 Single-Dimensional Arrays 7.9 (Find the smallest element) Write a method that finds the smallest element in an array of double values using the following header: public static double min(double[] array) Write a test program that prompts the user to enter ten numbers, invokes this method to return the minimum value, and displays the minimum value. Here is a read more..

  • Page - 302

    enter ten numbers, invokes the method to reverse the numbers, and displays the numbers. Section 7.9 *7.13 (Random number chooser) Write a method that returns a random number between 1 and 54, excluding the numbers passed in the argument. The method header is specified as follows: public static int getRandom(int... numbers) 7.14 (Computing gcd) Write a method that returns the gcd read more..

  • Page - 303

    280 Chapter 7 Single-Dimensional Arrays **7.19 (Sorted?) Write the following method that returns true if the list is already sorted in increasing order. public static boolean isSorted(int[] list) Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input read more..

  • Page - 304

    (Hint: Create an array named slots. Each element in slots stores the num- ber of balls in a slot. Each ball falls into a slot via a path. The number of Rs in a path is the position of the slot where the ball falls. For example, for the path LRLRLRR, the ball falls into slots[4], and for the path is RRLLLLL, the ball falls into slots[2].) ***7.22 (Game: Eight read more..

  • Page - 305

    282 Chapter 7 Single-Dimensional Arrays objects to be picked at least once. A variation of the problem is to pick cards from a shuffled deck of 52 cards repeatedly and find out how many picks are needed before you see one of each suit. Assume a picked card is placed back in the deck before picking another. Write a program to simulate the number of picks needed read more..

  • Page - 306

    Write a test program that prompts the user to enter two lists of integers and dis- plays whether the two are identical. Here are the sample runs. Note that the first number in the input indicates the number of the elements in the list. This number is not part of the list. Enter list1: 5 2 5 6 6 1 Enter list2: 5 5 2 6 1 6 Two lists are identical Enter read more..

  • Page - 307

    284 Chapter 7 Single-Dimensional Arrays Implement the method in a way that takes at most list1.length + list2. length comparisons. Write a test program that prompts the user to enter two sorted lists and displays the merged list. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list. This number is not part read more..

  • Page - 308

    the number of misses and ask the user whether to continue to play with another word. Declare an array to store words, as follows: // Add any words you wish in this array String[] words = {"write", "that", ...}; (Guess) Enter a letter in word ******* > p (Guess) Enter a letter in word p****** > r (Guess) Enter a letter in word pr**r** > p read more..

  • Page - 309

    This page intentionally left blank read more..

  • Page - 310

    MULTIDIMENSIONAL ARRAYS Objectives ■ To give examples of representing data using two-dimensional arrays (§8.1). ■ To declare variables for two-dimensional arrays, create arrays, and access array elements in a two-dimensional array using row and col- umn indexes (§8.2). ■ To program common operations for two-dimensional arrays (display- ing arrays, summing all elements, finding the read more..

  • Page - 311

    288 Chapter 8 Multidimensional Arrays 8.1 Introduction Data in a table or a matrix can be represented using a two-dimensional array. The preceding chapter introduced how to use one-dimensional arrays to store linear collec- tions of elements. You can use a two-dimensional array to store a matrix or a table. For example, the following table that lists the distances between read more..

  • Page - 312

    8.2 Two-Dimensional Array Basics 289 or int matrix[][]; // This style is allowed, but not preferred You can create a two-dimensional array of 5-by-5 int values and assign it to matrix using this syntax: matrix = new int[5][5]; Two subscripts are used in a two-dimensional array, one for the row and the other for the column. As in a one-dimensional array, the index for read more..

  • Page - 313

    290 Chapter 8 Multidimensional Arrays For example, suppose x = new int[3][4], x[0], x[1], and x[2] are one-dimensional arrays and each contains four elements, as shown in Figure  8.2. x.length is 3, and x[0].length, x[1].length, and x[2].length are 4. FIGURE 8.2 A two-dimensional array is a one-dimensional array in which each element is another one-dimensional array. x read more..

  • Page - 314

    8.3 Processing Two-Dimensional Arrays 291 8.1 Declare an array reference variable for a two-dimensional array of int values, create a 4-by-5 int matrix, and assign it to the variable. 8.2 Can the rows in a two-dimensional array have different lengths? 8.3 What is the output of the following code? int[][] array = new int[5][6]; int[] x = {1, 2}; array[0] = x; read more..

  • Page - 315

    292 Chapter 8 Multidimensional Arrays 4. Summing all elements. Use a variable named total to store the sum. Initially total is 0. Add each element in the array to total using a loop like this: int total = 0; for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { total += matrix[row][column]; read more..

  • Page - 316

    8.4 Passing Two-Dimensional Arrays to Methods 293 int temp = matrix[i][j]; matrix[i][j] = matrix[i1][j1]; matrix[i1][j1] = temp; } } 8.5 Show the output of the following code: int[][] array = {{1, 2}, {3, 4}, {5, 6}}; for (int i = array.length - 1; i >= 0 ; i——) { for (int j = array[i].length - 1; j >= 0 ; j——) read more..

  • Page - 317

    294 Chapter 8 Multidimensional Arrays 23 return m; 24 } 25 26 public static int sum(int[][] m) { 27 int total = 0; 28 for (int row = 0; row < m.length; row++) { 29 for (int column = 0; column < m[row].length; column++) { 30 total += m[row][column]; 31 } 32 } 33 34 return total; 35 } 36 } return read more..

  • Page - 318

    8.5 Case Study: Grading a Multiple-Choice Test 295 The key is stored in a one-dimensional array: Students’ Answers to the Questions: 0 1 2 3 4 5 6 7 8 9 Student 0 A B A C C D E E A D Student 1 D B A B C A E E A D Student 2 E D D A C B E E read more..

  • Page - 319

    296 Chapter 8 Multidimensional Arrays The statement in lines 5–13 declares, creates, and initializes a two-dimensional array of characters and assigns the reference to answers of the char[][] type. The statement in line 16 declares, creates, and initializes an array of char values and assigns the reference to keys of the char[] type. Each row in the array answers read more..

  • Page - 320

    8.6 Case Study: Finding the Closest Pair 297 10 double[][] points = new double[numberOfPoints][2]; 11 System.out.print("Enter " + numberOfPoints + " points: "); 12 for (int i = 0; i < points.length; i++) { 13 points[i][0] = input.nextDouble(); 14 points[i][1] = input.nextDouble(); 15 } 16 17 // p1 and p2 are the read more..

  • Page - 321

    298 Chapter 8 Multidimensional Arrays Note that there might be more than one closest pair of points with the same minimum dis- tance. The program finds one such pair. You may modify the program to find all closest pairs in Programming Exercise 8.8. Tip It is cumbersome to enter all points from the keyboard. You may store the input in a file, say FindNearestPoints.txt, read more..

  • Page - 322

    8.7 Case Study: Sudoku 299 To find a solution for the puzzle, we must replace each 0 in the grid with an appropriate number from 1 to 9. For the solution to the puzzle in Figure 8.5, the grid should be as shown in Figure 8.6. Once a solution to a Sudoku puzzle is found, how do you verify that it is correct? Here are two approaches: ■ Check if every row has read more..

  • Page - 323

    300 Chapter 8 Multidimensional Arrays 28 for (int i = 0; i < 9 ; i++) 29 for (int j = 0; j < 9 ; j++) 30 if (grid[i][j] < 1 || grid[i][j] > 9 31 || !isValid(i, j, grid)) 32 return false; 33 return true; // The solution is valid 34 } 35 36 /** Check whether grid[i][j] is valid in the grid */ 37 public static read more..

  • Page - 324

    8.8 Multidimensional Arrays 301 With this observation, you can easily identify all the cells in the box. For instance, if grid[r][c] is the starting cell of a 3 * 3 box, the cells in the box can be traversed in a nested loop as follows: // Get all cells in a 3-by-3 box starting at grid[r][c] for (int row = r; row < r + 3 ; row++) for (int col = c; read more..

  • Page - 325

    302 Chapter 8 Multidimensional Arrays scores[0][1][0] refers to the multiple-choice score for the first student’s second exam, which is 9.0. scores[0][1][1] refers to the essay score for the first student’s second exam, which is 22.5. This is depicted in the following figure: Which student Which exam Multiple-choice or essay scores [i] [j] [k] 1 1 76.4 0.92 1 2 77.7 0.93 . read more..

  • Page - 326

    8.8 Multidimensional Arrays 303 Note that the days are numbered from 1 to 10 and the hours from 1 to 24 in the file. Because the array index starts from 0, data[0][0][0] stores the temperature in day 1 at hour 1 and data[9][23][1] stores the humidity in day 10 at hour 24. The program is given in Listing 8.5. LISTING 8.5 Weather.java 1 import read more..

  • Page - 327

    304 Chapter 8 Multidimensional Arrays doing so will be awkward. For convenience, we store the data in a file and use input redirec- tion to read the data from the file. The loop in lines 24–27 adds all temperatures for each hour in a day to dailyTemperatureTotal and all humidity for each hour to dailyHumidity- Total. The average daily temperature and humidity are read more..

  • Page - 328

    Programming Exercises 305 46 } 47 48 System.out.println("Your birthday is " + day); 49 } 50 } A three-dimensional array dates is created in Lines 8–28. This array stores five sets of numbers. Each set is a 4-by-4 two-dimensional array. The loop starting from line 33 displays the numbers in each set and prompts the user to answer read more..

  • Page - 329

    306 Chapter 8 Multidimensional Arrays Write a test program that reads a 3-by-4 matrix and displays the sum of each column. Here is a sample run: Enter a 3-by-4 matrix row by row: 1.5 2 3 4 5.5 6 7 8 9.5 1 3 1 Sum of the elements at column 0 is 16.5 Sum of the elements at column 1 is 9.0 Sum of the elements at column 2 is 13.0 Sum of the elements read more..

  • Page - 330

    Programming Exercises 307 In order to be added, the two matrices must have the same dimensions and the same or compatible types of elements. Let c be the resulting matrix. Each ele- ment cij is aij + bij. For example, for two 3 * 3 matrices a and b, c is £a11 a12 a13 a21 a22 a23 a31 a32 a33 ≥ + £b11 b12 b13 b21 b22 b23 b31 b32 b33 ≥ = £a11 + read more..

  • Page - 331

    308 Chapter 8 Multidimensional Arrays The formula for computing the distance between two points (x1, y1, z1) and (x2, y2, z2) is 2(x 2 - x1) 2 + (y2 - y1) 2 + (z2 - z1) 2. **8.8 (All closest pairs of points) Revise Listing 8.3, FindNearestPoints.java, to display all closest pairs of points with the same minimum distance. Here is a sample run: read more..

  • Page - 332

    Programming Exercises 309 *8.10 (Largest row and column) Write a program that randomly fills in 0s and 1s into a 4-by-4 matrix, prints the matrix, and finds the first row and column with the most 1s. Here is a sample run of the program: 0011 0011 1101 1010 The largest row index: 2 The largest column index: 2 **8.11 (Game: nine heads and tails) Nine coins are placed in read more..

  • Page - 333

    310 Chapter 8 Multidimensional Arrays (82,250 - 33,950) at 25%, (171,550 - 82,550) at 28%, (372,550 - 82,250) at 33%, and (400,000 - 372,950) at 36%. The six rates are the same for all filing statuses, which can be represented in the following array: double[] rates = {0.10, 0.15, 0.25, 0.28, 0.33, 0.35}; The brackets for each rate for all the filing statuses read more..

  • Page - 334

    Programming Exercises 311 *8.15 (Geometry: same line?) Programming Exercise 6.39 gives a method for testing whether three points are on the same line. Write the following method to test whether all the points in the array points are on the same line. public static boolean sameLine(double[][] points) Write a program that prompts the user to enter five points and read more..

  • Page - 335

    312 Chapter 8 Multidimensional Arrays If a bank’s total assets are under a certain limit, the bank is unsafe. The money it borrowed cannot be returned to the lender, and the lender cannot count the loan in its total assets. Consequently, the lender may also be unsafe, if its total assets are under the limit. Write a program to find all the unsafe banks. read more..

  • Page - 336

    Programming Exercises 313 Write a test program that prompts the user to enter the number of rows and col- umns of a two-dimensional array and then the values in the array and displays true if the array contains four consecutive numbers with the same value. Other- wise, display false. Here are some examples of the true cases: 0 1 0 3 1 6 1 0 1 read more..

  • Page - 337

    314 Chapter 8 Multidimensional Arrays *8.21 (Central city) Given a set of cities, the central city is the city that has the shortest total distance to all other cities. Write a program that prompts the user to enter the number of the cities and the locations of the cities (coordinates), and finds the central city and its total distance to all other cities. Drop a read more..

  • Page - 338

    Programming Exercises 315 *8.24 (Check Sudoku solution) Listing 8.4 checks whether a solution is valid by check- ing whether every number is valid in the board. Rewrite the program by checking whether every row, every column, and every small box has the numbers 1 to 9. *8.25 (Markov matrix) An n * n matrix is called a positive Markov matrix if each element is read more..

  • Page - 339

    316 Chapter 8 Multidimensional Arrays 8.28 (Strictly identical arrays) The two-dimensional arrays m1 and m2 are strictly identical if their corresponding elements are equal. Write a method that returns true if m1 and m2 are strictly identical, using the following header: public static boolean equals(int[][] m1, int[][] m2) Write a test program that prompts the user read more..

  • Page - 340

    Programming Exercises 317 *8.30 (Algebra: solve linear equations) Write a method that solves the following 2 * 2 system of linear equations: a00x + a01y = b0 a10x + a11y = b1 x = b0a11 - b1a01 a00a11 - a01a10 y = b1a00 - b0a10 a00a11 - a01a10 The method header is public static double[] linearEquation(double[][] a, double[] b) The method returns null if a00a11 - read more..

  • Page - 341

    318 Chapter 8 Multidimensional Arrays *8.34 (Geometry: rightmost lowest point) In computational geometry, often you need to find the rightmost lowest point in a set of points. Write the following method that returns the rightmost lowest point in a set of points. public static double[] getRightmostLowestPoint(double[][] points) Write a test program that prompts the read more..

  • Page - 342

    Programming Exercises 319 program that prompts the user to enter the number n and the array of characters, as shown in the sample output, and checks if the input array is a Latin square. The characters are the first n characters starting from A. Enter number n: 3 Enter 3 rows of letters separated by spaces: A F D Wrong input: the letters must be from A to C read more..

  • Page - 343

    This page intentionally left blank read more..

  • Page - 344

    OBJECTS AND CLASSES Objectives ■ To describe objects and classes, and use classes to model objects (§9.2). ■ To use UML graphical notation to describe classes and objects (§9.2). ■ To demonstrate how to define classes and create objects (§9.3). ■ To create objects using constructors (§9.4). ■ To access objects via object reference variables (§9.5). ■ To define a read more..

  • Page - 345

    322 Chapter 9 Objects and Classes 9.1 Introduction Object-oriented programming enables you to develop large-scale software and GUIs effectively. Having learned the material in the preceding chapters, you are able to solve many program- ming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and read more..

  • Page - 346

    9.2 Defining Classes for Objects 323 The Circle class is different from all of the other classes you have seen thus far. It does not have a main method and therefore cannot be run; it is merely a definition for circle objects. The class that contains the main method will be referred to in this book, for convenience, as the main class. The illustration of class read more..

  • Page - 347

    324 Chapter 9 Objects and Classes The method is denoted as methodName(parameterName: parameterType): returnType 9.3 Example: Defining Classes and Creating Objects Classes are definitions for objects and objects are created from classes. This section gives two examples of defining classes and uses the classes to create objects. Listing 9.1 is a program that defines the Circle class read more..

  • Page - 348

    9.3 Example: Defining Classes and Creating Objects 325 23 } 24 } 25 26 // Define the circle class with two constructors 27 class SimpleCircle { 28 double radius; 29 30 /** Construct a circle with radius 1 */ 31 SimpleCircle() { 32 radius = 1; 33 } 34 35 /** Construct a circle with a specified radius */ 36 SimpleCircle(double newRadius) { 37 read more..

  • Page - 349

    326 Chapter 9 Objects and Classes The main class contains the main method (line 3) that creates three objects. As in creating an array, the new operator is used to create an object from the constructor: new SimpleCircle() creates an object with radius 1 (line 5), new SimpleCircle(25) creates an object with radius 25 (line 10), and new SimpleCircle(125) creates read more..

  • Page - 350

    9.3 Example: Defining Classes and Creating Objects 327 42 /** Return the perimeter of this circle */ 43 double getPerimeter() { 44 return 2 * radius * Math.PI; 45 } 46 47 /** Set a new radius for this circle */ 48 void setRadius(double newRadius) { 49 radius = newRadius; 50 } 51 } Since the combined class has a main method, it can be read more..

  • Page - 351

    328 Chapter 9 Objects and Classes 14 on = false; 15 } 16 17 public void setChannel(int newChannel) { 18 if (on && newChannel >= 1 && newChannel <= 120 ) 19 channel = newChannel; 20 } 21 22 public void setVolume(int newVolumeLevel) { 23 if (on && newVolumeLevel >= 1 && newVolumeLevel <= 7) 24 read more..

  • Page - 352

    9.4 Constructing Objects Using Constructors 329 The program creates two objects in lines 3 and 8 and invokes the methods on the objects to perform actions for setting channels and volume levels and for increasing channels and vol- umes. The program displays the state of the objects in lines 14–17. The methods are invoked using syntax such as tv1.turnOn() (line 4). The read more..

  • Page - 353

    330 Chapter 9 Objects and Classes 9.5 Accessing Objects via Reference Variables An object’s data and methods can be accessed through the dot (.) operator via the object’s reference variable. Newly created objects are allocated in the memory. They can be accessed via reference variables. 9.5.1 Reference Variables and Reference Types Objects are accessed via the object’s reference read more..

  • Page - 354

    9.5 Accessing Objects via Reference Variables 331 For example, myCircle.radius references the radius in myCircle, and myCircle .getArea() invokes the getArea method on myCircle. Methods are invoked as operations on objects. The data field radius is referred to as an instance variable, because it is dependent on a specific instance. For the same reason, the method getArea read more..

  • Page - 355

    332 Chapter 9 Objects and Classes System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); } } The following code has a compile error, because the local variables x and y are not initialized: class Test { public static void main(String[] read more..

  • Page - 356

    9.5 Accessing Objects via Reference Variables 333 for primitive variables. As shown in Figure 9.9, the assignment statement c1 = c2 copies the reference of c2 into c1 for reference variables. After the assignment, variables c1 and c2 refer to the same object. FIGURE 9.9 Reference variable c2 is copied to variable c1. Object type assignment c1 = c2 c1 After: c2 Before: c1 c2 read more..

  • Page - 357

    334 Chapter 9 Objects and Classes 9.12 What is wrong in the following code? 1 class Test { 2 public static void main(String[] args) { 3 A a = new A(); 4 a.print(); 5 } 6 } 7 8 class A { 9 String s; 10 11 A(String newS) { 12 s = newS; 13 } 14 15 public void print() { 16 read more..

  • Page - 358

    9.6 Using Classes from the Java Library 335 You can use the no-arg constructor in the Date class to create an instance for the cur- rent date and time, the getTime() method to return the elapsed time since January 1, 1970, GMT, and the toString() method to return the date and time as a string. For example, the following code java.util.Date date = new read more..

  • Page - 359

    336 Chapter 9 Objects and Classes The code generates the same sequence of random int values: From random1: 734 660 210 581 128 202 549 564 459 961 From random2: 734 660 210 581 128 202 549 564 459 961 Note The ability to generate the same sequence of random values is useful in software testing and many other applications. In software testing, often you need to read more..

  • Page - 360

    9.7 Static Variables, Constants, and Methods 337 This program creates two objects of the Point2D class (lines 15–16). The toString() method returns a string that describes the object (lines 17–18). Invoking p1.distance(p2) returns the distance between the two points (line 20). 9.14 How do you create a Date for the current time? How do you display the current time? 9.15 How read more..

  • Page - 361

    338 Chapter 9 Objects and Classes Constants in a class are shared by all objects of the class. Thus, constants should be declared as final static. For example, the constant PI in the Math class is defined as: final static double PI = 3.14159265358979323846; The new circle class, named CircleWithStaticMembers, is defined in Listing 9.6: LISTING 9.6 CircleWithStaticMembers.java read more..

  • Page - 362

    9.7 Static Variables, Constants, and Methods 339 Instance methods (e.g., getArea()) and instance data (e.g., radius) belong to instances and can be used only after the instances are created. They are accessed via a reference variable. Static methods (e.g., getNumberOfObjects()) and static data (e.g., numberOfObjects) can be accessed from a reference variable or from their class name. read more..

  • Page - 363

    340 Chapter 9 Objects and Classes The main method creates two circles, c1 and c2 (lines 9, 18). The instance variable radius in c1 is modified to become 9 (line 21). This change does not affect the instance variable radius in c2, since these two instance variables are independent. The static vari- able numberOfObjects becomes 1 after c1 is created (line read more..

  • Page - 364

    9.7 Static Variables, Constants, and Methods 341 Note that if you replace the preceding code with the following new code, the program would be fine, because the instance data field i and method m1 are now accessed from an object a (lines 7–8): 1 public class A { 2 int i = 5; 3 static int k = 2; 4 5 public static void main(String[] args) { read more..

  • Page - 365

    342 Chapter 9 Objects and Classes 9.18 Add the static keyword in the place of ? if appropriate. public class Test { int count; public ? void main(String[] args) { ... } public ? int getCount() { return count; } public ? int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) result *= i; return read more..

  • Page - 366

    9.8 Visibility Modifiers 343 Note Packages can be used to organize classes. To do so, you need to add the following line as the first noncomment and nonblank statement in the program: package packageName; If a class is defined without the package statement, it is said to be placed in the default package. Java recommends that you place classes into packages rather than read more..

  • Page - 367

    344 Chapter 9 Objects and Classes Caution The private modifier applies only to the members of a class. The public modifier can apply to a class or members of a class. Using the modifiers public and private on local variables would cause a compile error. Note In most cases, the constructor should be public. However, if you want to prohibit the user from creating an read more..

  • Page - 368

    9.9 Data Field Encapsulation 345 A private data field cannot be accessed by an object from outside the class that defines the private field. However, a client often needs to retrieve and modify a data field. To make a private data field accessible, provide a getter method to return its value. To enable a private data field to be updated, provide a setter method read more..

  • Page - 369

    346 Chapter 9 Objects and Classes 17 } 18 19 /** Return radius */ 20 public double getRadius() { 21 return radius; 22 } 23 24 /** Set a new radius */ 25 public void setRadius(double newRadius) { 26 radius = (newRadius >= 0 ) ? newRadius : 0; 27 } 28 29 /** Return numberOfObjects */ 30 public static int getNumberOfObjects() { 31 return read more..

  • Page - 370

    9.10 Passing Objects to Methods 347 Suppose you combined TestCircleWithPrivateDataFields and Circle into one class by moving the main method in TestCircleWithPrivateDataFields into Circle. Could you use myCircle.radius in the main method? See Checkpoint Question 9.22 for the answer. Design Guide To prevent data from being tampered with and to make the class easy to read more..

  • Page - 371

    348 Chapter 9 Objects and Classes LISTING 9.10 TestPassObject.java 1 public class TestPassObject { 2 /** Main method */ 3 public static void main(String[] args) { 4 // Create a Circle object with radius 1 5 CircleWithPrivateDataFields myCircle = 6 new CircleWithPrivateDataFields(1); 7 8 // Print areas for radius 1, 2, 3, 4, and read more..

  • Page - 372

    9.10 Passing Objects to Methods 349 9.23 Describe the difference between passing a parameter of a primitive type and passing a parameter of a reference type. Show the output of the following programs: ✓ Point ✓Check FIGURE 9.18 The value of n is passed to times, and the reference to myCircle is passed to c in the printAreas method. Activation record for the main read more..

  • Page - 373

    350 Chapter 9 Objects and Classes public static void swap2(Circle x, Circle y) { double temp = x.radius; x.radius = y.radius; y.radius = temp; } } class Circle { double radius; Circle(double newRadius) { radius = newRadius; } } 9.25 Show the output of the following code: public class Test { public static void main(String[] args) { read more..

  • Page - 374

    9.11 Array of Objects 351 9.26 What is the output of the following programs? import java.util.Date; public class Test { public static void main(String[] args) { Date date = null; m1(date); System.out.println(date); } public static void m1(Date date) { date = new Date(); } } (a) import java.util.Date; public class Test { public read more..

  • Page - 375

    352 Chapter 9 Objects and Classes Listing 9.11 gives an example that demonstrates how to use an array of objects. The pro- gram summarizes the areas of an array of circles. The program creates circleArray, an array composed of five Circle objects; it then initializes circle radii with random values and displays the total area of the circles in the array. LISTING 9.11 read more..

  • Page - 376

    9.12 Immutable Objects and Classes 353 43 44 /** Add circle areas */ 45 public static double sum(CircleWithPrivateDataFields[] circleArray) { 46 // Initialize sum 47 double sum = 0; 48 49 // Add areas to sum 50 for (int i = 0; i < circleArray.length; i++) 51 sum += circleArray[i].getArea(); 52 53 return sum; 54 } 55 } pass array of objects Radius read more..

  • Page - 377

    354 Chapter 9 Objects and Classes If a class is immutable, then all its data fields must be private and it cannot contain public setter methods for any data fields. A class with all private data fields and no mutators is not necessarily immutable. For example, the following Student class has all private data fields and no setter methods, but it is not an read more..

  • Page - 378

    9.13 The Scope of Variables 355 return values; } } 9.13 The Scope of Variables The scope of instance and static variables is the entire class, regardless of where the variables are declared. Section 6.9 discussed local v ariables and their scope rules. Local variables are declared and used inside a method locally. This section discusses the scope rules of all the variables read more..

  • Page - 379

    356 Chapter 9 Objects and Classes Tip To avoid confusion and mistakes, do not use the names of instance or static variables as local variable names, except for method parameters. 9.31 What is the output of the following program? public class Test { private static int i = 0; private static int j = 0; public static void main(String[] args) { int i = 2; int k = read more..

  • Page - 380

    The this keyword gives us a way to reference the object that invokes an instance method. To invoke f1.setI(10), this.i = i is executed, which assigns the value of parameter i to the data field i of this calling object f1. The keyword this refers to the object that invokes the instance method setI, as shown in Figure 9.21b. The line F.k = k means that the read more..

  • Page - 381

    358 Chapter 9 Objects and Classes 9.32 Describe the role of the this keyword. 9.33 What is wrong in the following code? 1 public class C { 2 private int p; 3 4 public C() { 5 System.out.println("C's no-arg constructor invoked"); 6 this(0); 7 } 8 9 public C(int p) { 10 p = p; 11 } 12 13 public void read more..

  • Page - 382

    CHAPTER SUMMARY 1. A class is a template for objects. It defines the properties of objects and provides constructors for creating objects and methods for manipulating them. 2. A class is also a data type. You can use it to declare object reference variables. An object reference variable that appears to hold an object actually contains a reference to that object. Strictly read more..

  • Page - 383

    360 Chapter 9 Objects and Classes PROGRAMMING EXERCISES Pedagogical Note The exercises in Chapters 9–13 help you achieve three objectives: ■ Design classes and draw UML class diagrams. ■ Implement classes from the UML. ■ Use classes to develop applications. Students can download solutions for the UML diagrams for the even-numbered exer- cises from the Companion Website, and read more..

  • Page - 384

    *9.5 (Use the GregorianCalendar class) Java API has the GregorianCalendar class in the java.util package, which you can use to obtain the year, month, and day of a date. The no-arg constructor constructs an instance for the current date, and the meth- ods get(GregorianCalendar.YEAR), get(GregorianCalendar.MONTH), and get(GregorianCalendar.DAY_OF_MONTH) return the year, month, and read more..

  • Page - 385

    362 Chapter 9 Objects and Classes 9.8 (The Fan class) Design a class named Fan to represent a fan. The class contains: ■ Three constants named SLOW, MEDIUM, and FAST with the values 1, 2, and 3 to denote the fan speed. ■ A private int data field named speed that specifies the speed of the fan (the default is SLOW). ■ A private boolean data read more..

  • Page - 386

    *9.10 (Algebra: quadratic equations) Design a class named QuadraticEquation for a quadratic equation ax2 + bx + x = 0. The class contains: ■ Private data fields a, b, and c that represent three coefficients. ■ A constructor for the arguments for a, b, and c. ■ Three getter methods for a, b, and c. ■ A method named getDiscriminant() that returns the read more..

  • Page - 387

    364 Chapter 9 Objects and Classes Enter the number of rows and columns in the array: 3 4 Enter the array: 23.5 35 2 10 4.5 3 45 3.5 35 44 5.5 9.6 The location of the largest element is 45 at (1, 2) The return value is an instance of Location. Write a test program that prompts the user to enter a two-dimensional array and displays the location of the largest read more..

  • Page - 388

    OBJECT-ORIENTED THINKING Objectives ■ To apply class abstraction to develop software (§10.2). ■ To explore the differences between the procedural paradigm and object-oriented paradigm (§10.3). ■ To discover the relationships between classes (§10.4). ■ To design programs using the object-oriented paradigm (§§10.5–10.6). ■ To create objects for primitive values using the wrapper read more..

  • Page - 389

    366 Chapter 10 Object-Oriented Thinking 10.1 Introduction The focus of this chapter is on class design and explores the differences between procedural programming and object-oriented programming. The preceding chapter introduced objects and classes. You learned how to define classes, create objects, and use objects from several classes in the Java API (e.g., Circle, Date, Random, and read more..

  • Page - 390

    10.2 Class Abstraction and Encapsulation 367 computing the monthly payment and total payment are its methods. When you buy a car, a loan object is created by instantiating the class with your loan interest rate, loan amount, and loan period. You can then use the methods to find the monthly payment and total payment of your loan. As a user of the Loan class, you read more..

  • Page - 391

    368 Chapter 10 Object-Oriented Thinking 6 // Create a Scanner 7 Scanner input = new Scanner(System.in); 8 9 // Enter annual interest rate 10 System.out.print( 11 "Enter annual interest rate, for example, 8.25: "); 12 double annualInterestRate = input.nextDouble(); 13 14 // Enter number of years 15 System.out.print("Enter number of years as an read more..

  • Page - 392

    10.2 Class Abstraction and Encapsulation 369 13 number of years, and loan amount 14 */ 15 public Loan(double annualInterestRate, int numberOfYears, 16 double loanAmount) { 17 this.annualInterestRate = annualInterestRate; 18 this.numberOfYears = numberOfYears; 19 this.loanAmount = loanAmount; 20 loanDate = new java.util.Date(); 21 } 22 23 /** Return annualInterestRate */ 24 read more..

  • Page - 393

    370 Chapter 10 Object-Oriented Thinking From a class developer’s perspective, a class is designed for use by many different customers. In order to be useful in a wide range of applications, a class should provide a variety of ways for customization through constructors, properties, and methods. The Loan class contains two constructors, four getter methods, three setter methods, read more..

  • Page - 394

    10.3 Thinking in Objects 371 Assume that the BMI class is available. Listing 10.3 gives a test program that uses this class. LISTING 10.3 UseBMIClass.java 1 public class UseBMIClass { 2 public static void main(String[] args) { 3 BMI bmi1 = new BMI("Kim Yang" , 18, 145, 70); 4 System.out.println("The BMI for " + bmi1.getName() + " is read more..

  • Page - 395

    372 Chapter 10 Object-Oriented Thinking 11 this.age = age; 12 this.weight = weight; 13 this.height = height; 14 } 15 16 public BMI(String name, double weight, double height) { 17 this(name, 20, weight, height); 18 } 19 20 public double getBMI() { 21 double bmi = weight * KILOGRAMS_PER_POUND / 22 ((height * METERS_PER_INCH) * (height * read more..

  • Page - 396

    10.4 Class Relationships 373 the operations that pertain to them in an object. This approach solves many of the problems inherent in procedural programming. The object-oriented programming approach organizes programs in a way that mirrors the real world, in which all objects are associated with both attributes and activities. Using objects improves software reusability and makes read more..

  • Page - 397

    374 Chapter 10 Object-Oriented Thinking relation “a student takes a course” is implemented using the addCourse method in the Stu- dent class and the addStuent method in the Course class. The relation “a faculty teaches a course” is implemented using the addCourse method in the Faculty class and the set- Faculty method in the Course class. The Student read more..

  • Page - 398

    10.4 Class Relationships 375 An aggregation relationship is usually represented as a data field in the aggregating class. For example, the relationships in Figure  10.6 may be implemented using the classes in Figure 10.7. The relation “a student has a name” and “a student has an address” are imple- mented in the data field name and address in the Student class. FIGURE read more..

  • Page - 399

    376 Chapter 10 Object-Oriented Thinking 10.5 Case Study: Designing the Course Class This section designs a class for modeling courses. This book’s philosophy is teaching by example and learning by doing. The book provides a wide variety of examples to demonstrate object-oriented programming. This section and the next offer additional examples on designing classes. Suppose you need read more..

  • Page - 400

    10.5 Case Study: Designing the Course Class 377 The Course class is implemented in Listing 10.6. It uses an array to store the students in the course. For simplicity, assume that the maximum course enrollment is 100. The array is cre- ated using new String[100] in line 3. The addStudent method (line 10) adds a student to the array. Whenever a new student is added read more..

  • Page - 401

    378 Chapter 10 Object-Oriented Thinking 10.6 Case Study: Designing a Class for Stacks This section designs a class for modeling stacks. Recall that a stack is a data structure that holds data in a last-in, first-out fashion, as shown in Figure 10.11. Key Point stack FIGURE 10.12 The StackOfIntegers class encapsulates the stack storage and provides the operations for read more..

  • Page - 402

    10.6 Case Study: Designing a Class for Stacks 379 4 5 for (int i = 0; i < 10; i++) 6 stack.push(i); 7 8 while (!stack.empty()) 9 System.out.print(stack.pop() + " "); 10 } 11 } push to stack pop from stack 9 8 7 6 5 4 3 2 1 0 FIGURE 10.13 The StackOfIntegers class encapsulates the stack storage and provides the read more..

  • Page - 403

    380 Chapter 10 Object-Oriented Thinking 16 /** Push a new integer to the top of the stack */ 17 public void push(int value) { 18 if (size >= elements.length) { 19 int[] temp = new int[elements.length * 2]; 20 System.arraycopy(elements, 0, temp, 0, elements.length); 21 elements = temp; 22 } 23 24 elements[size++] = value; read more..

  • Page - 404

    10.7 Processing Primitive Data Type Values as Objects 381 You can construct a wrapper object either from a primitive data type value or from a string representing the numeric value—for example, new Double(5.0), new Double("5.0"), new Integer(5), and new Integer("5"). The wrapper classes do not have no-arg constructors. The instances of all wrapper classes are read more..

  • Page - 405

    382 Chapter 10 Object-Oriented Thinking and returns 1, 0, or -1, if this number is greater than, equal to, or less than the other number. For example, new Double(12.4).compareTo(new Double(12.3)) returns 1; new Double(12.3).compareTo(new Double(12.3)) returns 0; new Double(12.3).compareTo(new Double(12.51)) returns -1; The numeric wrapper classes have a useful static method, valueOf (String s). read more..

  • Page - 406

    10.8 Automatic Conversion between Primitive Types and Wrapper Class Types 383 10.7 Describe primitive-type wrapper classes. 10.8 Can each of the following statements be compiled? a. Integer i = new Integer("23"); b. Integer i = new Integer( 23); c. Integer i = Integer.valueOf( "23"); d. Integer i = Integer.parseInt( "23", 8); e. Double d = new Double(); f. read more..

  • Page - 407

    384 Chapter 10 Object-Oriented Thinking For instance, the following statement in (a) can be simplified as in (b) due to autoboxing. Integer intObject = new Integer (2); Integer intObject = 2; (a) Equivalent autoboxing (b) Consider the following example: 1 Integer[] intArray = {1, 2, 3}; 2 System.out.println(intArray[0] + intArray[1] + intArray[2]); In line 1, the primitive values read more..

  • Page - 408

    10.9 The BigInteger and BigDecimal Classes 385 The output is 18446744073709551614. There is no limit to the precision of a BigDecimal object. The divide method may throw an ArithmeticException if the result cannot be terminated. However, you can use the overloaded divide(BigDecimal d, int scale, int roundingMode) method to spec- ify a scale and a rounding mode to avoid read more..

  • Page - 409

    386 Chapter 10 Object-Oriented Thinking 10.10 The String Class A String object is immutable: Its content cannot be changed once the string is created. Strings were introduced in Section  4.4. You know strings are objects. You can invoke the charAt(index) method to obtain a character at the specified index from a string, the length() method to return the size of a read more..

  • Page - 410

    10.10 The String Class 387 Because strings are immutable and are ubiquitous in programming, the JVM uses a unique instance for string literals with the same character sequence in order to improve efficiency and save memory. Such an instance is called an interned string. For example, the following statements: interned string FIGURE 10.15 Strings are immutable; once created, their read more..

  • Page - 411

    388 Chapter 10 Object-Oriented Thinking Once a string is created, its contents cannot be changed. The methods replace, replaceFirst, and replaceAll return a new string derived from the original string (without changing the original string!). Several versions of the replace methods are pro- vided to replace a character or a substring in the string with a new character or a read more..

  • Page - 412

    The replaceAll, replaceFirst, and split methods can be used with a regular expression. For example, the following statement returns a new string that replaces $, +, or # in a+b$#c with the string NNN. String s = "a+b$#c".replaceAll("[$+#]", "NNN"); System.out.println(s); Here the regular expression [$+#] specifies a pattern that matches $, +, or #. So, read more..

  • Page - 413

    390 Chapter 10 Object-Oriented Thinking number into a string is to use the overloaded static valueOf method. This method can also be used to convert a character or an array of characters into a string, as shown in Figure 10.17. overloaded valueOf FIGURE 10.17 The String class contains the static methods for creating strings from prim- itive type values. java.lang.String read more..

  • Page - 414

    c. s1 == s4 d. s1.equals(s3) e. s1.equals(s4) f. "Welcome to Java".replace("Java", "HTML") g. s1.replace('o', 'T') h. s1.replaceAll("o", "T") i. s1.replaceFirst( "o", "T") j. s1.toCharArray() 10.16 To create the string Welcome to Java, you may use a statement like this: String s = "Welcome to Java"; or: String s = new read more..

  • Page - 415

    392 Chapter 10 Object-Oriented Thinking 4 public void Test(String s) { 5 text = s; 6 } 7 8 public static void main(String[] args) { 9 Test test = new Test("ABC"); 10 System.out.println(test); 11 } 12 } 10.24 Show the output of the following code. public class Test { public static void main(String[] read more..

  • Page - 416

    10.11 The StringBuilder and StringBuffer Classes 393 StringBuffer. Concurrent programming will be introduced in Chapter 30. Using String- Builder is more efficient if it is accessed by just a single task, because no synchronization is needed in this case. The constructors and methods in StringBuffer and StringBuilder are almost the same. This section covers StringBuilder. You can read more..

  • Page - 417

    394 Chapter 10 Object-Oriented Thinking The StringBuilder class provides several overloaded methods to append boolean, char, char[], double, float, int, long, and String into a string builder. For example, the following code appends strings and characters into stringBuilder to form a new string, Welcome to Java. StringBuilder stringBuilder = new StringBuilder(); read more..

  • Page - 418

    10.11.2 The toString, capacity, length, setLength, and charAt Methods The StringBuilder class provides the additional methods for manipulating a string builder and obtaining its properties, as shown in Figure 10.20. FIGURE 10.20 The StringBuilder class contains the methods for modifying string builders. java.lang.StringBuilder +toString(): String +capacity(): int +charAt(index: int): char +length(): read more..

  • Page - 419

    396 Chapter 10 Object-Oriented Thinking 10.11.3 Case Study: Ignoring Nonalphanumeric Characters When Checking Palindromes Listing 5.14, Palindrome.java, considered all the characters in a string to check whether it is a palindrome. Write a new program that ignores nonalphanumeric characters in checking whether a string is a palindrome. Here are the steps to solve the problem: 1. Filter read more..

  • Page - 420

    40 } 41 42 // Return a new filtered string 43 return stringBuilder.toString(); 44 } 45 46 /** Create a new string by reversing a specified string */ 47 public static String reverse(String s) { 48 StringBuilder stringBuilder = new StringBuilder(s); 49 stringBuilder.reverse(); // Invoke reverse in StringBuilder 50 return stringBuilder.toString(); 51 } 52 read more..

  • Page - 421

    398 Chapter 10 Object-Oriented Thinking c. s1.insert( 2, "is fun"); d. s1.insert( 1, s2); e. s1.charAt( 2); f. s1.length(); g. s1.deleteCharAt( 3); h. s1.delete( 1, 3); i. s1.reverse(); j. s1.replace( 1, 3, "Computer"); k. s1.substring( 1, 3); l. s1.substring( 2); 10.32 Show the output of the following program: public class Test { public static void main(String[] args) { read more..

  • Page - 422

    Programming Exercises 399 3. Java can automatically convert a primitive type value to its corresponding wrapper object in the context and vice versa. 4. The BigInteger class is useful for computing and processing integers of any size. The BigDecimal class can be used to compute and process floating-point numbers with any arbitrary precision. 5. A String object is immutable; read more..

  • Page - 423

    400 Chapter 10 Object-Oriented Thinking 10.2 (The BMI class) Add the following new constructor in the BMI class: /** Construct a BMI with the specified name, age, weight, * feet, and inches */ public BMI(String name, int age, double weight, double feet, double inches) 10.3 (The MyInteger class) Design a class named MyInteger. The class contains: ■ An int read more..

  • Page - 424

    Programming Exercises 401 **10.7 (Game: ATM machine) Use the Account class created in Programming Exer- cise 9.7 to simulate an ATM machine. Create ten accounts in an array with id 0, 1, . . . , 9, and initial balance $100. The system prompts the user to enter an id. If the id is entered incorrectly, ask the user to enter a correct id. Once an id is read more..

  • Page - 425

    402 Chapter 10 Object-Oriented Thinking ***10.8 (Financial: the Tax class) Programming Exercise 8.12 writes a program for computing taxes using arrays. Design a class named Tax to contain the follow- ing instance data fields: ■ int filingStatus: One of the four tax-filing statuses: 0—single filer, 1— married filing jointly or qualifying widow(er), 2—married filing separately, read more..

  • Page - 426

    Programming Exercises 403 ■ The method dequeue() that removes and returns the element from the queue. ■ The method empty() that returns true if the queue is empty. ■ The method getSize() that returns the size of the queue. Draw an UML diagram for the class. Implement the class with the initial array size set to 8. The array size will be doubled once read more..

  • Page - 427

    404 Chapter 10 Object-Oriented Thinking ■ A method contains(Triangle2D t) that returns true if the specified triangle is inside this triangle (see Figure 10.22b). ■ A method overlaps(Triangle2D t) that returns true if the specified triangle overlaps with this triangle (see Figure 10.22c). FIGURE 10.22 (a) A point is inside the triangle. (b) A triangle is inside read more..

  • Page - 428

    Programming Exercises 405 ■ A method getArea() that returns the area of the rectangle. ■ A method getPerimeter() that returns the perimeter of the rectangle. ■ A method contains(double x, double y) that returns true if the specified point (x, y) is inside this rectangle (see Figure 10.24a). ■ A method contains(MyRectangle2D r) that returns true if the read more..

  • Page - 429

    406 Chapter 10 Object-Oriented Thinking The Rectangle2D class is defined in Programming Exercise 10.13. Write a test program that prompts the user to enter five points and displays the bounding rectangle’s center, width, and height. Here is a sample run: Enter five points: 1.0 2.5 3 4 5 6 7 8 9 10 The bounding rectangle's center (5.0, 6.25), width 8.0, height read more..

  • Page - 430

    Programming Exercises 407 **10.23 (Implement the String class) The String class is provided in the Java library. Provide your own implementation for the following methods (name the new class MyString2): public MyString2(String s); public int compare(String s); public MyString2 substring(int begin); public MyString2 toUpperCase(); public char[] toChars(); public static MyString2 read more..

  • Page - 431

    408 Chapter 10 Object-Oriented Thinking **10.28 (Implement the StringBuilder class) The StringBuilder class is provided in the Java library. Provide your own implementation for the following methods (name the new class MyStringBuilder2): public MyStringBuilder2(); public MyStringBuilder2(char[] chars); public MyStringBuilder2(String s); public MyStringBuilder2 insert(int offset, MyStringBuilder2 read more..

  • Page - 432

    INHERITANCE AND  POLYMORPHISM Objectives ■ To define a subclass from a superclass through inheritance (§11.2). ■ To invoke the superclass’s constructors and methods using the super keyword (§11.3). ■ To override instance methods in the subclass (§11.4). ■ To distinguish differences between overriding and overloading (§11.5). ■ To explore the toString() method in the Object read more..

  • Page - 433

    410 Chapter 11 Inheritance and Polymorphism 11.1 Introduction Object-oriented programming allows you to define new classes from existing classes. This is called inheritance. As discussed earlier in the book, the procedural paradigm focuses on designing methods and the object-oriented paradigm couples data and methods together into objects. Software design using the object-oriented paradigm read more..

  • Page - 434

    11.2 Superclasses and Subclasses 411 SimpleGeometricObject, CircleFromSimpleGeometricObject, and Rec- tangleFromSimpleGeometricObject in this chapter. For simplicity, we will still refer to them in the text as GeometricObject, Circle, and Rectangle classes. The best way to avoid naming conflicts is to place these classes in different packages. However, for simplicity and consistency, all read more..

  • Page - 435

    412 Chapter 11 Inheritance and Polymorphism 10 11 /** Construct a geometric object with the specified color 12 * and filled value */ 13 public SimpleGeometricObject(String color, boolean filled) { 14 dateCreated = new java.util.Date(); 15 this.color = color; 16 this.filled = filled; 17 } 18 19 /** Return color */ 20 public String getColor() { 21 return color; 22 } read more..

  • Page - 436

    11.2 Superclasses and Subclasses 413 17 } 18 19 /** Return radius */ 20 public double getRadius() { 21 return radius; 22 } 23 24 /** Set a new radius */ 25 public void setRadius(double radius) { 26 this.radius = radius; 27 } 28 29 /** Return area */ 30 public double getArea() { 31 return radius * radius * Math.PI; 32 } 33 34 /** Return read more..

  • Page - 437

    414 Chapter 11 Inheritance and Polymorphism This is wrong, because the private data fields color and filled in the GeometricObject class cannot be accessed in any class other than in the GeometricObject class itself. The only way to read and modify color and filled is through their getter and setter methods. The Rectangle class (Listing 11.3) extends the GeometricObject read more..

  • Page - 438

    11.2 Superclasses and Subclasses 415 42 43 /** Return area */ 44 public double getArea() { 45 return width * height; 46 } 47 48 /** Return perimeter */ 49 public double getPerimeter() { 50 return 2 * (width + height); 51 } 52 } The code in Listing 11.4 creates objects of Circle and Rectangle and invokes the methods on these objects. The toString() method read more..

  • Page - 439

    416 Chapter 11 Inheritance and Polymorphism ■ Not all is-a relationships should be modeled using inheritance. For example, a square is a rectangle, but you should not extend a Square class from a Rectangle class, because the width and height properties are not appropriate for a square. Instead, you should define a Square class to extend the GeometricObject class read more..

  • Page - 440

    11.3 Using the super Keyword 417 super(color, filled); this.radius = radius; } Caution You must use the keyword super to call the superclass constructor, and the call must be the first statement in the constructor. Invoking a superclass constructor’s name in a subclass causes a syntax error. 11.3.2 Constructor Chaining A constructor may invoke an overloaded constructor or its read more..

  • Page - 441

    418 Chapter 11 Inheritance and Polymorphism 23 public Person() { 24 System.out.println("(1) Performs Person's tasks"); 25 } 26 } (1) Performs Person's tasks (2) Invoke Employee's overloaded constructor (3) Performs Employee's tasks (4) Performs Faculty's tasks The program produces the preceding output. Why? Let us discuss the reason. In line 3, new Faculty() read more..

  • Page - 442

    11.4 Overriding Methods 419 You could rewrite the printCircle() method in the Circle class as follows: public void printCircle() { System.out.println("The circle is created " + super.getDateCreated() + " and the radius is " + radius); } It is not necessary to put super before getDateCreated() in this case, however, because getDateCreated is a method in the read more..

  • Page - 443

    420 Chapter 11 Inheritance and Polymorphism The toString() method is defined in the GeometricObject class and modified in the Circle class. Both methods can be used in the Circle class. To invoke the toString method defined in the GeometricObject class from the Circle class, use super.toString() (line 7). Can a subclass of Circle access the toString method defined read more..

  • Page - 444

    11.5 Overriding vs. Overloading 421 When you run the Test class in (a), both a.p(10) and a.p(10.0) invoke the p(double i) method defined in class A to display 10.0. When you run the Test class in (b), a.p(10) invokes the p(int i) method defined in class A to display 10, and a.p(10.0) invokes the p(double i) method defined in class B to display 20.0. read more..

  • Page - 445

    422 Chapter 11 Inheritance and Polymorphism 26 public double getArea() { 27 return getArea() * length; 28 } 29 } 11.12 Explain the difference between method overloading and method overriding. 11.13 If a method in a subclass has the same signature as a method in its superclass with the same return type, is the method overridden or overloaded? 11.14 If a method in read more..

  • Page - 446

    11.7 Polymorphism 423 Note You can also pass an object to invoke System.out.println(object) or System.out.print(object). This is equivalent to invoking System.out .println(object.toString()) or System.out.print(object. toString()). Thus, you could replace System.out.println(loan .toString()) with System.out.println(loan). 11.7 Polymorphism Polymorphism means that a variable of a supertype can refer to a read more..

  • Page - 447

    424 Chapter 11 Inheritance and Polymorphism 11.8 Dynamic Binding A method can be implemented in several classes along the inheritance chain. The JVM decides which method is invoked at runtime. A method can be defined in a superclass and overridden in its subclass. For example, the toString() method is defined in the Object class and overridden in GeometricObject. Consider the read more..

  • Page - 448

    11.8 Dynamic Binding 425 20 return "Student" ; 21 } 22 } 23 24 class Person extends Object { 25 @Override 26 public String toString() { 27 return "Person" ; 28 } 29 } override toString() Student Student Person java.lang.Object@130c19b Method m (line 9) takes a parameter of the Object type. You can invoke m with any object read more..

  • Page - 449

    426 Chapter 11 Inheritance and Polymorphism 13 System.out.print(o + " "); 14 System.out.println(); 15 } 16 } 11.21 Show the output of the following code: public class Test { public static void main(String[] args) { new Person().printPerson(); new Student().printPerson(); } } class Student extends Person { @Override public read more..

  • Page - 450

    class A { int i = 7; public A() { setI(20); System.out.println("i from A is " + i); } public void setI(int i) { this.i = 2 * i; } } class B extends A { public B() { System.out.println("i from B is " + i); } public void setI(int i) { this.i = 3 * i; } } 11.9 Casting Objects and the read more..

  • Page - 451

    428 Chapter 11 Inheritance and Polymorphism casting must be used to confirm your intention to the compiler with the (SubclassName) cast notation. For the casting to be successful, you must make sure that the object to be cast is an instance of the subclass. If the superclass object is not an instance of the subclass, a runtime ClassCastException occurs. For example, if read more..

  • Page - 452

    13 /** A method for displaying an object */ 14 public static void displayObject(Object object) { 15 if (object instanceof CircleFromSimpleGeometricObject) { 16 System.out.println("The circle area is " + 17 ((CircleFromSimpleGeometricObject)object).getArea()); 18 System.out.println("The circle diameter is " + 19 read more..

  • Page - 453

    430 Chapter 11 Inheritance and Polymorphism 11.24 Indicate true or false for the following statements: ■ You can always successfully cast an instance of a subclass to a superclass. ■ You can always successfully cast an instance of a superclass to a subclass. 11.25 For the GeometricObject and Circle classes in Listings 11.1 and 11.2, answer the following questions: a. read more..

  • Page - 454

    g. Is orange instanceof Fruit? h. Is orange instanceof Apple? i. Suppose the method makeAppleCider is defined in the Apple class. Can fruit invoke this method? Can orange invoke this method? j. Suppose the method makeOrangeJuice is defined in the Orange class. Can orange invoke this method? Can fruit invoke this method? k. Is the statement Orange p = new read more..

  • Page - 455

    432 Chapter 11 Inheritance and Polymorphism You can override the equals method in the Circle class to compare whether two circles are equal based on their radius as follows: public boolean equals(Object o) { if (o instanceof Circle) return radius == ((Circle)o).radius; else return this == o; } Note The == comparison operator is used for comparing two primitive data read more..

  • Page - 456

    class, which can be used to store an unlimited number of objects. Figure 11.3 shows some methods in ArrayList. 11.11 The ArrayList Class 433 FIGURE 11.3 An ArrayList stores an unlimited number of objects. java.util.ArrayList<E> +ArrayList() +add(o: E): void +add(index: int, o: E): void +clear(): void +contains(o: Object): boolean +get(index: int): E +indexOf(o: Object): int +isEmpty(): read more..

  • Page - 457

    434 Chapter 11 Inheritance and Polymorphism 3 public class TestArrayList { 4 public static void main(String[] args) { 5 // Create a list to store cities 6 ArrayList<String> cityList = new ArrayList<>(); 7 8 // Add some cities in the list 9 cityList.add("London"); 10 // cityList now contains [London] 11 cityList.add("Denver"); 12 // read more..

  • Page - 458

    Since the ArrayList is in the java.util package, it is imported in line 1. The program creates an ArrayList of strings using its no-arg constructor and assigns the reference to cityList (line 6). The add method (lines 9–19) adds strings to the end of list. So, after cityList.add("London") (line 9), the list contains [London] After cityList.add("Denver") read more..

  • Page - 459

    436 Chapter 11 Inheritance and Polymorphism You cannot use the get(index) and set(index, element) methods if the element is not in the list. It is easy to add, insert, and remove elements in a list, but it is rather complex to add, insert, and remove elements in an array. You have to write code to manipulate the array in order to perform these operations. Note that read more..

  • Page - 460

    18 19 // Display the distinct numbers 20 for (int i = 0; i < list.size(); i++) 21 System.out.print(list.get(i) + " "); 22 } 23 } Enter numbers (input ends with 0): 1 2 3 2 1 6 3 4 5 4 5 1 2 3 0 The distinct numbers are: 1 2 3 6 4 5 11.11 The ArrayList Class 437 The program creates an ArrayList for Integer objects read more..

  • Page - 461

    438 Chapter 11 Inheritance and Polymorphism 11.32 Suppose the ArrayList list contains {"Dallas", "Dallas", "Houston", "Dallas"}. What is the list after invoking list.remove("Dallas") one time? Does the following code correctly remove all elements with value "Dallas" from the list? If not, correct the code. for (int i = 0; i < read more..

  • Page - 462

    11.13 Case Study: A Custom Stack Class 439 You can use the static shuffle method in the java.util.Collections class to perform a random shuffle for the elements in a list. Here are examples: Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}; ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array)); java.util.Collections.shuffle(list); System.out.println(list); 11.35 Correct read more..

  • Page - 463

    440 Chapter 11 Inheritance and Polymorphism 17 18 public Object pop() { 19 Object o = list.get(getSize() - 1); 20 list.remove(getSize() - 1); 21 return o; 22 } 23 24 public void push(Object o) { 25 list.add(o); 26 } 27 28 @Override 29 public String toString() { 30 return "stack: " + list.toString(); 31 } 32 read more..

  • Page - 464

    Your class can be used in two ways: (1) for creating instances of the class and (2) for defin- ing subclasses by extending the class. Make the members private if they are not intended for use from outside the class. Make the members public if they are intended for the users of the class. Make the fields or methods protected if they are intended for the read more..

  • Page - 465

    442 Chapter 11 Inheritance and Polymorphism Note A subclass may override a protected method defined in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass. 11.37 What modifier read more..

  • Page - 466

    You also can define a method to be final; a final method cannot be overridden by its subclasses. For example, the following method m is final and cannot be overridden: public class Test { // Data fields, constructors, and methods omitted public final void m() { // Do something } } Note The modifiers public, protected, private, static, abstract, and final are used on read more..

  • Page - 467

    444 Chapter 11 Inheritance and Polymorphism 3. A constructor may invoke an overloaded constructor or its superclass’s constructor. The call must be the first statement in the constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor, which invokes the superclass’s no-arg constructor. 4. To override a method, the read more..

  • Page - 468

    Programming Exercises 445 PROGRAMMING EXERCISES Sections 11.2–11.4 11.1 (The Triangle class) Design a class named Triangle that extends GeometricObject. The class contains: ■ Three double data fields named side1, side2, and side3 with default values 1.0 to denote three sides of the triangle. ■ A no-arg constructor that creates a default triangle. ■ A constructor read more..

  • Page - 469

    446 Chapter 11 Inheritance and Polymorphism Write a test program that prompts the user to enter a sequence of numbers ending with 0, and invokes this method to return the largest number in the input. 11.5 (The Course class) Rewrite the Course class in Listing 10.6. Use an ArrayList to replace an array to store students. Draw the new UML diagram for the class. You should read more..

  • Page - 470

    Programming Exercises 447 *11.9 (Largest rows and columns) Write a program that randomly fills in 0s and 1s into an n-by-n matrix, prints the matrix, and finds the rows and columns with the most 1s. (Hint: Use two ArrayLists to store the row and column indices with the most 1s.) Here is a sample run of the program: Enter ten integers: 34 5 3 5 6 4 33 2 2 4 read more..

  • Page - 471

    448 Chapter 11 Inheritance and Polymorphism For example, the union of two array lists {2, 3, 1, 5} and {3, 4, 6} is {2, 3, 1, 5, 3, 4, 6}. Write a test program that prompts the user to enter two lists, each with five integers, and displays their union. The numbers are separated by exactly one space in the output. Here is a sample run: Enter five read more..

  • Page - 472

    EXCEPTION HANDLING AND TEXT I/O Objectives ■ To get an overview of exceptions and exception handling (§12.2). ■ To explore the advantages of using exception handling (§12.2). ■ To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs. unchecked (§12.3). ■ To declare exceptions in a method header (§12.4.1). ■ To throw exceptions in a method read more..

  • Page - 473

    450 Chapter 12 Exception Handling and Text I/O 12.1 Introduction Exception handling enables a program to deal with exceptional situations and continue its normal execution. Runtime errors occur while a program is running if the JVM detects an operation that is impossible to carry out. For example, if you access an array using an index that is out of bounds, you will get read more..

  • Page - 474

    12.2 Exception-Handling Overview 451 LISTING 12.2 QuotientWithIf.java 1 import java.util.Scanner; 2 3 public class QuotientWithIf { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 7 // Prompt the user to enter two integers 8 System.out.print("Enter two integers: "); 9 int number1 = input.nextInt(); 10 read more..

  • Page - 475

    452 Chapter 12 Exception Handling and Text I/O The method quotient (lines 4–11) returns the quotient of two integers. If number2 is 0, it cannot return a value, so the program is terminated in line 7. This is clearly a problem. You should not let the method terminate the program—the caller should decide whether to termi- nate the program. How can a method read more..

  • Page - 476

    12.2 Exception-Handling Overview 453 If number2 is 0, the method throws an exception (line 6) by executing throw new ArithmeticException("Divisor cannot be zero"); The value thrown, in this case new ArithmeticException("Divisor cannot be zero"), is called an exception. The execution of a throw statement is called throwing an exception. The exception is an object created read more..

  • Page - 477

    454 Chapter 12 Exception Handling and Text I/O done when an error occurs. The key benefit of exception handling is separating the detection of an error (done in a called method) from the handling of an error (done in the calling method). Many library methods throw exceptions. Listing 12.5 gives an example that handles an InputMismatchException when reading an input. LISTING read more..

  • Page - 478

    12.3 Exception Types 455 12.3 Point out the problem in the following code. Does the code throw any exceptions? long value = Long.MAX_VALUE + 1; System.out.println(value); 12.4 What does the JVM do when an exception occurs? How do you catch an exception? 12.5 What is the output of the following code? public class Test { public static void main(String[] args) { try { int read more..

  • Page - 479

    456 Chapter 12 Exception Handling and Text I/O Note The class names Error, Exception, and RuntimeException are somewhat con- fusing. All three of these classes are exceptions, and all of the errors occur at runtime. The Throwable class is the root of exception classes. All Java exception classes inherit directly or indirectly from Throwable. You can create your own exception read more..

  • Page - 480

    12.3 Exception Types 457 ■ Runtime exceptions are represented in the RuntimeException class, which describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Runtime exceptions are generally thrown by the JVM. Examples of subclasses are listed in Table 12.3. runtime exception Class Reasons for Exception ArithmeticException Dividing an read more..

  • Page - 481

    458 Chapter 12 Exception Handling and Text I/O 12.4 More on Exception Handling A handler for an exception is found by propagating the exception backward through a chain of method calls, starting from the current method. The preceding sections gave you an overview of exception handling and introduced sev- eral predefined exception types. This section provides an in-depth discussion read more..

  • Page - 482

    12.4 More on Exception Handling 459 must be nonnegative, but a negative argument is passed); the program can create an instance of IllegalArgumentException and throw it, as follows: IllegalArgumentException ex = new IllegalArgumentException("Wrong Argument"); throw ex; Or, if you prefer, you can use the following: throw new IllegalArgumentException("Wrong Argument"); Note read more..

  • Page - 483

    460 Chapter 12 Exception Handling and Text I/O Suppose the main method invokes method1, method1 invokes method2, method2 invokes method3, and method3 throws an exception, as shown in Figure 12.3. Consider the following scenario: ■ If the exception type is Exception3, it is caught by the catch block for han- dling exception ex3 in method2. statement5 is skipped, and read more..

  • Page - 484

    12.4 More on Exception Handling 461 Note Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2, and p2 may throw a read more..

  • Page - 485

    462 Chapter 12 Exception Handling and Text I/O information on the console. The getStackTrace() method provides programmatic access to the stack trace information printed by printStackTrace(). Listing 12.6 gives an example that uses the methods in Throwable to display exception information. Line 4 invokes the sum method to return the sum of all the elements in the array. read more..

  • Page - 486

    12.4 More on Exception Handling 463 24 result += list[i]; 25 return result; 26 } 27 } 12.4.5 Example: Declaring, Throwing, and Catching Exceptions This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius method in the Circle class in Listing 9.8, CircleWithPrivateDataFields.java. The new setRadius method throws an read more..

  • Page - 487

    464 Chapter 12 Exception Handling and Text I/O A test program that uses the new Circle class is given in Listing 12.8. LISTING 12.8 TestCircleWithException.java 1 public class TestCircleWithException { 2 public static void main(String[] args) { 3 try { 4 CircleWithException c1 = new CircleWithException(5); 5 CircleWithException c2 = new read more..

  • Page - 488

    12.4 More on Exception Handling 465 12.13 Suppose that statement2 causes an exception in the following try-catch block: try { statement1; statement2; statement3; } catch (Exception1 ex1) { } catch (Exception2 ex2) { } statement4; Answer the following questions: ■ Will statement3 be executed? ■ If the exception is not caught, will statement4 be executed? ■ If the read more..

  • Page - 489

    466 Chapter 12 Exception Handling and Text I/O System.out.println(1 / 0); } } 12.16 What is displayed when the following program is run? public class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call" ); } catch (RuntimeException ex) { read more..

  • Page - 490

    12.6 When to Use Exceptions 467 finally { finalStatements; } The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or is caught. Consider three possible cases: ■ If no exception arises in the try block, finalStatements is executed, and the next statement after the try statement is read more..

  • Page - 491

    468 Chapter 12 Exception Handling and Text I/O An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw or use exceptions. In general, common exceptions that may occur in multiple classes in a read more..

  • Page - 492

    12.8 Chained Exceptions 469 12.23 Suppose that statement2 causes an exception in the following statement: try { statement1; statement2; statement3; } catch (Exception1 ex1) { } catch (Exception2 ex2) { throw ex2; } finally { statement4; } statement5; Answer the following questions: ■ If no exception occurs, will statement4 be executed, and will statement5 be read more..

  • Page - 493

    470 Chapter 12 Exception Handling and Text I/O 19 20 public static void method2() throws Exception { 21 throw new Exception("New info from method2"); 22 } 23 } throw exception java.lang.Exception: New info from method1 at ChainedExceptionDemo.method1(ChainedExceptionDemo.java:16) at ChainedExceptionDemo.main(ChainedExceptionDemo.java:4) Caused by: java.lang.Exception: New info read more..

  • Page - 494

    12.9 Defining Custom Exception Classes 471 printStackTrace()) in Exception are inherited from Throwable. The Exception class contains four constructors. Among them, the following two constructors are often used: java.lang.Exception +Exception() +Exception(message: String) Constructs an exception with no message. Constructs an exception with the specified message. Line 6 invokes the superclass’s read more..

  • Page - 495

    472 Chapter 12 Exception Handling and Text I/O 38 return radius; 39 } 40 41 /** Set a new radius */ 42 public void setRadius(double newRadius) 43 throws InvalidRadiusException { 44 if (newRadius >= 0 ) 45 radius = newRadius; 46 else 47 throw new InvalidRadiusException(newRadius); 48 } 49 50 /** Return numberOfObjects */ 51 public static int read more..

  • Page - 496

    12.10 The File Class 473 catch (Exception ex) { System.out.println("Exception in main"); } } static void method() throws Exception { try { Circle c1 = new Circle(1); c1.setRadius(-1); System.out.println(c1.getRadius()); } catch (RuntimeException ex) { System.out.println("RuntimeException in read more..

  • Page - 497

    474 Chapter 12 Exception Handling and Text I/O Caution The directory separator for Windows is a backslash (\). The backslash is a special char- acter in Java and should be written as \\ in a string literal (see Table 4.5). Note Constructing a File instance does not create a file on the machine. You can create a File instance for any file name regardless whether read more..

  • Page - 498

    is the same as on UNIX. The statement new File("image/us.gif") works on Windows, UNIX, and any other platform. Listing 12.12 demonstrates how to create a File object and use the methods in the File class to obtain its properties. The program creates a File object for the file us.gif. This file is stored under the image directory in the current directory. read more..

  • Page - 499

    476 Chapter 12 Exception Handling and Text I/O 12.11 File Input and Output Use the Scanner class for reading text data from a file and the PrintWriter class for writing text data to a file. A File object encapsulates the properties of a file or a path, but it does not contain the meth- ods for creating a file or for writing/reading data to/from a file read more..

  • Page - 500

    12.11 File Input and Output 477 Lines 4–7 check whether the file scores.txt exists. If so, exit the program (line 6). Invoking the constructor of PrintWriter will create a new file if the file does not exist. If the file already exists, the current content in the file will be discarded without verifying with the user. Invoking the constructor of PrintWriter may read more..

  • Page - 501

    478 Chapter 12 Exception Handling and Text I/O A resource is declared and created followed by the keyword try. Note that the resources are enclosed in the parentheses (lines 9–12). The resources must be a subtype of AutoCloseable such as a PrinterWriter that has the close() method. A resource must be declared and created in the same statement and multiple resources read more..

  • Page - 502

    12.11 File Input and Output 479 Note that new Scanner(String) creates a Scanner for a given string. To create a Scanner to read data from a file, you have to use the java.io.File class to create an instance of the File using the constructor new File(filename) (line 6), and use new Scanner(File) to create a Scanner for the file (line 9). Invoking the read more..

  • Page - 503

    480 Chapter 12 Exception Handling and Text I/O Suppose a text file named test.txt contains a line 34 567 After the following code is executed, Scanner input = new Scanner(new File("test.txt")); int intValue = input.nextInt(); String line = input.nextLine(); intValue contains 34 and line contains the characters ' ', 5, 6, and 7. What happens if the input is read more..

  • Page - 504

    12.11 File Input and Output 481 4 public class ReplaceText { 5 public static void main(String[] args) throws Exception { 6 // Check command line parameter usage 7 if (args.length != 4) { 8 System.out.println( 9 "Usage: java ReplaceText sourceFile targetFile oldStr newStr"); 10 System.exit(1); 11 } 12 13 // Check if read more..

  • Page - 505

    482 Chapter 12 Exception Handling and Text I/O 12.32 Rewrite the code in the preceding question using a try-with-resources syntax. 12.33 How do you create a Scanner to read data from a file? What is the reason to define throws Exception in the main method in Listing 12.15, ReadData.java? What would happen if the close() method were not invoked in Listing 12.15? read more..

  • Page - 506

    12.12 Reading Data from the Web 483 4 catch (MalformedURLException ex) { 5 ex.printStackTrace(); 6 } A MalformedURLException is thrown if the URL string has a syntax error. For example, the URL string “http:www.google.com/index.html” would cause a MalformedURLException runtime error because two slashes (//) are required after the colon (:). Note that the http:// prefix read more..

  • Page - 507

    484 Chapter 12 Exception Handling and Text I/O The program prompts the user to enter a URL string (line 6) and creates a URL object (line 9). The constructor will throw a java.net.MalformedURLException (line 19) if the URL isn’t formed correctly. The program creates a Scanner object from the input stream for the URL (line 11). If the URL is formed correctly but read more..

  • Page - 508

    12.13 Case Study: Web Crawler 485 Remove a URL from listOfPendingURLs; if this URL is not in listOfTraversedURLs { Add it to listOfTraversedURLs; Display this URL; Read the page from this URL and for each URL contained in the page { Add it to listOfPendingURLs if it is not in listOfTraversedURLs; } } } Listing read more..

  • Page - 509

    486 Chapter 12 Exception Handling and Text I/O 48 else 49 current = -1; 50 } 51 } 52 } 53 catch (Exception ex) { 54 System.out.println("Error: " + ex.getMessage()); 55 } 56 57 return list; 58 } 59 } return URLs KEY TERMS absolute file name 473 chained read more..

  • Page - 510

    Chapter Summary 487 CHAPTER SUMMARY 1. Exception handling enables a method to throw an exception to its caller. 2. A Java exception is an instance of a class derived from java.lang.Throwable. Java provides a number of predefined exception classes, such as Error, Exception, RuntimeException, ClassNotFoundException, NullPointerException, and ArithmeticException. You can also define your read more..

  • Page - 511

    488 Chapter 12 Exception Handling and Text I/O QUIZ Answer the quiz for this chapter online at www.cs.armstrong.edu/liang/intro10e/quiz.html . PROGRAMMING EXERCISES Sections 12.2–12.9 *12.1 (NumberFormatException) Listing 7.9, Calculator.java, is a simple command- line calculator. Note that the program terminates if any operand is nonnumeric. Write a program with an exception handler that deals read more..

  • Page - 512

    Programming Exercises 489 *12.6 (NumberFormatException) Listing 6.8 implements the hex2Dec(String hexString) method, which converts a hex string into a decimal number. Implement the hex2Dec method to throw a NumberFormatException if the string is not a hex string. *12.7 (NumberFormatException) Write the bin2Dec(String binaryString) method to convert a binary string into a decimal number. read more..

  • Page - 513

    490 Chapter 12 Exception Handling and Text I/O *12.14 (Process scores in a text file) Suppose that a text file contains an unspecified number of scores separated by blanks. Write a program that prompts the user to enter the file, reads the scores from the file, and displays their total and average. *12.15 (Write/read data) Write a program to create a file named read more..

  • Page - 514

    Programming Exercises 491 If the strings are not sorted in the f ile, displays the first two strings that are out of the order. **12.22 (Replace text) Revise Programming Exercise 12.16 to replace a string in a file with a new string for all files in the specified directory using the command: java Exercise12_22 dir oldString newString **12.23 (Process scores in a text file on the Web) read more..

  • Page - 515

    492 Chapter 12 Exception Handling and Text I/O **12.29 (Rename files) Suppose you have a lot of files in a directory named Exercisei_j, where i and j are digits. Write a program that pads a 0 before j if j is a single digit. For example, a file named Exercise2_1 in a directory will be renamed to Exercise2_01. In Java, when you pass the symbol * from read more..

  • Page - 516

    Programming Exercises 493 *12.32 (Ranking summary) Write a program that uses the files described in Program- ming Exercise 12.31 and displays a ranking summary table for the first five girl’s and boy’s names as follows: Year Rank 1 Rank 2 Rank 3 Rank 4 Rank 5 Rank 1 Rank 2 Rank 3 Rank 4 Rank 5 2010 Isabella Sophia Emma Olivia Ava Jacob Ethan Michael Jayden William 2009 read more..

  • Page - 517

    This page intentionally left blank read more..

  • Page - 518

    ABSTRACT CLASSES AND INTERFACES Objectives ■ To design and use abstract classes (§13.2). ■ To generalize numeric wrapper classes, BigInteger, and BigDecimal using the abstract Number class (§13.3). ■ To process a calendar using the Calendar and GregorianCalendar classes (§13.4). ■ To specify common behavior for objects using interfaces (§13.5). ■ To define interfaces and read more..

  • Page - 519

    496 Chapter 13 Abstract Classes and Interfaces 13.1 Introduction A superclass defines common behavior for related subclasses. An interface can be used to define common behavior for classes (including unrelated classes). You can use the java.util.Arrays.sort method to sort an array of numbers or strings. Can you apply the same sort method to sort an array of geometric objects? read more..

  • Page - 520

    13.2 Abstract Classes 497 21 } 22 23 /** Set a new color */ 24 public void setColor(String color) { 25 this.color = color; 26 } 27 28 /** Return filled. Since filled is boolean, 29 * the get method is named isFilled */ 30 public boolean isFilled() { 31 return filled; 32 } 33 34 /** Set a new filled */ 35 public void setFilled(boolean filled) { read more..

  • Page - 521

    498 Chapter 13 Abstract Classes and Interfaces 43 44 @Override 45 public String toString() { 46 return "created on " + dateCreated + "\ncolor: " + color + 47 " and filled: " + filled; 48 } 49 50 /** Abstract method getArea */ 51 public abstract double getArea(); 52 53 /** Abstract method getPerimeter */ 54 public abstract double read more..

  • Page - 522

    13.2 Abstract Classes 499 7 8 System.out.println("The two objects have the same area? " + 9 equalArea(geoObject1, geoObject2)); 10 11 // Display circle 12 displayGeometricObject(geoObject1); 13 14 // Display rectangle 15 displayGeometricObject(geoObject2); 16 } 17 18 /** A method for comparing the areas of two geometric objects */ 19 public read more..

  • Page - 523

    500 Chapter 13 Abstract Classes and Interfaces 13.2.2 Interesting Points about Abstract Classes The following points about abstract classes are worth noting: ■ An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined as abstract. In other words, in a read more..

  • Page - 524

    13.3 Case Study: the Abstract Number Class 501 13.2 The getArea() and getPerimeter() methods may be removed from the GeometricObject class. What are the benefits of defining getArea() and getPerimeter() as abstract methods in the GeometricObject class? 13.3 True or false? a. An abstract class can be used just like a nonabstract class except that you cannot use the new read more..

  • Page - 525

    502 Chapter 13 Abstract Classes and Interfaces With Number defined as the superclass for the numeric classes, we can define methods to perform common operations for numbers. Listing 13.5 gives a program that finds the largest number in a list of Number objects. LISTING 13.5 LargestNumbers.java 1 import java.util.ArrayList; 2 import java.math.*; 3 4 public class read more..

  • Page - 526

    13.4 Case Study: Calendar and GregorianCalendar 503 13.5 Why do the following two lines of code compile but cause a runtime error? Number[] numberArray = new Integer[2]; numberArray[0] = new Double(1.5); 13.6 Show the output of the following code. public class Test { public static void main(String[] args) { Number x = 3; read more..

  • Page - 527

    504 Chapter 13 Abstract Classes and Interfaces FIGURE 13.3 The abstract Calendar class defines common features of various calendars. +GregorianCalendar() +GregorianCalendar(year: int, month: int, dayOfMonth: int) +GregorianCalendar(year: int, month: int, dayOfMonth: int, hour:int, minute: int, second: int) Constructs a GregorianCalendar for the current time. Constructs a GregorianCalendar for the read more..

  • Page - 528

    9 System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); 10 System.out.println("DATE: " + calendar.get(Calendar.DATE)); 11 System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); 12 System.out.println("HOUR_OF_DAY: " + 13 calendar.get(Calendar.HOUR_OF_DAY)); 14 System.out.println("MINUTE: " + read more..

  • Page - 529

    506 Chapter 13 Abstract Classes and Interfaces You can set a time represented in a Date object for the calendar by invoking calendar.setTime(date) and retrieve the time by invoking calendar.getTime(). 13.9 Can you create a Calendar object using the Calendar class? 13.10 Which method in the Calendar class is abstract? 13.11 How do you create a Calendar object for read more..

  • Page - 530

    13.5 Interfaces 507 14 15 abstract class Animal { 16 /** Return animal sound */ 17 public abstract String sound(); 18 } 19 20 class Chicken extends Animal implements Edible { 21 @Override 22 public String howToEat() { 23 return "Chicken: Fry it" ; 24 } 25 26 @Override 27 public String sound() { 28 return "Chicken: cock-a-doodle-doo"; 29 read more..

  • Page - 531

    508 Chapter 13 Abstract Classes and Interfaces The Fruit class implements Edible. Since it does not implement the howToEat method, Fruit must be denoted as abstract (line 39). The concrete subclasses of Fruit must implement the howToEat method. The Apple and Orange classes implement the howToEat method (lines 45, 52). The main method creates an array with three read more..

  • Page - 532

    13.6 The Comparable Interface 509 13.16 Show the error in the following code: interface A { void m1(); } class B implements A { void m1() { System.out.println("m1"); } } 13.6 The Comparable Interface The Comparable interface defines the compareTo method for comparing objects. Suppose you want to design a generic method to find the larger of two read more..

  • Page - 533

    510 Chapter 13 Abstract Classes and Interfaces Thus, numbers are comparable, strings are comparable, and so are dates. You can use the compareTo method to compare two numbers, two strings, and two dates. For example, the following code 1 System.out.println(new Integer(3).compareTo(new Integer(5))); 2 System.out.println("ABC".compareTo("ABE")); read more..

  • Page - 534

    Atlanta Boston Savannah Tampa 54623239292 432232323239292 2323231092923992 The program creates an array of strings (line 5) and invokes the sort method to sort the strings (line 6). The program creates an array of BigInteger objects (lines 11–13) and invokes the sort method to sort the BigInteger objects (line 14). You cannot use the sort method to sort an array of read more..

  • Page - 535

    512 Chapter 13 Abstract Classes and Interfaces You can now use the sort method to sort an array of ComparableRectangle objects, as in Listing 13.10. LISTING 13.10 SortRectangles.java 1 public class SortRectangles { 2 public static void main(String[] args) { 3 ComparableRectangle[] rectangles = { 4 new ComparableRectangle(3.4, 5.4), 5 new ComparableRectangle(13.24, 55.4), read more..

  • Page - 536

    13.7 The Cloneable Interface 513 13.20 You can define the compareTo method in a class without implementing the Comparable interface. What are the benefits of implementing the Comparable interface? 13.21 What is wrong in the following code? public class Test { public static void main(String[] args) { Person[] persons = {new Person(3), new Person(4), new read more..

  • Page - 537

    514 Chapter 13 Abstract Classes and Interfaces In the preceding code, line 2 copies the reference of calendar to calendar1, so calendar and calendar1 point to the same Calendar object. Line 3 creates a new object that is the clone of calendar and assigns the new object’s reference to calendar2. calendar2 and calendar are different objects with the same contents. read more..

  • Page - 538

    11 12 public int getId() { 13 return id; 14 } 15 16 public double getArea() { 17 return area; 18 } 19 20 public java.util.Date getWhenBuilt() { 21 return whenBuilt; 22 } 23 24 @Override /** Override the protected clone method defined in 25 the Object class, and strengthen its accessibility */ 26 public Object clone() throws CloneNotSupportedException read more..

  • Page - 539

    516 Chapter 13 Abstract Classes and Interfaces deep copy, meaning that if the field is of an object type, the object’s reference is copied rather than its contents. deep copy FIGURE 13.6 (a) The default clone method performs a shallow copy. (b) The custom clone method performs a deep copy. (a) (b) house2: House id = 1 area = 1750.50 whenBuilt Memory house2 = read more..

  • Page - 540

    13.8 Interfaces vs. Abstract Classes 517 13.22 Can you invoke the clone() method to clone an object if the class for the object does not implement the java.lang.Cloneable? Does the Date class implement Cloneable? 13.23 What would happen if the House class (defined in Listing 13.11) did not override the clone() method or if House did not implement java.lang.Cloneable? read more..

  • Page - 541

    518 Chapter 13 Abstract Classes and Interfaces Java allows only single inheritance for class extension but allows multiple extensions for interfaces. For example, public class NewClass extends BaseClass implements Interface1, ..., InterfaceN { ... } An interface can inherit other interfaces using the extends keyword. Such an interface is called a subinterface. For example, read more..

  • Page - 542

    13.8 Interfaces vs. Abstract Classes 519 In general, interfaces are preferred over abstract classes because an interface can define a common supertype for unrelated classes. Interfaces are more flexible than classes. Consider the Animal class. Suppose the howToEat method is defined in the Animal class, as follows: abstract class Animal { public abstract String howToEat(); } read more..

  • Page - 543

    520 Chapter 13 Abstract Classes and Interfaces public static void eat(Edible stuff) { stuff.howToEat(); } interface Edible { public String howToEat(); } class Chicken implements Edible { @Override public String howToEat() { return "Fry it" ; } } class Duck implements Edible { @Override public String howToEat() { return "Roast it" ; } } class read more..

  • Page - 544

    Java provides data types for integers and floating-point numbers, but not for rational num- bers. This section shows how to design a class to represent rational numbers. Since rational numbers share many common features with integers and floating-point num- bers, and Number is the root class for numeric wrapper classes, it is appropriate to define Rational as a subclass of read more..

  • Page - 545

    522 Chapter 13 Abstract Classes and Interfaces 9 System.out.println(r1 + " + " + r2 + " = " + r1.add(r2)); 10 System.out.println(r1 + " - " + r2 + " = " + r1.subtract(r2)); 11 System.out.println(r1 + " * " + r2 + " = " + r1.multiply(r2)); 12 System.out.println(r1 + " / " + read more..

  • Page - 546

    30 } 31 32 /** Return numerator */ 33 public long getNumerator() { 34 return numerator; 35 } 36 37 /** Return denominator */ 38 public long getDenominator() { 39 return denominator; 40 } 41 42 /** Add a rational number to this rational */ 43 public Rational add(Rational secondRational) { 44 long n = numerator * read more..

  • Page - 547

    524 Chapter 13 Abstract Classes and Interfaces 90 return (int)doubleValue(); 91 } 92 93 @Override // Implement the abstract floatValue method in Number 94 public float floatValue() { 95 return (float)doubleValue(); 96 } 97 98 @Override // Implement the doubleValue method in Number 99 public double doubleValue() { 100 return numerator read more..

  • Page - 548

    13.10 Class Design Guidelines 525 Tip The numerator and denominator are represented using two variables. It is possible to use an array of two integers to represent the numerator and denominator (see Programming Exercise 13.14). The signatures of the public methods in the Rational class are not changed, although the internal representation of a rational number is changed. This read more..

  • Page - 549

    526 Chapter 13 Abstract Classes and Interfaces 13.10.1 Cohesion A class should describe a single entity, and all the class operations should logically fit together to support a coherent purpose. You can use a class for students, for example, but you should not combine students and staff in the same class, because students and staff are different entities. A single entity with read more..

  • Page - 550

    13.10 Class Design Guidelines 527 private int age; ... } 13.10.5 Completeness Classes are designed for use by many different customers. In order to be useful in a wide range of applications, a class should provide a variety of ways for customization through properties and methods. For example, the String class contains more than 40 methods that are useful for a variety read more..

  • Page - 551

    528 Chapter 13 Abstract Classes and Interfaces 13.10.8 Interfaces vs. Abstract Classes Both interfaces and abstract classes can be used to specify common behavior for objects. How do you decide whether to use an interface or a class? In general, a strong is-a relationship that clearly describes a parent–child relationship should be modeled using classes. For exam- ple, since an read more..

  • Page - 552

    Programming Exercises 529 8. The java.lang.Cloneable interface is a marker interface. An object of the class that implements the Cloneable interface is cloneable. 9. A class can extend only one superclass but can implement one or more interfaces. 10. An interface can extend one or more interfaces. QUIZ Answer the quiz for this chapter online at read more..

  • Page - 553

    530 Chapter 13 Abstract Classes and Interfaces You also can run the program without the year. In this case, the year is the current year. If you run the program without specifying a month and a year, the month is the current month. Sections 13.4–13.8 *13.5 (Enable GeometricObject comparable) Modify the GeometricObject class to implement the Comparable interface, and read more..

  • Page - 554

    Programming Exercises 531 Write a test program that creates an array of four objects (two circles and two rectangles) and computes their total area using the sumArea method. *13.13 (Enable the Course class cloneable) Rewrite the Course class in Listing 10.6 to add a clone method to perform a deep copy on the students field. Section 13.9 *13.14 (Demonstrate the benefits read more..

  • Page - 555

    532 Chapter 13 Abstract Classes and Interfaces You can also obtain the absolute value for a complex number using the following formula: a + bi = 2a2 + b2 (A complex number can be interpreted as a point on a plane by identifying the (a,b) values as the coordinates of the point. The absolute value of the complex number corresponds to the distance of the point read more..

  • Page - 556

    Programming Exercises 533 13.20 (Algebra: solve quadratic equations) Rewrite Programming Exercise 3.1 to obtain imaginary roots if the determinant is less than 0 using the Complex class in Programming Exercise 13.17. Here are some sample runs. Enter a decimal number: -0.45452 The fraction number is -11363/25000 13.21 (Algebra: vertex form equations) The equation of a parabola read more..

  • Page - 557

    This page intentionally left blank read more..

  • Page - 558

    JAVAFX BASICS Objectives ■ To distinguish between JavaFX, Swing, and AWT (§14.2). ■ To write a simple JavaFX program and understand the relationship among stages, scenes, and nodes (§14.3). ■ To create user interfaces using panes, UI controls, and shapes (§14.4). ■ To update property values automatically through property binding (§14.5). ■ To use the common properties style read more..

  • Page - 559

    536 Chapter 14 JavaFX Basics 14.1 Introduction JavaFX is an excellent pedagogical tool for learning object-oriented programming. JavaFX is a new framework for developing Java GUI programs. The JavaFX API is an excellent example of how the object-oriented principles are applied. This chapter serves two purposes. First, it presents the basics of JavaFX programming. Second, it uses read more..

  • Page - 560

    14.3 The Basic Structure of a JavaFX Program 537 5 6 public class MyJavaFX extends Application { 7 @Override // Override the start method in the Application class 8 public void start(Stage primaryStage) { 9 // Create a scene and place a button in the scene 10 Button btOK = new Button("OK"); 11 Scene scene = new read more..

  • Page - 561

    538 Chapter 14 JavaFX Basics LISTING 14.2 MultipleStageDemo.java 1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.scene.control.Button; 4 import javafx.stage.Stage; 5 6 public class MultipleStageDemo extends Application { 7 @Override // Override the start method in the Application class 8 public void start(Stage primaryStage) { 9 read more..

  • Page - 562

    14.4 Panes, UI Controls, and Shapes 539 @Override // Override the start method in the Application class public void start(Stage primaryStage) { System.out.println("start method is invoked"); } public static void main(String[] args) { System.out.println("launch application"); Application.launch(args); } } 14.4 Panes, UI Controls, and Shapes read more..

  • Page - 563

    540 Chapter 14 JavaFX Basics LISTING 14.3 ButtonInPane.java 1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.scene.control.Button; 4 import javafx.stage.Stage; 5 import javafx.scene.layout.StackPane; 6 7 public class ButtonInPane extends Application { 8 @Override // Override the start method in the Application class 9 public void read more..

  • Page - 564

    14.4 Panes, UI Controls, and Shapes 541 21 pane.getChildren().add(circle); 22 23 // Create a scene and place it in the stage 24 Scene scene = new Scene(pane, 200, 200); 25 primaryStage.setTitle("ShowCircle"); // Set the stage title 26 primaryStage.setScene(scene); // Place the scene in the stage 27 primaryStage.show(); // Display the stage 28 } 29 read more..

  • Page - 565

    542 Chapter 14 JavaFX Basics 14.5 How do you create a Scene object? How do you set a scene in a stage? How do you place a circle into a scene? 14.6 What is a pane? What is a node? How do you place a node in a pane? Can you directly place a Shape or an ImageView into a Scene? Can you directly place a Control or a Pane into a Scene? 14.7 read more..

  • Page - 566

    14.5 Property Binding 543 updates itself once a change is made in the source. A target binds with a source using the bind method as follows: target.bind(source); The bind method is defined in the javafx.beans.property.Property interface. A binding property is an instance of javafx.beans.property.Property. A source object is an instance of the javafx.beans.value.ObservableValue read more..

  • Page - 567

    544 Chapter 14 JavaFX Basics Since centerX is bound to width.divide(2), when pane’s width is changed, centerX automatically updates itself to match pane’s width / 2. Listing 14.6 gives another example that demonstrates bindings. LISTING 14.6 BindingDemo.java 1 import javafx.beans.property.DoubleProperty; 2 import javafx.beans.property.SimpleDoubleProperty; 3 4 public class BindingDemo read more..

  • Page - 568

    14.6 Common Properties and Methods for Nodes 545 14.6 Common Properties and Methods for Nodes The abstract Node class defines many properties and methods that are common to all nodes. Nodes share many common properties. This section introduces two such properties style and rotate. JavaFX style properties are similar to cascading style sheets (CSS) used to specify the styles for read more..

  • Page - 569

    546 Chapter 14 JavaFX Basics 23 primaryStage.show(); // Display the stage 24 } 25 } FIGURE 14.8 A pane’s style is set and it is rotated 45 degrees. As seen in Figure 14.8, the rotate on a pane causes all its containing nodes rotated too. The Node class contains many useful methods that can be applied to all nodes. For example, you can use the contains(double read more..

  • Page - 570

    A color instance can be constructed using the following constructor: public Color(double r, double g, double b, double opacity); in which r, g, and b specify a color by its red, green, and blue components with values in the range from 0.0 (darkest shade) to 1.0 (lightest shade). The opacity value defines the trans- parency of a color within the range from read more..

  • Page - 571

    548 Chapter 14 JavaFX Basics LISTING 14.8 FontDemo.java 1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.scene.layout.*; 4 import javafx.scene.paint.Color; 5 import javafx.scene.shape.Circle; 6 import javafx.scene.text.*; 7 import javafx.scene.control.*; 8 import javafx.stage.Stage; 9 10 public class FontDemo extends Application { 11 read more..

  • Page - 572

    The program creates a StackPane (line 14) and adds a circle and a label to it (lines 21, 27). These two statements can be combined using the following one statement: pane.getChildren().addAll(circle, label); A StackPane places the nodes in the center and nodes are placed on top of each other. A custom color is created and set as a fill color for the circle (line 20). read more..

  • Page - 573

    550 Chapter 14 JavaFX Basics Listing 14.9 displays an image in three image views, as shown in Figure 14.14. LISTING 14.9 ShowImage.java 1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.scene.layout.HBox; 4 import javafx.scene.layout.Pane; 5 import javafx.geometry.Insets; 6 import javafx.stage.Stage; 7 import javafx.scene.image.Image; 8 import read more..

  • Page - 574

    22 pane.getChildren().add(imageView2); 23 24 ImageView imageView3 = new ImageView(image); 25 imageView3.setRotate(90); 26 pane.getChildren().add(imageView3); 27 28 // Create a scene and place it in the stage 29 Scene scene = new Scene(pane); 30 primaryStage.setTitle("ShowImage"); // Set the stage title 31 primaryStage.setScene(scene); // Place the scene in the read more..

  • Page - 575

    552 Chapter 14 JavaFX Basics 14.19 How do you create an Image from a URL or a filename? 14.20 How do you create an ImageView from an Image, or directly from a file or a URL? 14.21 Can you set an Image to multiple ImageView? Can you display the same ImageView multiple times? 14.10 Layout Panes JavaFX provides many types of panes for automatically laying out nodes read more..

  • Page - 576

    14.10 Layout Panes 553 Listing 14.10 gives a program that demonstrates FlowPane. The program adds labels and text fields to a FlowPane, as shown in Figure 14.16. LISTING 14.10 ShowFlowPane.java 1 import javafx.application.Application; 2 import javafx.geometry.Insets; 3 import javafx.scene.Scene; 4 import javafx.scene.control.Label; 5 import javafx.scene.control.TextField; 6 import read more..

  • Page - 577

    554 Chapter 14 JavaFX Basics The program creates a FlowPane (line 13) and sets its padding property with an Insets object (line 14). An Insets object specifies the size of the border of a pane. The constructor Insets(11, 12, 13, 14) creates an Insets with the border sizes for top (11), right (12), bottom (13), and left (14) in pixels, as shown in read more..

  • Page - 578

    14.10 Layout Panes 555 14.10.2 GridPane A GridPane arranges nodes in a grid (matrix) formation. The nodes are placed in the speci- fied column and row indices. The class diagram for GridPane is shown in Figure 14.18. FIGURE 14.18 GridPane lays out nodes in the specified cell in a grid. -alignment: ObjectProperty<Pos> -gridLinesVisible: BooleanProperty -hgap: read more..

  • Page - 579

    556 Chapter 14 JavaFX Basics 4 import javafx.geometry.Pos; 5 import javafx.scene.Scene; 6 import javafx.scene.control.Button; 7 import javafx.scene.control.Label; 8 import javafx.scene.control.TextField; 9 import javafx.scene.layout.GridPane; 10 import javafx.stage.Stage; 11 12 public class ShowGridPane extends Application { 13 @Override // Override the start method in the read more..

  • Page - 580

    14.10 Layout Panes 557 FIGURE 14.20 BorderPane places the nodes in top, bottom, left, right, and center regions. -top: ObjectProperty<Node> -right: ObjectProperty<Node> -bottom: ObjectProperty<Node> -left: ObjectProperty<Node> -center: ObjectProperty<Node> javafx.scene.layout.BorderPane The node placed in the top region (default: null). The node placed in the right region read more..

  • Page - 581

    558 Chapter 14 JavaFX Basics The program defines CustomPane that extends StackPane (line 31). The constructor of CustomPane adds a label with the specified title (line 33), sets a style for the border color, and sets a padding using insets (line 35). The program creates a BorderPane (line 13) and places five instances of CustomPane into five regions of the border read more..

  • Page - 582

    14.10 Layout Panes 559 Listing 14.12 gives a program that demonstrates HBox and VBox. The program places two buttons in an HBox and five labels in a VBox, as shown in Figure 14.24. LISTING 14.13 ShowHBoxVBox.java 1 import javafx.application.Application; 2 import javafx.geometry.Insets; 3 import javafx.scene.Scene; 4 import javafx.scene.control.Button; 5 import read more..

  • Page - 583

    560 Chapter 14 JavaFX Basics The program defines the getHBox() method. This method returns an HBox that contains two buttons and an image view (lines 30–39). The background color of the HBox is set to gold using Java CSS (line 33). The program defines the getVBox() method. This method returns a VBox that contains five labels (lines 41–55). The first label is read more..

  • Page - 584

    14.11 Shapes 561 LISTING 14.14 ShowText.java 1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.scene.layout.Pane; 4 import javafx.scene.paint.Color; 5 import javafx.geometry.Insets; FIGURE 14.25 A shape is a node. The Shape class is the root of all shape classes. Shape Node Text Rectangle Line Circle Ellipse Arc Polygon Polyline FIGURE 14.26 Text read more..

  • Page - 585

    562 Chapter 14 JavaFX Basics 6 import javafx.stage.Stage; 7 import javafx.scene.text.Text; 8 import javafx.scene.text.Font; 9 import javafx.scene.text.FontWeight; 10 import javafx.scene.text.FontPosture; 11 12 public class ShowText extends Application { 13 @Override // Override the start method in the Application class 14 public void start(Stage primaryStage) { 15 // Create read more..

  • Page - 586

    14.11 Shapes 563 12 Scene scene = new Scene(new LinePane(), 200, 200); 13 primaryStage.setTitle("ShowLine"); // Set the stage title 14 primaryStage.setScene(scene); // Place the scene in the stage 15 primaryStage.show(); // Display the stage 16 } 17 } 18 19 class LinePane extends Pane { 20 public LinePane() { 21 Line line1 = new read more..

  • Page - 587

    564 Chapter 14 JavaFX Basics 14.11.3 Rectangle A rectangle is defined by the parameters x, y, width, height, arcWidth, and arcHeight, as shown in Figure 14.31a. The rectangle’s upper-left corner point is at (x, y) and parameter aw (arcWidth) is the horizontal diameter of the arcs at the corner, and ah (arcHeight) is the vertical diameter of the arcs at the corner. The Rectangle read more..

  • Page - 588

    14.11 Shapes 565 13 Pane pane = new Pane(); 14 15 // Create rectangles and add to pane 16 Rectangle r1 = new Rectangle(25, 10, 60, 30); 17 r1.setStroke(Color.BLACK); 18 r1.setFill(Color.WHITE); 19 pane.getChildren().add(new Text(10, 27, "r1")); 20 pane.getChildren().add(r1); 21 22 Rectangle r2 = new Rectangle(25, 50, 60, 30); 23 read more..

  • Page - 589

    566 Chapter 14 JavaFX Basics LISTING 14.17 ShowEllipse.java 1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.scene.layout.Pane; 4 import javafx.scene.paint.Color; 5 import javafx.stage.Stage; 6 import javafx.scene.shape.Ellipse; 7 8 public class ShowEllipse extends Application { 9 @Override // Override the start method in the read more..

  • Page - 590

    14.11 Shapes 567 10 public void start(Stage primaryStage) { 11 // Create a pane 12 Pane pane = new Pane(); 13 14 for (int i = 0; i < 16; i++) { 15 // Create an ellipse and add it to pane 16 Ellipse e1 = new Ellipse(150, 100, 100, 50); 17 e1.setStroke(Color.color(Math.random(), Math.random(), 18 Math.random())); 19 read more..

  • Page - 591

    568 Chapter 14 JavaFX Basics LISTING 14.18 ShowArc.java 1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.scene.layout.Pane; 4 import javafx.scene.paint.Color; 5 import javafx.stage.Stage; 6 import javafx.scene.shape.Arc; 7 import javafx.scene.shape.ArcType; 8 import javafx.scene.text.Text; 9 10 public class ShowArc extends Application { 11 read more..

  • Page - 592

    14.11 Shapes 569 39 arc4.setStroke(Color.BLACK); 40 pane.getChildren().add(new Text(210, 170, "arc4: chord")); 41 pane.getChildren().add(arc4); 42 43 // Create a scene and place it in the stage 44 Scene scene = new Scene(pane, 300, 200); 45 primaryStage.setTitle("ShowArc"); // Set the stage title 46 primaryStage.setScene(scene); read more..

  • Page - 593

    570 Chapter 14 JavaFX Basics The UML diagram for the Polygon class is shown in Figure 14.39. Listing 14.19 gives an example that creates a hexagon, as shown in Figure 14.40. FIGURE 14.39 Polygon defines a polygon. +Polygon() +Polygon(double... points) +getPoints(): ObservableList<Double> javafx.scene.shape.Arc Creates an empty Polygon. Creates a Polygon with the given points. Returns read more..

  • Page - 594

    14.11 Shapes 571 8 9 public class ShowPolygon extends Application { 10 @Override // Override the start method in the Application class 11 public void start(Stage primaryStage) { 12 // Create a pane, a polygon, and place polygon to pane 13 Pane pane = new Pane(); 14 Polygon polygon = new Polygon(); 15 pane.getChildren().add(polygon); 16 read more..

  • Page - 595

    572 Chapter 14 JavaFX Basics 14.34 Write code fragments to display the lower half of a circle with radius 50 filled with the red color. 14.35 Write code fragments to display a polygon connecting the following points: (20, 40), (30, 50), (40, 90), (90, 10), (10, 30), and fill the polygon with green color. 14.36 Write code fragments to display a polyline connecting the read more..

  • Page - 596

    14.12 Case Study: The ClockPane Class 573 LISTING 14.20 DisplayClock.java 1 import javafx.application.Application; 2 import javafx.geometry.Pos; 3 import javafx.stage.Stage; 4 import javafx.scene.Scene; 5 import javafx.scene.control.Label; 6 import javafx.scene.layout.BorderPane; 7 8 public class DisplayClock extends Application { 9 @Override // Override the start method read more..

  • Page - 597

    574 Chapter 14 JavaFX Basics For simplicity in computing the angles of the minute hand and hour hand, you can omit the seconds, because they are negligibly small. Therefore, the endpoints for the second hand, minute hand, and hour hand can be computed as: secondX = centerX + secondHandLength × sin(second × (2π/60)) secondY = centerY - secondHandLength × cos(second × (2π/60)) read more..

  • Page - 598

    46 /** Set a new minute */ 47 public void setMinute(int minute) { 48 this.minute = minute; 49 paintClock(); 50 } 51 52 /** Return second */ 53 public int getSecond() { 54 return second; 55 } 56 57 /** Set a new second */ 58 public void setSecond(int second) { 59 this.second = second; 60 paintClock(); read more..

  • Page - 599

    576 Chapter 14 JavaFX Basics 106 Circle circle = new Circle(centerX, centerY, clockRadius); 107 circle.setFill(Color.WHITE); 108 circle.setStroke(Color.BLACK); 109 Text t1 = new Text(centerX - 5, centerY - clockRadius + 12, "12"); 110 Text t2 = new Text(centerX - clockRadius + 3, centerY + 5, "9"); 111 Text read more..

  • Page - 600

    Chapter Summary 577 The second hand, minute hand, and hour hand are the lines created in lines  114–139. The paintClock() method places all these shapes in the pane using the addAll method in a list (line 142). Because the paintClock() method is invoked whenever a new property (hour, minute, second, w, and h) is set (lines 27, 38, 49, 60, 71, 82, 95), before read more..

  • Page - 601

    578 Chapter 14 JavaFX Basics 10. A FlowPane arranges the nodes in the pane horizontally from left to right or vertically from top to bottom in the order in which they were added. A GridPane arranges nodes in a grid (matrix) formation. The nodes are placed in the specified column and row indi- ces. A BorderPane can place nodes in five regions: top, bottom, left, read more..

  • Page - 602

    Programming Exercises 579 14.5 (Characters around circle) Write a program that displays a string Welcome to Java around the circle, as shown in Figure 14.44b. Hint: Y ou need to display each character in the right location with appropriate rotation using a loop. *14.6 (Game: display a checkerboard) Write a program that displays a checkerboard in which each white and black cell read more..

  • Page - 603

    580 Chapter 14 JavaFX Basics *14.11 (Paint a smiley face) Write a program that paints a smiley face, as shown in Figure 14.46a. FIGURE 14.46 (a) Exercise 14.11 paints a smiley face. (b) Exercise 14.12 paints a bar chart. (c) Exercise 14.13 paints a pie chart. (a) (b) (c) FIGURE 14.47 (a) Exercise 14.14 paints a rectanguloid. (b) Exercise 14.15 paints a STOP sign. (c) read more..

  • Page - 604

    Programming Exercises 581 *14.16 (Display a 3 * 3 grid) Write a program that displays a 3 * 3 grid, as shown in Figure 14.47c. Use red color for v ertical lines and blue for horizontals. The lines are automatically resized when the window is resized. 14.17 (Game: hangman) Write a program that displays a drawing for the popular hang- man game, as shown in Figure 14.48a. FIGURE read more..

  • Page - 605

    582 Chapter 14 JavaFX Basics *14.21 (Two circles and their distance) Write a program that draws two filled circles with radius 15 pixels, centered at random locations, with a line connecting the two circles. The distance between the two centers is displayed on the line, as shown in Figure 14.49b. *14.22 (Connect two circles) Write a program that draws two circles with read more..

  • Page - 606

    Programming Exercises 583 *14.25 (Random points on a circle) Modify Programming Exercise 4.6 to create five random points on a circle, form a polygon by connecting the points clockwise, and display the circle and the polygon, as shown in Figure 14.51b. Section 14.12 14.26 (Use the ClockPane class) Write a program that displays two clocks. The hour, minute, and second values read more..

  • Page - 607

    This page intentionally left blank read more..

  • Page - 608

    EVENT-DRIVEN PROGRAMMING AND  ANIMATIONS Objectives ■ To get a taste of event-driven programming (§15.1). ■ To describe events, event sources, and event classes (§15.2). ■ To define handler classes, register handler objects with the source object, and write the code to handle events (§15.3). ■ To define handler classes using inner classes (§15.4). ■ To define handler classes read more..

  • Page - 609

    586 Chapter 15 Event-Driven Programming and Animations 15.1 Introduction You can write code to process events such as a button click, mouse movement, and keystrokes. Suppose you wish to write a GUI program that lets the user enter a loan amount, annual interest rate, and number of years and click the Calculate button to obtain the monthly payment and total payment, as read more..

  • Page - 610

    15.1 Introduction 587 The EventHandler<ActionEvent> interface contains the handle(ActionEvent) method for processing the action event. Your handler class must override this method to respond to the event. Listing 15.1 gives the code that processes the ActionEvent on the two buttons. When you click the OK button, the message “OK button clicked” is displayed. When you click the read more..

  • Page - 611

    588 Chapter 15 Event-Driven Programming and Animations OKHandlerClass is invoked to process the event. The object handler2 is an instance of CancelHandlerClass (line 20), which is registered with the button btCancel in line 21. When the Cancel button is clicked, the handle(ActionEvent) method (line 41) in CancelHandlerClass is invoked to process the event. You now have read more..

  • Page - 612

    15.3 Registering Handlers and Handling Events 589 15.1 What is an event source object? What is an event object? Describe the relationship between an event source object and an event object. 15.2 Can a button fire a MouseEvent? Can a button fire a KeyEvent? Can a button fire an ActionEvent? 15.3 Registering Handlers and Handling Events A handler is an object that must be read more..

  • Page - 613

    590 Chapter 15 Event-Driven Programming and Animations the handler class implements EventHandler<ActionEvent> in line 34. The source object invokes setOnAction(handler) to register a handler, as follows: Button btOK = new Button("OK"); // Line 16 in Listing 15.1 OKHandlerClass handler1 = new OKHandlerClass(); // Line 18 in Listing 15.1 btOK.setOnAction(handler1); // Line 19 read more..

  • Page - 614

    15.3 Registering Handlers and Handling Events 591 5 import javafx.scene.layout.StackPane; 6 import javafx.scene.layout.HBox; 7 import javafx.scene.layout.BorderPane; 8 import javafx.scene.paint.Color; 9 import javafx.scene.shape.Circle; 10 import javafx.stage.Stage; 11 12 public class ControlCircleWithoutEventHandling extends Application { 13 @Override // Override the start method in the read more..

  • Page - 615

    592 Chapter 15 Event-Driven Programming and Animations LISTING 15.3 ControlCircle.java 1 import javafx.application.Application; 2 import javafx.event.ActionEvent; 3 import javafx.event.EventHandler; 4 import javafx.geometry.Pos; 5 import javafx.scene.Scene; 6 import javafx.scene.control.Button; 7 import javafx.scene.layout.StackPane; 8 import javafx.scene.layout.HBox; 9 import read more..

  • Page - 616

    15.4 Inner Classes 593 59 60 public void enlarge() { 61 circle.setRadius(circle.getRadius() + 2); 62 } 63 64 public void shrink() { 65 circle.setRadius(circle.getRadius() > 2 ? 66 circle.getRadius() - 2 : circle.getRadius()); 67 } 68 } As an exercise, add the code for handling the Shrink button to display a smaller circle read more..

  • Page - 617

    594 Chapter 15 Event-Driven Programming and Animations a class as an inner class if it is used only by its outer class. An inner class has the following features: ■ An inner class is compiled into a class named OuterClassName$InnerClassName. class. For example, the inner class A in Test is compiled into Test$A.class in Figure 15.7b. ■ An inner class can read more..

  • Page - 618

    15.5 Anonymous Inner Class Handlers 595 The syntax for an anonymous inner class is shown below new SuperClassName/InterfaceName() { // Implement or override methods in superclass or interface // Other methods if necessary } Since an anonymous inner class is a special kind of inner class, it is treated like an inner class with the following features: ■ An anonymous inner read more..

  • Page - 619

    596 Chapter 15 Event-Driven Programming and Animations 6 import javafx.scene.control.Button; 7 import javafx.scene.layout.HBox; 8 import javafx.stage.Stage; 9 10 public class AnonymousHandlerDemo extends Application { 11 @Override // Override the start method in the Application class 12 public void start(Stage primaryStage) { 13 // Hold two buttons in an HBox 14 read more..

  • Page - 620

    15.6 Simplifying Event Handling Using Lambda Expressions 597 The anonymous inner classes in this example are compiled into AnonymousHandlerDemo$1.class, AnonymousHandlerDemo$2.class, AnonymousHandlerDemo$3.class, and AnonymousHandlerDemo$4.class. 15.9 If class A is an inner class in class B, what is the .class file for A? If class B contains two anonymous inner classes, what are the read more..

  • Page - 621

    598 Chapter 15 Event-Driven Programming and Animations The data type for a parameter may be explicitly declared or implicitly inferred by the com- piler. The parentheses can be omitted if there is only one parameter without an explicit data type. In the preceding example, the lambda expression is as follows e -> { // Code for processing event e } The compiler treats a read more..

  • Page - 622

    15.6 Simplifying Event Handling Using Lambda Expressions 599 36 37 // Create a scene and place it in the stage 38 Scene scene = new Scene(hBox, 300, 50); 39 primaryStage.setTitle("LambdaHandlerDemo"); // Set title 40 primaryStage.setScene(scene); // Place the scene in the stage 41 primaryStage.show(); // Display the stage 42 read more..

  • Page - 623

    600 Chapter 15 Event-Driven Programming and Animations 15.7 Case Study: Loan Calculator This case study develops a loan calculator using event-driven programming with GUI controls. Now, we will write the program for the loan-calculator problem presented at the beginning of this chapter. Here are the major steps in the program: 1. Create the user interface, as shown in Figure 15.9. read more..

  • Page - 624

    15.7 Case Study: Loan Calculator 601 23 gridPane.setHgap(5); 24 gridPane.setVgap(5); 25 gridPane.add(new Label("Annual Interest Rate:"), 0, 0); 26 gridPane.add(tfAnnualInterestRate, 1, 0); 27 gridPane.add(new Label("Number of Years:"), 0, 1); 28 gridPane.add(tfNumberOfYears, 1, 1); 29 gridPane.add(new read more..

  • Page - 625

    602 Chapter 15 Event-Driven Programming and Animations computing the loan payments. This class was introduced in Listing 10.2, Loan.java. Invok- ing loan.getMonthlyPayment() returns the monthly payment for the loan (line 71). The String.format method, introduced in Section 10.10.7, is used to format a number into a desirable format and returns it as a string (lines 70, 72). Invoking the setText read more..

  • Page - 626

    15.9 Key Events 603 4 import javafx.scene.text.Text; 5 import javafx.stage.Stage; 6 7 public class MouseEventDemo extends Application { 8 @Override // Override the start method in the Application class 9 public void start(Stage primaryStage) { 10 // Create a pane and set its properties 11 Pane pane = new Pane(); 12 Text text = new read more..

  • Page - 627

    604 Chapter 15 Event-Driven Programming and Animations key-released events, getCode() returns the value as defined in the table, getText() returns a string that describes the key code, and getCharacter() returns an empty string. For the key-typed event, getCode() returns UNDEFINED and getCharacter() returns the Unicode character or a sequence of characters associated with the read more..

  • Page - 628

    15.9 Key Events 605 21 default: 22 if (Character.isLetterOrDigit(e.getText().charAt(0))) 23 text.setText(e.getText()); 24 } 25 }); 26 27 // Create a scene and place it in the stage 28 Scene scene = new Scene(pane); 29 primaryStage.setTitle("KeyEventDemo"); // Set the stage title 30 primaryStage.setScene(scene); // Place the read more..

  • Page - 629

    606 Chapter 15 Event-Driven Programming and Animations 28 29 circlePane.setOnMouseClicked(e -> { 30 if (e.getButton() == MouseButton.PRIMARY) { 31 circlePane.enlarge(); 32 } 33 else if (e.getButton() == MouseButton.SECONDARY) { 34 circlePane.shrink(); 35 } 36 }); 37 38 read more..

  • Page - 630

    15.10 Listeners for Observable Objects 607 the value is changed in the Observable object, the listener is notified by invoking its invalidated(Observable  o) method. Every binding property is an instance of Observable. Listing  15.10 gives an example of observing and handling a change in a DoubleProperty object balance. LISTING 15.10 ObservablePropertyDemo.java 1 import read more..

  • Page - 631

    608 Chapter 15 Event-Driven Programming and Animations 15 Label lblCurrentTime = new Label(timeString); 16 17 // Place clock and label in border pane 18 BorderPane pane = new BorderPane(); 19 pane.setCenter(clock); 20 pane.setBottom(lblCurrentTime); 21 BorderPane.setAlignment(lblCurrentTime, Pos.TOP_CENTER); 22 23 // Create a scene and place read more..

  • Page - 632

    15.11 Animation 609 The autoReverse is a Boolean property that indicates whether an animation will reverse its direction on the next cycle. The cycleCount indicates the number of the cycles for the animation. You can use the constant Timeline.INDEFINTE to indicate an indefinite num- ber of cycles. The rate defines the speed of the animation. A negative rate value indicates read more..

  • Page - 633

    610 Chapter 15 Event-Driven Programming and Animations an instance of Duration, the add, subtract, multiply, and divide methods to perform arithmetic operations, and the toHours(), toMinutes(), toSeconds(), and toMillis() to return the number of hours, minutes, seconds, and milliseconds in this duration. You can also use compareTo to compare two durations. The constants NONE and read more..

  • Page - 634

    15.11 Animation 611 48 primaryStage.setScene(scene); // Place the scene in the stage 49 primaryStage.show(); // Display the stage 50 } 51 } FIGURE 15.17 The PathTransition animates a rectangle moving along the circle. (a) (b) The program creates a pane (line 16), a rectangle (line 19), and a circle (line 23). The circle and rectangle are placed read more..

  • Page - 635

    612 Chapter 15 Event-Driven Programming and Animations 22 new Line(100, 200, 100, 0), imageView); 23 pt.setCycleCount(5); 24 pt.play(); // Start animation 25 26 // Create a scene and place it in the stage 27 Scene scene = new Scene(pane, 250, 200); 28 primaryStage.setTitle("FlagRisingAnimation"); // Set the stage title 29 read more..

  • Page - 636

    15.11 Animation 613 9 import javafx.util.Duration; 10 11 public class FadeTransitionDemo extends Application { 12 @Override // Override the start method in the Application class 13 public void start(Stage primaryStage) { 14 // Place an ellipse to the pane 15 Pane pane = new Pane(); 16 Ellipse ellipse = new Ellipse(10, 10, 100, 50); 17 read more..

  • Page - 637

    614 Chapter 15 Event-Driven Programming and Animations 15.11.3 Timeline PathTransition and FadeTransition define specialized animations. The Timeline class can be used to program any animation using one or more KeyFrames. Each KeyFrame is executed sequentially at a specified time interval. Timeline inherits from Animation. You can construct a Timeline using the constructor new read more..

  • Page - 638

    15.11 Animation 615 45 } 46 }); 47 48 // Create a scene and place it in the stage 49 Scene scene = new Scene(pane, 250, 250); 50 primaryStage.setTitle("TimelineDemo"); // Set the stage title 51 primaryStage.setScene(scene); // Place the scene in the stage 52 primaryStage.show(); // Display the stage 53 read more..

  • Page - 639

    616 Chapter 15 Event-Driven Programming and Animations 22 new KeyFrame(Duration.millis(1000), eventHandler)); 23 animation.setCycleCount(Timeline.INDEFINITE); 24 animation.play(); // Start animation 25 26 // Create a scene and place it in the stage 27 Scene scene = new Scene(clock, 250, 50); 28 primaryStage.setTitle("ClockAnimation"); // Set the stage title read more..

  • Page - 640

    15.12 Case Study: Bouncing Ball 617 FIGURE 15.23 BounceBallControl contains BallPane. 11 BallPane -x: double -y: double -dx: double -dy: double -radius: double -circle: Circle -animation: Timeline +BallPane() +play(): void +pause(): void +increaseSpeed(): void +decreaseSpeed(): void +rateProperty(): DoubleProperty +moveBall(): void javafx.scene.layout.Pane javafx.application.Application BounceBallControl Here are the read more..

  • Page - 641

    618 Chapter 15 Event-Driven Programming and Animations 19 20 // Create an animation for moving the ball 21 animation = new Timeline( 22 new KeyFrame(Duration.millis(50), e -> moveBall())); 23 animation.setCycleCount(Timeline.INDEFINITE); 24 animation.play(); // Start animation 25 } 26 27 public void play() { 28 animation.play(); 29 } 30 31 public void read more..

  • Page - 642

    15.12 Case Study: Bouncing Ball 619 method (lines 44–46) returns a binding property value for rate. This binding property is useful for binding the rate in future applications in the next chapter. LISTING 15.18 BounceBallControl.java 1 import javafx.application.Application; 2 import javafx.stage.Stage; 3 import javafx.scene.Scene; 4 import javafx.scene.input.KeyCode; 5 6 public read more..

  • Page - 643

    620 Chapter 15 Event-Driven Programming and Animations CHAPTER SUMMARY 1. The root class of the JavaFX event classes is javafx.event.Event, which is a sub- class of java.util.EventObject. The subclasses of Event deal with special types of events, such as action events, window events, mouse events, and key events. If a node can fire an event, any subclass of the node can read more..

  • Page - 644

    Programming Exercises 621 QUIZ Answer the quiz for this chapter online at www.cs.armstrong.edu/liang/intro10e/quiz.html . PROGRAMMING EXERCISES Sections 15.2–15.7 *15.1 (Pick four cards) Write a program that lets the user click the Refresh button to display four cards from a deck of 52 cards, as shown in Figure 15.24a. (See the hint in Programming Exercise 14.3 on how to obtain four read more..

  • Page - 645

    622 Chapter 15 Event-Driven Programming and Animations Use text fields for the investment amount, number of years, and annual interest rate. Display the future amount in a text field when the user clicks the Calculate button, as shown in Figure 15.25b. Sections 15.8 and 15.9 **15.6 (Alternate two messages) Write a program to display the text Java is fun and Java is read more..

  • Page - 646

    Programming Exercises 623 **15.13 (Geometry: inside a rectangle?) Write a program that draws a fixed rectangle centered at (100, 60) with width 100 and height 40. Whenever the mouse is moved, display a message indicating whether the mouse point is inside the rec- tangle at the mouse point or outside of it, as shown in Figure 15.27b. To detect whether a point is inside a read more..

  • Page - 647

    624 Chapter 15 Event-Driven Programming and Animations **15.18 (Move a rectangle using mouse) Write a program that displays a rectangle. You can point the mouse inside the rectangle and drag (i.e., move with mouse pressed) the rectangle wherever the mouse goes. The mouse point becomes the center of the rectangle. **15.19 (Game: eye-hand coordination) Write a program that displays read more..

  • Page - 648

    Programming Exercises 625 **15.25 (Animation: ball on curve) Write a program that animates a ball moving along a sine curve, as shown in Figure 15.32. When the ball gets to the right border, it starts over from the left. Enable the user to resume/pause the animation with a click on the left/right mouse button. FIGURE 15.32 The program animates a ball traveling along a sine curve. read more..

  • Page - 649

    626 Chapter 15 Event-Driven Programming and Animations two seconds. The slides are displayed in order. When the last slide finishes, the first slide is redisplayed, and so on. Click to pause if the animation is currently playing. Click to resume if the animation is currently paused. **15.31 (Geometry: pendulum) Write a program that animates a pendulum swinging, as shown in Figure 15.35. Press the UP read more..

  • Page - 650

    Programming Exercises 627 ***15.33 (Game: bean-machine animation) Write a program that animates the bean machine introduced in Programming Exercise 7.21. The animation terminates after ten balls are dropped, as shown in Figure 15.36b and c. ***15.34 (Simulation: self-avoiding random walk) A self-avoiding walk in a lattice is a path from one point to another that does not visit the read more..

  • Page - 651

    This page intentionally left blank read more..

  • Page - 652

    JAVAFX UI CONTROLS AND MULTIMEDIA Objectives ■ To create graphical user interfaces with various user-interface controls (§§16.2–16.11). ■ To create a label with text and graphic using the Label class and explore properties in the abstract Labeled class (§16.2). ■ To create a button with text and graphic using the Button class and set a handler using the setOnAction read more..

  • Page - 653

    630 Chapter 16 JavaFX UI Controls and Multimedia 16.1 Introduction JavaFX provides many UI controls for developing a comprehensive user interface. A graphical user interface (GUI) makes a system user-friendly and easy to use. Creating a GUI requires creativity and knowledge of how UI controls work. Since the UI controls in JavaFX are very flexible and versatile, you can create read more..

  • Page - 654

    16.2 Labeled and Label 631 6 import javafx.scene.image.Image; 7 import javafx.scene.image.ImageView; 8 import javafx.scene.layout.HBox; 9 import javafx.scene.layout.StackPane; 10 import javafx.scene.paint.Color; 11 import javafx.scene.shape.Circle; 12 import javafx.scene.shape.Rectangle; 13 import javafx.scene.shape.Ellipse; 14 15 public class LabelWithGraphic extends Application { 16 @Override // read more..

  • Page - 655

    632 Chapter 16 JavaFX UI Controls and Multimedia 34 Ellipse ellipse = new Ellipse(50, 50, 50, 25); 35 ellipse.setStroke(Color.GREEN); 36 ellipse.setFill(Color.WHITE); 37 StackPane stackPane = new StackPane(); 38 stackPane.getChildren().addAll(ellipse, new Label("JavaFX")); 39 Label lb5 = new Label("A pane inside a read more..

  • Page - 656

    16.3 Button 633 Listing 16.2 gives a program that uses the buttons to control the movement of a text, as shown in Figure 16.6. LISTING 16.2 ButtonDemo.java 1 import javafx.application.Application; 2 import javafx.stage.Stage; 3 import javafx.geometry.Pos; 4 import javafx.scene.Scene; 5 import javafx.scene.control.Button; 6 import javafx.scene.image.ImageView; 7 import read more..

  • Page - 657

    634 Chapter 16 JavaFX UI Controls and Multimedia 36 } 37 38 @Override // Override the start method in the Application class 39 public void start(Stage primaryStage) { 40 // Create a scene and place it in the stage 41 Scene scene = new Scene(getPane(), 450, 200); 42 primaryStage.setTitle("ButtonDemo"); // Set the stage title 43 read more..

  • Page - 658

    When a check box is clicked (checked or unchecked), it fires an ActionEvent. To see if a check box is selected, use the isSelected() method. We now write a program that adds two check boxes named Bold and Italic to the pre- ceding example to let the user specify whether the message is in bold or italic, as shown in Figure 16.8. FIGURE 16.7 CheckBox contains the read more..

  • Page - 659

    636 Chapter 16 JavaFX UI Controls and Multimedia 15 16 Font fontBoldItalic = Font.font("Times New Roman", 17 FontWeight.BOLD, FontPosture.ITALIC, 20); 18 Font fontBold = Font.font("Times New Roman", 19 FontWeight.BOLD, FontPosture.REGULAR, 20); 20 Font fontItalic = Font.font("Times New Roman", 21 read more..

  • Page - 660

    16.5 RadioButton Radio buttons, also known as option buttons, enable the user to choose a single item from a group of choices. In appearance radio buttons resemble check boxes, but check boxes display a square that is either checked or blank, whereas radio buttons display a circle that is either filled (if selected) or blank (if not selected). RadioButton is a subclass of read more..

  • Page - 661

    638 Chapter 16 JavaFX UI Controls and Multimedia We now give a program that adds three radio buttons named Red, Green, and Blue to the preceding example to let the user choose the color of the message, as shown in Figure 16.10. FIGURE 16.10 The program demonstrates using radio buttons. VBox containing three radio buttons Again there are at least two approaches to writing read more..

  • Page - 662

    38 } 39 }); 40 41 rbBlue.setOnAction(e -> { 42 if (rbBlue.isSelected()) { 43 text.setFill(Color.BLUE); 44 } 45 }); 46 47 return pane; 48 } 49 } RadioButtonDemo extends CheckBoxDemo and overrides the getPane() method (line 10). The new getPane() method invokes the getPane() method read more..

  • Page - 663

    640 Chapter 16 JavaFX UI Controls and Multimedia 3 import javafx.scene.control.Label; 4 import javafx.scene.control.TextField; 5 import javafx.scene.layout.BorderPane; 6 7 public class TextFieldDemo extends RadioButtonDemo { 8 @Override // Override the getPane() method in the super class 9 protected BorderPane getPane() { 10 BorderPane pane = super.getPane(); read more..

  • Page - 664

    TextFieldDemo extends RadioButtonDemo (line 7) and adds a label and a text field to let the user enter a new text (lines 12–19). After you set a new text in the text field and press the Enter key, a new message is displayed (line 22). Pressing the Enter key on the text field triggers an action event. Note If a text field is used for entering a password, read more..

  • Page - 665

    642 Chapter 16 JavaFX UI Controls and Multimedia TextArea provides scrolling, but often it is useful to create a ScrollPane object to hold an instance of TextArea and let ScrollPane handle scrolling for TextArea, as follows: // Create a scroll pane to hold text area ScrollPane scrollPane = new ScrollPane(taNote); Tip You can place any node in a ScrollPane. ScrollPane read more..

  • Page - 666

    4 import javafx.scene.control.ScrollPane; 5 import javafx.scene.control.TextArea; 6 import javafx.scene.image.ImageView; 7 import javafx.scene.layout.BorderPane; 8 import javafx.scene.text.Font; 9 10 public class DescriptionPane extends BorderPane { 11 /** Label for displaying an image and a title */ 12 private Label lblImageTitle = new Label(); 13 14 /** Text area for displaying read more..

  • Page - 667

    644 Chapter 16 JavaFX UI Controls and Multimedia LISTING 16.7 TextAreaDemo.java 1 import javafx.application.Application; 2 import javafx.stage.Stage; 3 import javafx.scene.Scene; 4 import javafx.scene.image.ImageView; 5 6 public class TextAreaDemo extends Application { 7 @Override // Override the start method in the Application class 8 public void start(Stage read more..

  • Page - 668

    16.8 ComboBox 645 ComboBox inherits from ComboBoxBase. ComboBox can fire an ActionEvent. Whenever an item is selected, an ActionEvent is fired. ObservableList is a subinterface of java.util.List. So you can apply all the methods defined in List for an ObservableList. For convenience, JavaFX provides the static method FXCollections.observableArrayList(arrayOfElements) for creating an read more..

  • Page - 669

    646 Chapter 16 JavaFX UI Controls and Multimedia LISTING 16.8 ComboBoxDemo.java 1 import javafx.application.Application; 2 import javafx.stage.Stage; 3 import javafx.collections.FXCollections; 4 import javafx.collections.ObservableList; 5 import javafx.scene.Scene; 6 import javafx.scene.control.ComboBox; 7 import javafx.scene.control.Label; 8 import javafx.scene.image.ImageView; 9 import read more..

  • Page - 670

    16.9 ListView 647 59 cbo.setPrefWidth(400); 60 cbo.setValue("Canada"); 61 62 ObservableList<String> items = 63 FXCollections.observableArrayList(flagTitles); 64 cbo.getItems().addAll(items); 65 pane.setCenter(descriptionPane); 66 67 // Display the selected country 68 cbo.setOnAction(e -> setDisplay(items.indexOf(cbo.getValue()))); 69 70 // Create a scene and place read more..

  • Page - 671

    648 Chapter 16 JavaFX UI Controls and Multimedia The getSelectionModel() method returns an instance of SelectionModel, which contains the methods for setting a selection mode and obtaining selected indices and items. The selection mode is defined in one of the two constants SelectionMode.MULTIPLE and SelectionMode.SINGLE, which indicates whether a single item or multiple items can read more..

  • Page - 672

    16.9 ListView 649 System.out.println("Selected items: " + lv.getSelectionModel().getSelectedItems()); } }); This anonymous inner class can be simplified using a lambda expression as follows: lv.getSelectionModel().selectedItemProperty().addListener(ov -> { System.out.println("Selected indices: " read more..

  • Page - 673

    650 Chapter 16 JavaFX UI Controls and Multimedia 13 // Declare an array of Strings for flag titles 14 private String[] flagTitles = {"Canada", "China", "Denmark", 15 "France", "Germany", "India", "Norway", "United Kingdom", 16 "United States of America"}; 17 18 // Declare an ImageView array for the national flags of 9 read more..

  • Page - 674

    16.10 ScrollBar 651 16.27 How do you create an observable list with an array of strings? 16.28 How do you set the orientation in a list view? 16.29 What selection modes are available for a list view? What is the default selection mode? How do you set a selection mode? 16.30 How do you obtain the selected items and selected indices? 16.10 ScrollBar ScrollBar is a read more..

  • Page - 675

    652 Chapter 16 JavaFX UI Controls and Multimedia When the user changes the value of the scroll bar, it notifies the listener of the change. You can register a listener on the scroll bar’s valueProperty for responding to this change as follows: ScrollBar sb = new ScrollBar(); sb.valueProperty().addListener(ov -> { System.out.println("old value: read more..

  • Page - 676

    16.10 ScrollBar 653 20 Pane paneForText = new Pane(); 21 paneForText.getChildren().add(text); 22 23 // Create a border pane to hold text and scroll bars 24 BorderPane pane = new BorderPane(); 25 pane.setCenter(paneForText); 26 pane.setBottom(sbHorizontal); 27 pane.setRight(sbVertical); 28 29 // Listener for horizontal scroll bar read more..

  • Page - 677

    654 Chapter 16 JavaFX UI Controls and Multimedia 16.11 Slider Slider is similar to ScrollBar, but Slider has more properties and can appear in many forms. Figure  16.24 shows two sliders. Slider lets the user graphically select a value by sliding a knob within a bounded interval. The slider can show both major tick marks and minor tick marks between them. The number read more..

  • Page - 678

    16.11 Slider 655 LISTING 16.11 SliderDemo.java 1 import javafx.application.Application; 2 import javafx.stage.Stage; 3 import javafx.geometry.Orientation; 4 import javafx.scene.Scene; 5 import javafx.scene.control.Slider; 6 import javafx.scene.layout.BorderPane; 7 import javafx.scene.layout.Pane; 8 import javafx.scene.text.Text; 9 10 public class SliderDemo extends Application { 11 read more..

  • Page - 679

    656 Chapter 16 JavaFX UI Controls and Multimedia The code in lines 35–41 can be replaced by using binding properties as follows: text.xProperty().bind(slHorizontal.valueProperty(). multiply(paneForText.widthProperty()). divide(slHorizontal.maxProperty())); text.yProperty().bind((slVertical.maxProperty().subtract( slVertical.valueProperty()).multiply( read more..

  • Page - 680

    16.12 Case Study: Developing a Tic-Tac-Toe Game 657 The animation stops if the rate is 0. If the rate is greater than 20, the animation will be too fast. So, we purposely set the rate to a value between 0 and 20. This value is bound to the slider value (line 13). So the slider max value is set to 20 (line 12). 16.34 How do you create a horizontal slider? How do you create a vertical read more..

  • Page - 681

    658 Chapter 16 JavaFX UI Controls and Multimedia The tic-tac-toe board consists of nine cells, created using new Cell[3][3]. To determine which player’s turn it is, you can introduce a variable named whoseTurn of the char type. whoseTurn is initially 'X', then changes to 'O', and subsequently changes between 'X' and 'O' whenever a new cell is occupied. When the read more..

  • Page - 682

    16.12 Case Study: Developing a Tic-Tac-Toe Game 659 6 import javafx.scene.layout.GridPane; 7 import javafx.scene.layout.Pane; 8 import javafx.scene.paint.Color; 9 import javafx.scene.shape.Line; 10 import javafx.scene.shape.Ellipse; 11 12 public class TicTacToe extends Application { 13 // Indicate which player has a turn, initially it is the X player 14 private read more..

  • Page - 683

    660 Chapter 16 JavaFX UI Controls and Multimedia 66 67 if (cell[0][0].getToken() == token 68 && cell[1 ][1].getToken() == token 69 && cell[2 ][2].getToken() == token) { 70 return true; 71 } 72 73 if (cell[0][2].getToken() == token 74 && cell[1 ][1].getToken() == token 75 read more..

  • Page - 684

    16.12 Case Study: Developing a Tic-Tac-Toe Game 661 126 ellipse.radiusYProperty().bind( 127 this.heightProperty().divide(2).subtract(10)); 128 ellipse.setStroke(Color.BLACK); 129 ellipse.setFill(Color.WHITE); 130 131 getChildren().add(ellipse); // Add the ellipse to the pane 132 } 133 } 134 135 /* read more..

  • Page - 685

    662 Chapter 16 JavaFX UI Controls and Multimedia 16.37 When the game starts, what value is in whoseTurn? When the game is over, what value is in whoseTurn? 16.38 What happens when the user clicks on an empty cell if the game is not over? What happens when the user clicks on an empty cell if the game is over? 16.39 How does the program check whether a player read more..

  • Page - 686

    16.13 Video and Audio 663 The MediaView class is a subclass of Node that provides a view of the Media being played by a MediaPlayer. The MediaView class provides the properties for viewing the media, as shown in Figure 16.32. FIGURE 16.32 MediaView provides the properties for viewing the media. javafx.scene.media.MediaView -x: DoubleProperty -y: DoubleProperty -mediaPlayer: read more..

  • Page - 687

    664 Chapter 16 JavaFX UI Controls and Multimedia 12 import javafx.scene.media.MediaPlayer; 13 import javafx.scene.media.MediaView; 14 import javafx.util.Duration; 15 16 public class MediaDemo extends Application { 17 private static final String MEDIA_URL = 18 "http://cs.armstrong.edu/liang/common/sample.mp4"; 19 20 @Override // Override the start method in the Application class 21 read more..

  • Page - 688

    16.14 Case Study: National Flags and Anthems 665 A Media object supports live streaming. You can now download a large media file and play it in the same time. A Media object can be shared by multiple media players and different views can use the same MediaPlayer object. A play button is created (line 26) to play/pause the media (line 29). The button’s text is read more..

  • Page - 689

    666 Chapter 16 JavaFX UI Controls and Multimedia The program is given in Listing 16.15. LISTING 16.15 FlagAnthem.java 1 import javafx.application.Application; 2 import javafx.collections.FXCollections; 3 import javafx.collections.ObservableList; 4 import javafx.stage.Stage; 5 import javafx.geometry.Pos; 6 import javafx.scene.Scene; 7 import javafx.scene.control.Button; 8 import read more..

  • Page - 690

    Chapter Summary 667 58 59 HBox hBox = new HBox(10); 60 hBox.getChildren().addAll(btPlayPause, 61 new Label("Select a nation: "), cboNation); 62 hBox.setAlignment(Pos.CENTER); 63 64 // Create a pane to hold nodes 65 BorderPane pane = new BorderPane(); 66 pane.setCenter(imageView); 67 pane.setBottom(hBox); 68 69 // Create a read more..

  • Page - 691

    668 Chapter 16 JavaFX UI Controls and Multimedia 6. A ComboBox fires an action event when a new item is selected. 7. You can set a single item or multiple item selection for a ListView and add a listener for processing selected items. 8. You can use a ScrollBar or Slider to select a range of values and add a listener to the value property to respond to read more..

  • Page - 692

    Programming Exercises 669 *16.4 (Create a miles/kilometers converter) Write a program that converts miles and kilometers, as shown in Figure 16.37b. If you enter a v alue in the Mile text field and press the Enter key, the corresponding kilometer measurement is displayed in the Kilometer text field. Likewise, if you enter a value in the Kilometer text field and press the Enter read more..

  • Page - 693

    670 Chapter 16 JavaFX UI Controls and Multimedia *16.7 (Set clock time) Write a program that displays a clock and sets the time with the input from three text fields, as shown in Figure 16.38b. Use the ClockPane in Listing 14.21. Resize the clock to the center of the pane. **16.8 (Geometry: two circles intersect?) Write a program that enables the user to specify the read more..

  • Page - 694

    Programming Exercises 671 **16.11 (Create a histogram for occurrences of letters) Write a program that reads a file and displays a histogram to show the occurrences of each letter in the file, as shown in Figure 16.40b. The f ile name is entered from a text field. Pressing the Enter key on the text field causes the program to start to read and process the file and read more..

  • Page - 695

    672 Chapter 16 JavaFX UI Controls and Multimedia **16.15 (Demonstrate Label properties) Write a program to let the user dynamically set the properties contentDisplay and graphicTextGap, as shown in Figure 16.42b. *16.16 (Use ComboBox and ListView) Write a program that demonstrates selecting items in a list. The program uses a combo box to specify a selection mode, as shown in read more..

  • Page - 696

    Programming Exercises 673 *16.21 (Count-down stopwatch) Write a program that allows the user to enter time in seconds in the text field and press the Enter key to count down the seconds, as shown in Figure  16.45d. The remaining seconds are redisplayed every one second. When the seconds are expired, the program starts to play music continuously. 16.22 (Play, loop, and read more..

  • Page - 697

    674 Chapter 16 JavaFX UI Controls and Multimedia **16.23 (Create an image animator with audio) Create animation in Figure  16.46b to meet the following requirements: ■ Allow the user to specify the animation speed in a text field. ■ Get the number of iamges and image’s file-name prefix from the user. For example, if the user enters n for the number of read more..

  • Page - 698

    Programming Exercises 675 description8.txt under the text directory for the nine countries Canada, China, Denmark, France, Germany, India, Norway, United Kingdom, and United States, in this order. **16.28 (Slide show) Programming Exercise 15.30 developed a slide show using images. Rewrite that program to develop a slide show using text files. Suppose ten text files named read more..

  • Page - 699

    676 Chapter 16 JavaFX UI Controls and Multimedia ***16.31 (Game: connect four) Programming Exercise 8.20 enables two players to play the connect-four game on the console. Rewrite a GUI version for the program, as shown in Figure 16.49c. The program enables two players to place red and yellow discs in turn. To place a disk, the player needs to click an available cell. An available read more..

  • Page - 700

    BINARY I/O Objectives ■ To discover how I/O is processed in Java (§17.2). ■ To distinguish between text I/O and binary I/O (§17.3). ■ To read and write bytes using FileInputStream and FileOutputStream (§17.4.1). ■ To filter data using the base classes FilterInputStream and FilterOutputStream (§17.4.2). ■ To read and write primitive values and strings using read more..

  • Page - 701

    678 Chapter 17 Binary I/O 17.1 Introduction Java provides many classes for performing text I/O and binary I/O. Files can be classified as either text or binary. A file that can be processed (read, created, or modified) using a text editor such as Notepad on Windows or vi on UNIX is called a text file. All the other files are called binary files. You cannot read read more..

  • Page - 702

    17.3 Text I/O vs. Binary I/O 679 17.1 What is a text file and what is a binary file? Can you view a text file or a binary file using a text editor? 17.2 How do you read or write text data in Java? What is a stream? 17.3 Text I/O vs. Binary I/O Binary I/O does not involve encoding or decoding and thus is more efficient than text I/O. Computers do not read more..

  • Page - 703

    680 Chapter 17 Binary I/O hex) and for character 9 is 57 (0x39 in hex). Thus, to write the characters 199, three bytes— 0x31, 0x39, and 0x39—are sent to the output, as shown in Figure 17.2a. Binary I/O does not require conversions. If you write a numeric value to a file using binary I/O, the exact value in the memory is copied into the file. For example, read more..

  • Page - 704

    17.4 Binary I/O Classes 681 17.4.1 FileInputStream/FileOutputStream FileInputStream/FileOutputStream is for reading/writing bytes from/to files. All the methods in these classes are inherited from InputStream and OutputStream. FileInputStream/FileOutputStream does not introduce new methods. To construct a FileInputStream, use the constructors shown in Figure 17.6. A java.io.FileNotFoundException will read more..

  • Page - 705

    682 Chapter 17 Binary I/O Almost all the methods in the I/O classes throw java.io.IOException. Therefore, you have to declare to throw java.io.IOException in the method or place the code in a try- catch block, as shown below: IOException FIGURE 17.7 FileOutputStream outputs a stream of bytes to a file. Creates a FileOutputStream from a File object. Creates a read more..

  • Page - 706

    17.4 Binary I/O Classes 683 15 // Create an input stream for the file 16 FileInputStream input = new FileInputStream("temp.dat"); 17 ) { 18 // Read values from the file 19 int value; 20 while ((value = input.read()) != -1) 21 System.out.print(value + " "); 22 } 23 } 24 } input stream input FIGURE 17.8 A read more..

  • Page - 707

    684 Chapter 17 Binary I/O new PrintWriter(new FileOutputStream("temp.txt", true)); If temp.txt does not exist, it is created. If temp.txt already exists, new data are appended to the file. 17.4.2 FilterInputStream/FilterOutputStream Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can be used only read more..

  • Page - 708

    17.4 Binary I/O Classes 685 of ASCII characters, since an ASCII code is stored only in the lower byte of a Unicode. If a string consists of non-ASCII characters, you have to use the writeChars method to write the string. The writeUTF(String s) method writes two bytes of length information to the output stream, followed by the modified UTF-8 representation of every read more..

  • Page - 709

    686 Chapter 17 Binary I/O The following statements create data streams. The first statement creates an input stream for the file in.dat; the second statement creates an output stream for the file out.dat. DataInputStream input = new DataInputStream(new FileInputStream("in.dat")); DataOutputStream output = new DataOutputStream(new FileOutputStream("out.dat")); Listing 17.2 read more..

  • Page - 710

    17.4 Binary I/O Classes 687 outputs the bytes to an output stream. You can view DataInputStream/FileInputStream and DataOutputStream/FileOutputStream working in a pipe line as shown in Figure 17.11. FIGURE 17.11 DataInputStream filters an input stream of byte to data and DataOutputStream converts data into a stream of bytes. DataInputStream FileInputStream External File 01000110011 … read more..

  • Page - 711

    688 Chapter 17 Binary I/O The program writes three double values to the file using DataOutputStream (lines 6–11) and reads the data using DataInputStream (lines 13–17). When reading past the end of the file, an EOFException is thrown. The exception is caught in line 19. 17.4.4 BufferedInputStream/BufferedOutputStream BufferedInputStream/BufferedOutputStream can be used to speed read more..

  • Page - 712

    17.4 Binary I/O Classes 689 If no buffer size is specified, the default size is 512 bytes. You can improve the perfor- mance of the TestDataStream program in Listing 17.2 by adding buffers in the stream in lines 6–7 and lines 19–20, as follows: DataOutputStream output = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("temp.dat"))); DataInputStream read more..

  • Page - 713

    690 Chapter 17 Binary I/O public static void main(String[] args) { try ( FileInputStream fis = new FileInputStream("test.dat"); ) { } catch (IOException ex) { ex.printStackTrace(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } } 17.18 Suppose you run the following program on Windows using read more..

  • Page - 714

    17.5 Case Study: Copying Files 691 17.5 Case Study: Copying Files This section develops a useful utility for copying files. In this section, you will learn how to write a program that lets users copy files. The user needs to provide a source file and a target file as command-line arguments using the command: java Copy source target The program copies the source file to read more..

  • Page - 715

    692 Chapter 17 Binary I/O 21 System.exit(2); 22 } 23 24 // Check if target file exists 25 File targetFile = new File(args[1]); 26 if (targetFile.exists()) { 27 System.out.println("Target file " + args[1] 28 + " already exists"); 29 System.exit(3); 30 } 31 32 try ( 33 // read more..

  • Page - 716

    17.6 Object I/O 693 for objects in addition to primitive-type values and strings. Since ObjectInputStream/ ObjectOutputStream contains all the functions of DataInputStream/ DataOutputStream, you can replace DataInputStream/DataOutputStream completely with ObjectInputStream/ObjectOutputStream. ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants, as shown in read more..

  • Page - 717

    694 Chapter 17 Binary I/O 4 public static void main(String[] args) throws IOException { 5 try ( // Create an output stream for file object.dat 6 ObjectOutputStream output = 7 new ObjectOutputStream(new FileOutputStream("object.dat")); 8 ) { 9 // Write a string, double value, and object to the file 10 output.writeUTF("John"); read more..

  • Page - 718

    17.6 Object I/O 695 17.6.1 The Serializable Interface Not every object can be written to an output stream. Objects that can be so written are said to be serializable. A serializable object is an instance of the java.io.Serializable inter- face, so the object’s class must implement Serializable. The Serializable interface is a marker interface. Since it has no methods, you read more..

  • Page - 719

    696 Chapter 17 Binary I/O same object is written again. When the objects are read back, their references are the same since only one object is actually created in the memory. 17.6.2 Serializing Arrays An array is serializable if all its elements are serializable. An entire array can be saved into a file using writeObject and later can be restored using readObject. Listing read more..

  • Page - 720

    17.7 Random-Access Files 697 17.26 If you serialize two objects of the same type, will they take the same amount of space? If not, give an example. 17.27 Is it true that any instance of java.io.Serializable can be successfully serial- ized? Are the static variables in an object serialized? How do you mark an instance variable not to be serialized? 17.28 Can you write read more..

  • Page - 721

    698 Chapter 17 Binary I/O Tip If the file is not intended to be modified, open it with the r mode. This prevents unin- tentional modification of the file. A random-access file consists of a sequence of bytes. A special marker called a file pointer is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When read more..

  • Page - 722

    17.7 Random-Access Files 699 RandomAccessFile. A large case study of using RandomAccessFile to organize an address book is given in Supplement VI.D. LISTING 17.8 TestRandomAccessFile.jav 1 import java.io.*; 2 3 public class TestRandomAccessFile { 4 public static void main(String[] args) throws IOException { 5 try ( // Create a random access file 6 RandomAccessFile read more..

  • Page - 723

    700 Chapter 17 Binary I/O A RandomAccessFile is created for the file named inout.dat with mode rw to allow both read and write operations in line 6. inout.setLength(0) sets the length to 0 in line 9. This, in effect, destroys the old con- tents of the file. The for loop writes 200 int values from 0 to 199 into the file in lines 12 and 13. Since read more..

  • Page - 724

    Programming Exercises 701 CHAPTER SUMMARY 1. I/O can be classified into text I/O and binary I/O. Text I/O interprets data in sequences of characters. Binary I/O interprets data as raw binary values. How text is stored in a file depends on the encoding scheme for the file. Java automatically performs encoding and decoding for text I/O. 2. The InputStream and OutputStream read more..

  • Page - 725

    702 Chapter 17 Binary I/O Section 17.6 *17.5 (Store objects and arrays in a file) Write a program that stores an array of the five int values 1, 2, 3, 4, and 5, a Date object for the current time, and the double value 5.5 into the file named Exercise17_05.dat. *17.6 (Store Loan objects) The Loan class in Listing 10.2 does not implement Serializable. Rewrite read more..

  • Page - 726

    Programming Exercises 703 *17.13 (Combine files GUI) Rewrite Exercise 17.12 with a GUI, as shown in Figure 17.21b. 17.14 (Encrypt files) Encode the file by adding 5 to every byte in the file. Write a pro- gram that prompts the user to enter an input file name and an output file name and saves the encrypted version of the input file to the output file. 17.15 read more..

  • Page - 727

    704 Chapter 17 Binary I/O *17.19 (View hex) Write a program that prompts the user to enter a file name, reads bytes from the file, and displays each byte’s hex representation. (Hint: You can first convert the byte value into an 8-bit string, then convert the bit string into a two- digit hex string.) **17.20 (Binary editor) Write a GUI application that lets the user read more..

  • Page - 728

    RECURSION Objectives ■ To describe what a recursive method is and the benefits of using recursion (§18.1). ■ To develop recursive methods for recursive mathematical functions (§§18.2–18.3). ■ To explain how recursive method calls are handled in a call stack (§§18.2–18.3). ■ To solve problems using recursion (§18.4). ■ To use an overloaded helper method to design a read more..

  • Page - 729

    706 Chapter 18 Recursion 18.1 Introduction Recursion is a technique that leads to elegant solutions to problems that are difficult to program using simple loops. Suppose you want to find all the files under a directory that contain a particular word. How do you solve this problem? There are several ways to do so. An intuitive and effective solution is to use recursion by read more..

  • Page - 730

    18.2 Case Study: Computing Factorials 707 else return n * factorial(n - 1); A recursive call can result in many more recursive calls, because the method keeps on dividing a subproblem into new subproblems. For a recursive method to terminate, the problem must eventually be reduced to a stopping case, at which point the method returns a result to its caller. The caller read more..

  • Page - 731

    708 Chapter 18 Recursion FIGURE 18.2 Invoking factorial(4) spawns recursive calls to factorial. return 1 return 2 * factorial(1) return 1 * factorial(0) Step 9: return 24 Step 0: executes factorial(4) Step 1: executes factorial(3) Step 2: executes factorial(2) Step 3: executes factorial(1) Step 5: return 1 Step 6: return 1 Step 7: return 2 Step 8: return 6 Step 4: executes read more..

  • Page - 732

    18.3 Case Study: Computing Fibonacci Numbers 709 Pedagogical Note It is simpler and more efficient to implement the factorial method using a loop. However, we use the recursive factorial method here to demonstrate the concept of recursion. Later in this chapter, we will present some problems that are inherently recursive and are difficult to solve without using recursion. If read more..

  • Page - 733

    710 Chapter 18 Recursion The series: 0 1 1 2 3 5 8 13 21 34 55 89 … indexes: 0 1 2 3 4 5 6 7 8 9 10 11 The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the pre- ceding two. The series can be recursively defined as: fib(0) = 0; fib(1) = 1; fib(index) = fib(index - 2) + fib(index - 1); index >= 2 The Fibonacci read more..

  • Page - 734

    18.3 Case Study: Computing Fibonacci Numbers 711 20 else if (index == 1) // Base case 21 return 1; 22 else // Reduction and recursive calls 23 return fib(index - 1) + fib(index - 2); 24 } 25 } base case recursion Enter an index for a Fibonacci number: 1 The Fibonacci number at index 1 is 1 Enter an index for a Fibonacci number: 6 The Fibonacci number at read more..

  • Page - 735

    712 Chapter 18 Recursion Pedagogical Note The recursive implementation of the fib method is very simple and straightforward, but it isn’t efficient, since it requires more time and memory to run recursive methods. See Programming Exercise 18.2 for an efficient solution using loops. Though it is not practical, the recursive fib method is a good example of how to write read more..

  • Page - 736

    18.4 Problem Solving Using Recursion 713 Recursion is everywhere. It is fun to think recursively. Consider drinking coffee. You may describe the procedure recursively as follows: public static void drinkCoffee(Cup cup) { if (!cup.isEmpty()) { cup.takeOneSip(); // Take one sip drinkCoffee(cup); } } Assume cup is an object for a cup of coffee with the read more..

  • Page - 737

    714 Chapter 18 Recursion 13 + isPalindrome("moon")); 14 System.out.println("Is noon a palindrome? " 15 + isPalindrome("noon")); 16 System.out.println("Is a a palindrome? " + isPalindrome("a")); 17 System.out.println("Is aba a palindrome? " + 18 isPalindrome("aba")); 19 read more..

  • Page - 738

    18.5 Recursive Helper Methods 715 14 15 public static void main(String[] args) { 16 System.out.println("Is moon a palindrome? " 17 + isPalindrome("moon")); 18 System.out.println("Is noon a palindrome? " 19 + isPalindrome("noon")); 20 System.out.println("Is a a palindrome? " + read more..

  • Page - 739

    716 Chapter 18 Recursion 22 // Sort the remaining list[low+1 .. high] 23 sort(list, low + 1, high); 24 } 25 } 26 } Two overloaded sort methods are defined. The first method, sort(double[] list), sorts an array in list[0..list.length - 1] and the second method, sort(double[] list, int low, int high), sorts an array in list[low..high]. The second method can read more..

  • Page - 740

    18.6 Case Study: Finding the Directory Size 717 18.13 Show the call stack for isPalindrome("abcba") using the method defined in Listing 18.4. 18.14 Show the call stack for selectionSort(new double[]{2, 3, 5, 1}) using the method defined in Listing 18.5. 18.15 What is a recursive helper method? 18.6 Case Study: Finding the Directory Size Recursive methods are efficient read more..

  • Page - 741

    718 Chapter 18 Recursion 14 15 public static long getSize(File file) { 16 long size = 0; // Store the total size of all files 17 18 if (file.isDirectory()) { 19 File[] files = file.listFiles(); // All files and subdirectories 20 for (int i = 0; files != null && i < files.length; i++) { 21 size += getSize(files[i]); // Recursive call 22 read more..

  • Page - 742

    18.7 Case Study: Tower of Hanoi 719 18.21 Will the program work if lines 20–21 is replaced by the following code? for (File file: files) size += getSize(file); // Recursive call 18.7 Case Study: Tower of Hanoi The Tower of Hanoi problem is a classic problem that can be solved easily using recursion, but it is difficult to solve otherwise. The problem involves read more..

  • Page - 743

    720 Chapter 18 Recursion Note The Tower of Hanoi is a classic computer-science problem, to which many websites are devoted. One of them worth looking at is www.cut-the-knot.com/recurrence/hanoi.shtml . In the case of three disks, you can find the solution manually. For a larger number of disks, however—even for four—the problem is quite complex. Fortunately, the problem has an read more..

  • Page - 744

    18.7 Case Study: Tower of Hanoi 721 Listing 18.8 gives a program that prompts the user to enter the number of disks and invokes the recursive method moveDisks to display the solution for moving the disks. LISTING 18.8 TowerOfHanoi.java 1 import java.util.Scanner; 2 3 public class TowerOfHanoi { 4 /** Main method */ 5 public static void main(String[] args) { read more..

  • Page - 745

    722 Chapter 18 Recursion This problem is inherently recursive. Using recursion makes it possible to find a natural, sim- ple solution. It would be difficult to solve the problem without using recursion. Consider tracing the program for n = 3. The successive recursive calls are shown in Figure 18.8. As you can see, writing the program is easier than tracing the recursive calls. The system uses stacks read more..

  • Page - 746

    18.8 Case Study: Fractals 723 drawing a Sierpinski triangle of order n can be reduced to drawing three Sierpinski triangles of order n - 1. Listing 18.9 gives a program that displays a Sierpinski triangle of any order, as shown in Figure 18.9. You can enter an order in a text field to display a Sierpinski triangle of the speci- fied order. LISTING 18.9 SierpinskiTriangle.java 1 import read more..

  • Page - 747

    724 Chapter 18 Recursion 20 e -> trianglePane.setOrder(Integer.parseInt(tfOrder.getText()))); 21 tfOrder.setPrefColumnCount(4); 22 tfOrder.setAlignment(Pos.BOTTOM_RIGHT); 23 24 // Pane to hold label, text field, and a button 25 HBox hBox = new HBox(10); 26 hBox.getChildren().addAll(new Label("Enter an order: "), tfOrder); 27 read more..

  • Page - 748

    18.8 Case Study: Fractals 725 80 // Get the midpoint on each edge in the triangle 81 Point2D p12 = p1.midpoint(p2); 82 Point2D p23 = p2.midpoint(p3); 83 Point2D p31 = p3.midpoint(p1); 84 85 // Recursively display three triangles 86 displayTriangles(order - 1, p1, p12, p31); 87 displayTriangles(order - 1, p12, p2, p23); 88 read more..

  • Page - 749

    726 Chapter 18 Recursion x- and y-coordinates. Invoking p1.midpoint(p2) returns a new Point2D object that is the midpoint between p1 and p2 (lines 81–83). 18.23 How do you obtain the midpoint between two points? 18.24 What is the base case for the displayTriangles method? 18.25 How many times is the displayTriangles method invoked for a Sierpinski trian- gle of order read more..

  • Page - 750

    18.10 Tail Recursion 727 18.10 Tail Recursion A tail recursive method is efficient for reducing stack size. A recursive method is said to be tail recursive if there are no pending operations to be per- formed on return from a recursive call, as illustrated in Figure 18.11a. However, method B in Figure 18.11b is not tail recursive because there are pending operations after a method call is read more..

  • Page - 751

    728 Chapter 18 Recursion a call is returned. The final result is returned in line 10, which is also the return value from invoking factorial(n, 1) in line 4. 18.30 Identify tail-recursive methods in this chapter. 18.31 Rewrite the fib method in Listing 18.2 using tail recursion. ✓ Point ✓Check KEY TERMS base case 706 direct recursion 709 indirect recursion 709 infinite read more..

  • Page - 752

    Programming Exercises 729 numbers. The current Fibonacci number would then be f0 + f1. The algorithm can be described as follows: f0 = 0; // For fib(0) f1 = 1; // For fib(1) for (int i = 1; i <= n; i++) { currentFib = f0 + f1; f0 = f1; f1 = currentFib; } // After the loop, currentFib is fib(n) Write a test program that prompts the user read more..

  • Page - 753

    730 Chapter 18 Recursion For example, reverseDisplay("abcd") displays dcba. Write a test program that prompts the user to enter a string and displays its reversal. *18.10 (Occurrences of a specified character in a string) Write a recursive method that finds the number of occurrences of a specified letter in a string using the follow- ing method header: public static read more..

  • Page - 754

    Programming Exercises 731 Write a test program that prompts the user to enter a list of characters in one line, and a character, and displays the number of occurrences of the character in the list. Sections 18.6–18.10 *18.18 (Tower of Hanoi) Modify Listing 18.8, TowerOfHanoi.java, so that the program finds the number of moves needed to move n disks from tower A read more..

  • Page - 755

    732 Chapter 18 Recursion *18.24 (Hex to decimal) Write a recursive method that parses a hex number as a string into a decimal integer. The method header is: public static int hex2Dec(String hexString) Write a test program that prompts the user to enter a hex string and displays its decimal equivalent. **18.25 (String permutation) Write a recursive method to print all read more..

  • Page - 756

    Programming Exercises 733 ■ The program enables the user to place or remove a mark on a cell. A path consists of adjacent unmarked cells. Two cells are said to be adjacent if they are horizontal or vertical neighbors, but not if they are diagonal neighbors. ■ The path does not contain cells that form a square. The path in Figure 18.13b, for example, does read more..

  • Page - 757

    734 Chapter 18 Recursion a program that displays the moves for the knight, as shown in Figure 18.15c. When you click a cell, the knight is placed at the cell. This cell will be starting point for the knight. Clicking the Solve button to display the path for a solution. FIGURE 18.15 (a) A knight traverses all squares once. (b) A knight makes an L-shaped move. (c) read more..

  • Page - 758

    Programming Exercises 735 **18.35 (H-tree fractal) An H-tree (introduced at the beginning of this chapter in Figure 18.1) is a fractal defined as follows: 1. Begin with a letter H. The three lines of the H are of the same length, as shown in Figure 18.1a. 2. The letter H (in its sans-serif form, H) has four endpoints. Draw an H cen- tered at each of the four endpoints to read more..

  • Page - 759

    736 Chapter 18 Recursion **18.38 (Recursive tree) Write a program to display a recursive tree as shown in Figure 18.20. VideoNote Recursive tree FIGURE 18.19 A Hilbert curve with the specified order is drawn. (a) (b) (c) (d) FIGURE 18.20 A recursive tree with the specified depth is drawn. (a) (b) (c) (d) **18.39 (Dragging the tree) Revise Programming Exercise 18.38 to move the read more..

  • Page - 760

    GENERICS Objectives ■ To descriibe the benefits of generics (§19.2). ■ To use generic classes and interfaces (§19.2). ■ To define generic classes and interfaces (§19.3). ■ To explain why generic types can improve reliability and readability (§19.3). ■ To define and use generic methods and bounded generic types (§19.4). ■ To develop a generic sort method to sort an read more..

  • Page - 761

    738 Chapter 19 Generics 19.1 Introduction Generics enable you to detect errors at compile time rather than at runtime. You have used a generic class ArrayList in Chapter 11 and generic interface Comparable in Chapter 13. Generics let you parameterize types. With this capability, you can define a class or a method with generic types that the compiler can replace with concrete read more..

  • Page - 762

    19.2 Motivations and Benefits 739 method must be of the Date type. Since the errors can be detected at compile time rather than at runtime, the generic type makes the program more reliable. ArrayList was introduced in Section 11.11, The ArrayList Class. This class has been a generic class since JDK 1.5. Figure 19.3 shows the class diagram for ArrayList before and since JDK read more..

  • Page - 763

    740 Chapter 19 Generics Casting is not needed to retrieve a value from a list with a specified element type, because the compiler already knows the element type. For example, the following statements create a list that contains strings, add strings to the list, and retrieve strings from the list. 1 ArrayList<String> list = new ArrayList<>(); 2 list.add("Red"); 3 read more..

  • Page - 764

    19.3 Defining Generic Classes and Interfaces 741 Let us revise the stack class in Section 11.13, Case Study: A Custom Stack Class, to gener- alize the element type with a generic type. The new stack class, named GenericStack, is shown in Figure 19.4 and is implemented in Listing 19.1. FIGURE 19.4 The GenericStack class encapsulates the stack storage and provides the operations for manipulating read more..

  • Page - 765

    742 Chapter 19 Generics This example creates a stack to hold integers and adds three integers to the stack: GenericStack<Integer> stack2 = new GenericStack<>(); stack2.push(1); // autoboxing 1 to new Integer(1) stack2.push(2); stack2.push(3); Instead of using a generic type, you could simply make the type element Object, which can accommodate any object type. However, using generic read more..

  • Page - 766

    19.4 Generic Methods 743 LISTING 19.2 GenericMethodDemo.java 1 public class GenericMethodDemo { 2 public static void main(String[] args ) { 3 Integer[] integers = {1, 2, 3, 4, 5}; 4 String[] strings = {"London", "Paris", "New York" , "Austin"}; 5 6 GenericMethodDemo.<Integer>print(integers); 7 read more..

  • Page - 767

    744 Chapter 19 Generics Note An unbounded generic type <E> is the same as <E extends Object>. Note To define a generic type for a class, place it after the class name, such as GenericStack<E>. To define a generic type for a method, place the generic type before the method return type, such as <E> void max(E o1, E o2). 19.8 How do you declare a generic method? read more..

  • Page - 768

    19.5 Case Study: Sorting an Array of Objects 745 35 /** Sort an array of comparable objects */ 36 public static <E extends Comparable<E>> void sort(E[] list) { 37 E currentMin; 38 int currentMinIndex; 39 40 for (int i = 0; i < list.length - 1 ; i++) { 41 // Find the minimum in the list[i+1..list.length-2] 42 currentMin = list[i]; 43 read more..

  • Page - 769

    746 Chapter 19 Generics 19.6 Raw Types and Backward Compatibility A generic class or interface used without specifying a concrete type, called a raw type, enables backward compatibility with earlier versions of Java. You can use a generic class without specifying a concrete type like this: GenericStack stack = new GenericStack(); // raw type This is roughly equivalent to read more..

  • Page - 770

    19.7 Wildcard Generic Types 747 7 return o2; 8 } 9 } If you invoke the max method using // 23 is autoboxed into new Integer(23) MaxUsingGenericType.max("Welcome", 23); a compile error will be displayed, because the two arguments of the max method in MaxUsingGenericType must have the same type (e.g., two strings or two integer objects). Furthermore, the read more..

  • Page - 771

    748 Chapter 19 Generics 11 /** Find the maximum in a stack of numbers */ 12 public static double max(GenericStack<Number> stack) { 13 double max = stack.pop().doubleValue(); // Initialize max 14 15 while (!stack.isEmpty()) { 16 double value = stack.pop().doubleValue(); 17 if (value > max) 18 max = value; 19 } 20 21 return max; 22 } 23 read more..

  • Page - 772

    19.7 Wildcard Generic Types 749 When is the wildcard <? super T> needed? Consider the example in Listing 19.9. The example creates a stack of strings in stack1 (line 3) and a stack of objects in stack2 (line 4), and invokes add(stack1, stack2) (line 8) to add the strings in stack1 into stack2. GenericStack<? super T> is used to declare stack2 in line read more..

  • Page - 773

    750 Chapter 19 Generics 19.17 What happens if lines 12–13 in Listing 19.9 are changed to public static <T> void add(GenericStack<? extends T> stack1, GenericStack<T> stack2) 19.8 Erasure and Restrictions on Generics The information on generics is used by the compiler but is not available at runtime. This is called type erasure. Generics are implemented read more..

  • Page - 774

    19.8 Erasure and Restrictions on Generics 751 Although ArrayList<String> and ArrayList<Integer> are two types at compile time, only one ArrayList class is loaded into the JVM at runtime. list1 and list2 are both instances of ArrayList, so the following statements display true: System.out.println(list1 instanceof ArrayList); System.out.println(list2 instanceof ArrayList); read more..

  • Page - 775

    752 Chapter 19 Generics a generic type parameter for a class in a static method, field, or initializer. For example, the following code is illegal: public class Test<E> { public static void m(E o1) { // Illegal } public static E o1; // Illegal static { E o2; // Illegal } } Restriction 4: Exception Classes Cannot Be Generic A generic class may not read more..

  • Page - 776

    19.9 Case Study: Generic Matrix Class 753 Integer type and 0/1 for the Rational type. These methods will be implemented in the subclasses in which the matrix element type is specified. IntegerMatrix and RationalMatrix are concrete subclasses of GenericMatrix. These two classes implement the add, multiply, and zero methods defined in the GenericMatrix class. Listing 19.10 read more..

  • Page - 777

    754 Chapter 19 Generics 20 E[][] result = 21 (E[][])new Number[matrix1.length][matrix1[0].length]; 22 23 // Perform addition 24 for (int i = 0; i < result.length; i++) 25 for (int j = 0; j < result[i].length; j++) { 26 result[i][j] = add(matrix1[i][j], matrix2[i][j]); 27 } 28 29 return result; 30 } 31 32 /** read more..

  • Page - 778

    19.9 Case Study: Generic Matrix Class 755 80 System.out.print(m3[i][j] + " "); 81 82 System.out.println(); 83 } 84 } 85 } Listing 19.11 implements the IntegerMatrix class. The class extends GenericMatrix<Integer> in line 1. After the generic instantiation, the add method in GenericMatrix<Integer> is now read more..

  • Page - 779

    756 Chapter 19 Generics Listing 19.13 gives a program that creates two Integer matrices (lines 4–5) and an IntegerMatrix object (line 8), and adds and multiplies two matrices in lines 12 and 16. LISTING 19.13 TestIntegerMatrix.java 1 public class TestIntegerMatrix { 2 public static void main(String[] args) { 3 // Create Integer arrays m1, m2 4 read more..

  • Page - 780

    Chapter Summary 757 20 GenericMatrix.printResult( 21 m1, m2, rationalMatrix.multiplyMatrix(m1, m2), '*'); 22 } 23 } multiply two matrices KEY TERMS actual concrete type 738 bounded generic type 743 bounded wildcard (<? extends E>) 748 formal generic type 738 generic instantiation 738 lower-bound wildcard (<? super E>) 748 raw type 746 unbounded wildcard read more..

  • Page - 781

    758 Chapter 19 Generics 5. A generic class such as ArrayList used without a type parameter is called a raw type. Use of raw types is allowed for backward compatibility with the earlier ver- sions of Java. 6. A wildcard generic type has three forms: ? and ? extends T, and ? super T, where T is a generic type. The first form, ?, called an unbounded wildcard, is read more..

  • Page - 782

    Programming Exercises 759 19.6 (Maximum element in a two-dimensional array) Write a generic method that returns the maximum element in a two-dimensional array. public static <E extends Comparable<E>> E max(E[][] list) 19.7 (Generic binary search) Implement the following method using binary search. public static <E extends Comparable<E>> int binarySearch(E[] list, E key) 19.8 read more..

  • Page - 783

    This page intentionally left blank read more..

  • Page - 784

    LISTS,STACKS, QUEUES, AND PRIORITY QUEUES Objectives ■ To explore the relationship between interfaces and classes in the Java Collections Framework hierarchy (§20.2). ■ To use the common methods defined in the Collection interface for operating collections (§20.2). ■ To use the Iterator interface to traverse the elements in a collection (§20.3). ■ To use a foreach loop to read more..

  • Page - 785

    762 Chapter 20 Lists, Stacks, Queues, and Priority Queues 20.1 Introduction Choosing the best data structures and algorithms for a particular task is one of the keys to developing high-performance software. A data structure is a collection of data organized in some fashion. The structure not only stores data but also supports operations for accessing and manipulating the data. read more..

  • Page - 786

    20.2 Collections 763 a concrete class that extends the abstract class rather implements all the methods in the interface. The abstract classes such as AbstractCollection are provided for convenience. For this reason, they are called convenience abstract classes. The Collection interface is the root interface for manipulating a collection of objects. Its public methods are listed read more..

  • Page - 787

    764 Chapter 20 Lists, Stacks, Queues, and Priority Queues .UnsupportedOperationException, a subclass of RuntimeException. This is a good design that y ou can use in your project. If a method has no meaning in the subclass, you can implement it as follows: public void someMethod() { throw new UnsupportedOperationException ("Method not supported"); } Listing 20.1 gives an example read more..

  • Page - 788

    20.2 Collections 765 10 11 System.out.println("A list of cities in collection1:"); 12 System.out.println(collection1); 13 14 System.out.println("\nIs Dallas in collection1? " 15 + collection1.contains("Dallas")); 16 17 collection1.remove("Dallas"); 18 System.out.println("\n" + collection1.size() + 19 " cities are read more..

  • Page - 789

    766 Chapter 20 Lists, Stacks, Queues, and Priority Queues The program creates a copy of an array list (lines 30, 35, 40). The purpose of this is to keep the original array list intact and use its copy to perform addAll, retainAll, and removeAll operations. Note All the concrete classes in the Java Collections Framework implement the java.lang. Cloneable and java.io.Serializable read more..

  • Page - 790

    20.4 Lists 767 The program creates a concrete collection object using ArrayList (line 5) and adds four strings into the list (lines 6–9). The program then obtains an iterator for the collection (line 11) and uses the iterator to traverse all the strings in the list and displays the strings in uppercase (lines 12–14). Tip You can simplify the code in lines 11–14 read more..

  • Page - 791

    768 Chapter 20 Lists, Stacks, Queues, and Priority Queues The listIterator() or listIterator(startIndex) method returns an instance of ListIterator. The ListIterator interface extends the Iterator interface to add bidi- rectional traversal of the list. The methods in ListIterator are listed in Figure 20.4. FIGURE 20.3 The List interface stores elements in sequence and permits read more..

  • Page - 792

    20.4 Lists 769 method to check whether the iterator has more elements when traversed in the backward direction. The next() method defined in the Iterator interface returns the next element in the iterator, and the previous() method returns the previous element in the iterator. The nextIndex() method returns the index of the next element in the iterator, and the read more..

  • Page - 793

    770 Chapter 20 Lists, Stacks, Queues, and Priority Queues Listing 20.3 gives a program that creates an array list filled with numbers and inserts new elements into specified locations in the list. The example also creates a linked list from the array list and inserts and removes elements from the list. Finally, the example traverses the list forward and backward. LISTING read more..

  • Page - 794

    20.4 Lists 771 A list can hold identical elements. Integer 1 is stored twice in the list (lines 6, 9). ArrayList and LinkedList operate similarly. The critical difference between them pertains to internal implementation, which affects their performance. ArrayList is efficient for retrieving ele- ments and LinkedList is efficient for inserting and removing elements at the read more..

  • Page - 795

    772 Chapter 20 Lists, Stacks, Queues, and Priority Queues 20.5 The Comparator Interface Comparator can be used to compare the objects of a class that doesn’t implement Comparable. You have learned how to compare elements using the Comparable interface (introduced in Section  13.6). Several classes in the Java API, such as String, Date, Calendar, BigInteger, BigDecimal, and read more..

  • Page - 796

    20.6 Static Methods for Lists and Collections 773 5 GeometricObject g1 = new Rectangle(5, 5); 6 GeometricObject g2 = new Circle(5); 7 8 GeometricObject g = 9 max(g1, g2, new GeometricObjectComparator()); 10 11 System.out.println("The area of the larger object is " + 12 g.getArea()); 13 } 14 read more..

  • Page - 797

    774 Chapter 20 Lists, Stacks, Queues, and Priority Queues FIGURE 20.7 The Collections class contains static methods for manipulating lists and collections. java.util.Collections +sort(list: List): void +sort(list: List, c: Comparator): void +binarySearch(list: List, key: Object): int +binarySearch(list: List, key: Object, c: Comparator): int +reverse(list: List): void +reverseOrder(): Comparator read more..

  • Page - 798

    20.6 Static Methods for Lists and Collections 775 System.out.println("(2) Index: " + Collections.binarySearch(list1, 9)); List<String> list2 = Arrays.asList("blue", "green", "red"); System.out.println("(3) Index: " + Collections.binarySearch(list2, "red")); System.out.println("(4) Index: " + Collections.binarySearch(list2, "cyan")); The output read more..

  • Page - 799

    776 Chapter 20 Lists, Stacks, Queues, and Priority Queues The output for list1 is [white, black, green, blue]. The copy method performs a shallow copy: only the references of the elements from the source list are copied. You can use the nCopies(int n, Object o) method to create an immutable list that consists of n copies of the specified object. For example, the read more..

  • Page - 800

    20.7 Case Study: Bouncing Balls 777 List<String> list = Arrays.asList("yellow", "red", "green", "blue"); Collections.reverse(list); System.out.println(list); List<String> list1 = Arrays.asList("yellow", "red", "green", "blue"); List<String> list2 = read more..

  • Page - 801

    778 Chapter 20 Lists, Stacks, Queues, and Priority Queues Each ball has its state: the x-, y-coordinates, color, and direction to move. You can define a class named Ball that extends javafx.scene.shape.Circle. The x-, y-coordinates and the color are already defined in Circle. When a ball is created, it starts from the upper-left corner and moves downward to the right. read more..

  • Page - 802

    20.7 Case Study: Bouncing Balls 779 25 Button btSubtract = new Button("-"); 26 HBox hBox = new HBox(10); 27 hBox.getChildren().addAll(btAdd, btSubtract); 28 hBox.setAlignment(Pos.CENTER); 29 30 // Add or remove a ball 31 btAdd.setOnAction(e -> ballPane.add()); 32 btSubtract.setOnAction(e -> ballPane.subtract()); 33 34 // read more..

  • Page - 803

    780 Chapter 20 Lists, Stacks, Queues, and Priority Queues 84 animation.pause(); 85 } 86 87 public void increaseSpeed() { 88 animation.setRate(animation.getRate() + 0.1); 89 } 90 91 public void decreaseSpeed() { 92 animation.setRate( 93 animation.getRate() > 0 ? read more..

  • Page - 804

    20.8 Vector and Stack Classes 781 20.24 How do you modify the code in the MutilpleBallApp program to remove the first ball in the list when the button is clicked? 20.25 How do you modify the code in the MutilpleBallApp program so that each ball will get a random radius between 10 and 20? 20.8 Vector and Stack Classes Vector is a subclass of AbstractList, read more..

  • Page - 805

    782 Chapter 20 Lists, Stacks, Queues, and Priority Queues Most of the methods in the Vector class listed in the UML diagram in Figure 20.10 are similar to the methods in the List interface. These methods were introduced before the Java Collections Framework. For example, addElement(Object element) is the same as the add(Object element) method, except that the read more..

  • Page - 806

    20.9 Queues and Priority Queues 783 20.9 Queues and Priority Queues In a priority queue, the element with the highest priority is removed first. A queue is a first-in, first-out data structure. Elements are appended to the end of the queue and are removed from the beginning of the queue. In a priority queue, elements are assigned priorities. When accessing elements, the read more..

  • Page - 807

    784 Chapter 20 Lists, Stacks, Queues, and Priority Queues Listing 20.7 shows an example of using a queue to store strings. Line 4 creates a queue using LinkedList. Four strings are added to the queue in lines 5–8. The size() method defined in the Collection interface returns the number of elements in the queue (line 10). The remove() method retrieves and read more..

  • Page - 808

    20.9 Queues and Priority Queues 785 LISTING 20.8 PriorityQueueDemo.java 1 import java.util.*; 2 3 public class PriorityQueueDemo { 4 public static void main(String[] args) { 5 PriorityQueue<String> queue1 = new PriorityQueue<>(); 6 queue1.offer("Oklahoma"); 7 queue1.offer("Indiana"); 8 queue1.offer("Georgia"); 9 read more..

  • Page - 809

    786 Chapter 20 Lists, Stacks, Queues, and Priority Queues 20.30 How do you create a priority queue for integers? By default, how are elements ordered in a priority queue? Is the element with the least value assigned the highest priority in a priority queue? 20.31 How do you create a priority queue that reverses the natural order of the elements? 20.10 Case Study: read more..

  • Page - 810

    20.10 Case Study: Evaluating Expressions 787 1.4. If the extracted item is a ( symbol, push it to operatorStack. 1.5. If the extracted item is a ) symbol, repeatedly process the operators from the top of operatorStack until seeing the ( symbol on the stack. Phase 2: Clearing the stack Repeatedly process the operators from the top of operatorStack until read more..

  • Page - 811

    788 Chapter 20 Lists, Stacks, Queues, and Priority Queues LISTING 20.9 EvaluateExpression.java 1 import java.util.Stack; 2 3 public class EvaluateExpression { 4 public static void main(String[] args) { 5 // Check number of arguments passed 6 if (args.length != 1) { 7 System.out.println( 8 "Usage: java EvaluateExpression read more..

  • Page - 812

    20.10 Case Study: Evaluating Expressions 789 59 // Push the * or / operator into the operator stack 60 operatorStack.push(token.charAt(0)); 61 } 62 else if (token.trim().charAt(0) == '(') { 63 operatorStack.push('('); // Push '(' to stack 64 } 65 else if (token.trim().charAt(0) == ')') { 66 read more..

  • Page - 813

    790 Chapter 20 Lists, Stacks, Queues, and Priority Queues You can use the GenericStack class provided by the book or the java.util.Stack class defined in the Java API for creating stacks. This example uses the java.util.Stack class. The program will work if it is replaced by GenericStack. The program takes an expression as a command-line argument in one string. The read more..

  • Page - 814

    Programming Exercises 791 4. To allow duplicate elements to be stored in a collection, you need to use a list. A list not only can store duplicate elements but also allows the user to specify where they are stored. The user can access elements by an index. 5. Two types of lists are supported: ArrayList and LinkedList. ArrayList is a resizable-array implementation of read more..

  • Page - 815

    792 Chapter 20 Lists, Stacks, Queues, and Priority Queues *20.3 (Guessing the capitals) Rewrite Programming Exercise 8.37 to store the pairs of states and capitals so that the questions are displayed randomly. *20.4 (Sort points in a plane) Write a program that meets the following requirements: ■ Define a class named Point with two data fields x and y to represent a read more..

  • Page - 816

    Programming Exercises 793 FIGURE 20.18 The program displays a hangman game. read more..

  • Page - 817

    794 Chapter 20 Lists, Stacks, Queues, and Priority Queues 20.12 (Clone PriorityQueue) Define MyPriorityQueue class that extends PriorityQueue to implement the Cloneable interface and implement the clone() method to clone a priority queue. **20.13 (Game: the 24-point card game) The 24-point game is to pick any 4 cards from 52 cards, as shown in Figure 20.19. Note that the Jokers are read more..

  • Page - 818

    Programming Exercises 795 Write a program to evaluate postfix expressions. Pass the expression as a command-line argument in one string. ***20.15 (Game: the 24-point card game) Improve Programming Exercise 20.13 to enable the computer to display the expression if one exists, as shown in Figure  20.20. Otherwise, report that the expression does not exist. Place the label for read more..

  • Page - 819

    796 Chapter 20 Lists, Stacks, Queues, and Priority Queues program should use a queue to store the subdirectories under a directory. The algorithm can be described as follows: long getSize(File directory) { long size = 0; add directory to the queue; while (queue is not empty) { Remove an item from the queue into t; if (t is a file) size read more..

  • Page - 820

    SETS AND MAPS Objectives ■ To store unordered, nonduplicate elements using a set (§21.2). ■ To explore how and when to use HashSet (§21.2.1), LinkedHashSet (§21.2.2), or TreeSet (§21.2.3) to store a set of elements. ■ To compare the performance of sets and lists (§21.3). ■ To use sets to develop a program that counts the keywords in a Java source file (§21.4). ■ To tell read more..

  • Page - 821

    798 Chapter 21 Sets and Maps 21.1 Introduction A set is an efficient data structure for storing and processing nonduplicate elements. A map is like a dictionary that provides a quick lookup to retrieve a value using a key. The “No-Fly” list is a list, created and maintained by the U.S. government’s Terrorist Screen- ing Center, of people who are not permitted to board a commercial aircraft read more..

  • Page - 822

    21.2 Sets 799 Listing 21.1 gives a program that creates a hash set to store strings and uses a foreach loop to traverse the elements in the set. LISTING 21.1 TestHashSet.java 1 import java.util.*; 2 3 public class TestHashSet { 4 public static void main(String[] args) { 5 // Create a hash set 6 Set<String> set = new HashSet<>(); 7 8 // Add read more..

  • Page - 823

    800 Chapter 21 Sets and Maps 14 set.add("New York" ); 15 16 System.out.println(set); 17 18 // Display the elements in the hash set 19 for (String s: set) { 20 System.out.print(s.toUpperCase() + " "); 21 } 22 } 23 } traverse elements [San Francisco, New York, Paris, Beijing, London] SAN FRANCISCO NEW YORK read more..

  • Page - 824

    21.2 Sets 801 30 31 System.out.println("\nIs Taipei in set2? " 32 + set2.contains("Taipei")); 33 34 set1.addAll(set2); 35 System.out.println("\nAfter adding set2 to set1, set1 is " 36 + set1); 37 38 set1.removeAll(set2); 39 System.out.println("After removing set2 from set1, set1 is " 40 + read more..

  • Page - 825

    802 Chapter 21 Sets and Maps retains the common elements in set1. Since set1 and set2 have no common elements, set1 becomes empty. 21.2.2 LinkedHashSet LinkedHashSet extends HashSet with a linked-list implementation that supports an order- ing of the elements in the set. The elements in a HashSet are not ordered, but the elements in a LinkedHashSet can be retrieved read more..

  • Page - 826

    21.2 Sets 803 a portion of the set whose elements are less than toElement and greater than or equal to fromElement, respectively. NavigableSet extends SortedSet to provide navigation methods lower(e), floor(e), ceiling(e), and higher(e) that return elements respectively less than, less than or equal, greater than or equal, and greater than a given element and return null read more..

  • Page - 827

    804 Chapter 21 Sets and Maps The example creates a hash set filled with strings, then creates a tree set for the same strings. The strings are sorted in the tree set using the compareTo method in the Comparable interface. The elements in the set are sorted once you create a TreeSet object from a HashSet object using new TreeSet<String>(set) (line 16). You read more..

  • Page - 828

    21.2 Sets 805 3 public class TestTreeSetWithComparator { 4 public static void main(String[] args) { 5 // Create a tree set for geometric objects using a comparator 6 Set<GeometricObject> set = 7 new TreeSet<>(new GeometricObjectComparator()); 8 set.add(new Rectangle(4, 5)); 9 set.add(new Circle(40)); 10 set.add(new read more..

  • Page - 829

    806 Chapter 21 Sets and Maps 21.7 Show the output of the following code: import java.util.*; public class Test { public static void main(String[] args) { LinkedHashSet<String> set1 = new LinkedHashSet<>(); set1.add("New York" ); LinkedHashSet<String> set2 = set1; LinkedHashSet<String> set3 = read more..

  • Page - 830

    21.3 Comparing the Performance of Sets and Lists 807 is in a hash set, linked hash set, tree set, array list, and linked list, and (2) removing elements from a hash set, linked hash set, tree set, array list, and linked list. LISTING 21.6 SetListPerformanceTest.java 1 import java.util.*; 2 3 public class SetListPerformanceTest { 4 static final int N = 50000; read more..

  • Page - 831

    808 Chapter 21 Sets and Maps 57 } 58 59 public static long getRemoveTime(Collection<Integer> c) { 60 long startTime = System.currentTimeMillis(); 61 62 for (int i = 0; i < N; i++) 63 c.remove(i); 64 65 return System.currentTimeMillis() - startTime; 66 } 67 } remove from container return execution time Member test time for hash set is 20 milliseconds Remove read more..

  • Page - 832

    21.4 Case Study: Counting Keywords 809 21.4 Case Study: Counting Keywords This section presents an application that counts the number of the keywords in a Java source file. For each word in a Java source file, we need to determine whether the word is a keyword. To handle this efficiently, store all the keywords in a HashSet and use the contains method to test if read more..

  • Page - 833

    810 Chapter 21 Sets and Maps FIGURE 21.2 The entries consisting of key/value pairs are stored in a map. Corresponding element value Entry Search key A map Corresponding value Entry Search key (b) (a) 111-34-3434 John 132-56-6290 Peter Enter a Java source file: c:\TTT.java File c:\TTT.java does not exist Enter a Java source file: c:\Welcome.java The number of keywords in c:\Welcome.java is read more..

  • Page - 834

    21.5 Maps 811 There are three types of maps: HashMap, LinkedHashMap, and TreeMap. The com- mon features of these maps are defined in the Map interface. Their relationship is shown in Figure 21.3. FIGURE 21.3 A map stores key/value pairs. SortedMap HashMap LinkedHashMap TreeMap Interfaces Abstract Classes Concrete Classes Map NavigableMap AbstractMap FIGURE 21.4 The Map interface maps read more..

  • Page - 835

    812 Chapter 21 Sets and Maps You can obtain a set of the keys in the map using the keySet() method, and a collection of the values in the map using the values() method. The entrySet() method returns a set of entries. The entries are instances of the Map.Entry<K, V> interface, where Entry is an inner interface for the Map interface, as shown in read more..

  • Page - 836

    21.5 Maps 813 The HashMap class is efficient for locating a value, inserting an entry, and deleting an entry. LinkedHashMap extends HashMap with a linked-list implementation that supports an ordering of the entries in the map. The entries in a HashMap are not ordered, but the entries in a LinkedHashMap can be retrieved either in the order in which they were inserted read more..

  • Page - 837

    814 Chapter 21 Sets and Maps 17 new TreeMap<>(hashMap); 18 System.out.println("Display entries in ascending order of key"); 19 System.out.println(treeMap); 20 21 // Create a LinkedHashMap 22 Map<String, Integer> linkedHashMap = 23 new LinkedHashMap<>(16, 0.75f, true); 24 linkedHashMap.put("Smith", 30); 25 read more..

  • Page - 838

    21.6 Case Study: Occurrences of Words 815 21.20 Show the output of the following code: public class Test { public static void main(String[] args) { Map<String, String> map = new LinkedHashMap<>(); map.put("123", "John Smith"); map.put("111", "George Smith"); map.put("123", "Steve Yao"); read more..

  • Page - 839

    816 Chapter 21 Sets and Maps 31 // Get key and value from each entry 32 for (Map.Entry<String, Integer> entry: entrySet) 33 System.out.println(entry.getValue() + "\t" + entry.getKey()); 34 } 35 } display entry a 2 class 1 fun 1 good 3 have read more..

  • Page - 840

    Chapter Summary 817 an immutable list containing only a single item, and the singletonMap(Object key, Object value) method for creating an immutable map containing only a single entry. The Collections class also provides six static methods for returning read-only views for collections: unmodifiableCollection(Collection c), unmodifiableList(List list), unmodifiableMap(Map m), unmodifiableSet(Set read more..

  • Page - 841

    818 Chapter 21 Sets and Maps they were inserted. TreeSet stores elements sorted. All the methods in HashSet, LinkedHashSet, and TreeSet are inherited from the Collection interface. 4. The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integers. In Map, the keys can be any objects. A map cannot contain duplicate keys. read more..

  • Page - 842

    Programming Exercises 819 Sections 21.5–21.7 *21.6 (Count the occurrences of numbers entered) Write a program that reads an unspecified number of integers and finds the one that has the most occurrences. The input ends when the input is 0. For example, if you entered 2340354–3 3320, the number 3 occurred most often. If not one but several numbers have the most read more..

  • Page - 843

    820 Chapter 21 Sets and Maps **21.12 (Name for both genders) Write a program that prompts the user to enter one of the filenames described in Programming Exercise 12.31 and displays the names that are used for both genders in the file. Use sets to store names and find com- mon names in two sets. Here is a sample run: FIGURE 21.9 The user selects a year and read more..

  • Page - 844

    DEVELOPING EFFICIENT ALGORITHMS Objectives ■ To estimate algorithm efficiency using the Big O notation (§22.2). ■ To explain growth rates and why constants and nondominating terms can be ignored in the estimation (§22.2). ■ To determine the complexity of various types of algorithms (§22.3). ■ To analyze the binary search algorithm (§22.4.1). ■ To analyze the selection sort read more..

  • Page - 845

    822 Chapter 22 Developing Efficient Algorithms 22.1 Introduction Algorithm design is to develop a mathematical process for solving a problem. Algorithm analysis is to predict the performance of an algorithm. The preceding two chapters introduced classic data structures (lists, stacks, queues, priority queues, sets, and maps) and applied them to solve problems. This chapter will use a read more..

  • Page - 846

    22.2 Measuring Algorithm Efficiency Using Big O Notation 823 The linear search algorithm requires n comparisons in the worst case and n/2 comparisons in the average case if you are nearly always looking for something known to be in the list. Using the Big O notation, both cases require O(n) time. The multiplicative constant (1/2) can be omitted. Algorithm analysis is read more..

  • Page - 847

    824 Chapter 22 Developing Efficient Algorithms 22.3 Examples: Determining Big O This section gives several examples of determining Big O for repetition, sequence, and selection statements. Example 1 Consider the time complexity for the following loop: for (int i = 1; i <= n; i++) { k = k + 5; } It is a constant time, c, for executing k = k + 5; Since the loop read more..

  • Page - 848

    22.3 Examples: Determining Big O 825 k = k + i + j; } } It is a constant time, c, for executing k = k + i + j; The outer loop executes n times. For each iteration in the outer loop, the inner loop is executed n times. Thus, the time complexity for the loop is T(n) = (a constant c)* n * n = O(n2) An algorithm with the O(n2) time read more..

  • Page - 849

    826 Chapter 22 Developing Efficient Algorithms for (int j = 1; j <= 20; j++) { k = k + i + j; } } The first loop executes 10 times, and the second loop 20 * n times. Thus, the time com- plexity for the loop is T(n) = 10 * c + 20 * c * n = O(n) Example 6 Consider the following selection statement: if (list.contains(e)) { read more..

  • Page - 850

    22.3 Examples: Determining Big O 827 22.4 How many stars are displayed in the following code if n is 10? How many if n is 20? Use the Big O notation to estimate the time complexity. int count = 1; while (count < n) { count = count * 2; } (c) int count = 15; while (count < n) { count = count * 3; } (d) for (int i = 0; i < n; read more..

  • Page - 851

    828 Chapter 22 Developing Efficient Algorithms 22.4 Analyzing Algorithm Time Complexity This section analyzes the complexity of several well-known algorithms: binary search, selection sort, and Tower of Hanoi. 22.4.1 Analyzing Binary Search The binary search algorithm presented in Listing 7.7, BinarySearch.java, searches for a key in a sorted array. Each iteration in the algorithm contains read more..

  • Page - 852

    22.4 Analyzing Algorithm Time Complexity 829 2. Move disk n from A to B. 3. Move n - 1 disks from C to B with the assistance of tower A. The complexity of this algorithm is measured by the number of moves. Let T(n) denote the number of moves for the algorithm to move n disks from tower A to tower B with T(1) = 1. Thus, T(n) = T(n - 1) + 1 + read more..

  • Page - 853

    830 Chapter 22 Developing Efficient Algorithms These functions are ordered as follows, as illustrated in Figure 22.1. O(1) 6 O(logn) 6 O(n) 6 O(n logn) 6 O(n2) 6 O(n3) 6 O(2n) FIGURE 22.1 As the size n increases, the function grows. O(1) O(logn) O(n) O(n logn) O(2 n) O(n 3) O(n 2) f(n) n Function Name n = 25 n = 50 f(50)/f(25) O(1) Constant time 1 1 1 O(logn) Logarithmic time 4.64 read more..

  • Page - 854

    22.5 Finding Fibonacci Numbers Using Dynamic Programming 831 22.5 Finding Fibonacci Numbers Using Dynamic Programming This section analyzes and designs an efficient algorithm for finding Fibonacci numbers using dynamic programming. Section 18.3, Case Study: Computing Fibonacci Numbers, gave a recursive method for find- ing the Fibonacci number, as follows: /** The method for finding the Fibonacci read more..

  • Page - 855

    832 Chapter 22 Developing Efficient Algorithms The new method is implemented in Listing 22.2. LISTING 22.2 ImprovedFibonacci.java 1 import java.util.Scanner; 2 3 public class ImprovedFibonacci { 4 /** Main method */ 5 public static void main(String args[]) { 6 // Create a Scanner 7 Scanner input = new Scanner(System.in); 8 read more..

  • Page - 856

    22.6 Finding Greatest Common Divisors Using Euclid’s Algorithm 833 subproblems overlap. The key idea behind dynamic programming is to solve each subproblem only once and store the results for subproblems for later use to avoid redundant computing of the subproblems. 22.14 What is dynamic programming? Give an example of dynamic programming. 22.15 Why is the recursive Fibonacci read more..

  • Page - 857

    834 Chapter 22 Developing Efficient Algorithms break; } } However, this algorithm is incorrect, because n can be a divisor for m. This case must be con- sidered. The correct algorithm is shown in Listing 22.3. LISTING 22.3 GCD.java 1 import java.util.Scanner; 2 3 public class GCD { 4 /** Find GCD for integers m and n */ 5 public static int gcd(int m, read more..

  • Page - 858

    22.6 Finding Greatest Common Divisors Using Euclid’s Algorithm 835 Note The Big O notation provides a good theoretical estimate of algorithm efficiency. How- ever, two algorithms of the same time complexity are not necessarily equally efficient. As shown in the preceding example, both algorithms in Listings 5.9 and 22.3 have the same complexity, but in practice the one in read more..

  • Page - 859

    836 Chapter 22 Developing Efficient Algorithms In the best case when m % n is 0, the algorithm takes just one step to find the GCD. It is dif- ficult to analyze the average case. However, we can prove that the worst-case time complexity is O(log n). Assuming m Ú n, we can show that m % n < m / 2 , as follows: ■ If n <= m / 2 , m % n < m / 2 read more..

  • Page - 860

    22.7 Efficient Algorithms for Finding Prime Numbers 837 = gcd(3, 2) = gcd(2, 1) = 1 Therefore, the number of times the gcd method is invoked is the same as the index. We can prove that index … 1.44 logn, where n = fib(index - 1). This is a tighter bound than index … 2logn. Table 22.4 summarizes the complexity of three algorithms for finding the GCD. Algorithm Complexity read more..

  • Page - 861

    838 Chapter 22 Developing Efficient Algorithms LISTING 22.5 PrimeNumbers.java 1 import java.util.Scanner; 2 3 public class PrimeNumbers { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 System.out.print("Find all prime numbers <= n, enter n: "); 7 int n = input.nextInt(); 8 9 final int read more..

  • Page - 862

    22.7 Efficient Algorithms for Finding Prime Numbers 839 The program is not efficient if you have to compute Math.sqrt(number) for every iteration of the for loop (line 21). A good compiler should evaluate Math.sqrt(number) only once for the entire for loop. To ensure this happens, you can explicitly replace line 21 with the following two lines: int squareRoot = read more..

  • Page - 863

    840 Chapter 22 Developing Efficient Algorithms 7 int n = input.nextInt(); 8 9 // A list to hold prime numbers 10 java.util.List<Integer> list = 11 new java.util.ArrayList<>(); 12 13 final int NUMBER_PER_LINE = 10; // Display 10 per line 14 int count = 0; // Count the number of prime numbers 15 int number = 2; // A number to be tested for read more..

  • Page - 864

    22.7 Efficient Algorithms for Finding Prime Numbers 841 Let p (i) denote the number of prime numbers less than or equal to i. The primes under 20 are 2, 3, 5, 7, 11, 13, 17, and 19. Therefore, p (2) is 1, p (3) is 2, p (6) is 3, and p (20) is 8. It has been proved that p (i) is approximately i logi (see primes.utm.edu/howmany.shtml ). For each read more..

  • Page - 865

    842 Chapter 22 Developing Efficient Algorithms still true, then i is a prime number. As shown in Figure 22.3, 2 , 3, 5, 7, 11, 13, 17, 19, and 23 are prime numbers. Listing 22.7 gives the program for finding the prime numbers using the Sieve of Eratosthenes algorithm. LISTING 22.7 SieveOfEratosthenes.java 1 import java.util.Scanner; 2 3 public class SieveOfEratosthenes read more..

  • Page - 866

    22.8 Finding the Closest Pair of Points Using Divide-and-Conquer 843 For each prime number k (line 17), the algorithm sets primes[k * i] to false (line 19). This is performed n / k – k + 1 times in the for loop (line 18). Thus, the complexity for finding all prime numbers up to n is n 2 - 2 + 1 + n 3 - 3 + 1 + n 5 - 5 + 1 + n 7 - 7 + 1 read more..

  • Page - 867

    844 Chapter 22 Developing Efficient Algorithms We will use an approach called divide-and-conquer to solve this problem. The approach divides the problem into subproblems, solves the subproblems, then combines the solutions of the subproblems to obtain the solution for the entire problem. Unlike the dynamic program- ming approach, the subproblems in the divide-and-conquer approach read more..

  • Page - 868

    22.8 Finding the Closest Pair of Points Using Divide-and-Conquer 845 LISTING 22.9 Algorithm for Obtaining stripL and stripR 1 for each point p in pointsOrderedOnY 2 if (p is in S1 and mid.x – p.x <= d) 3 append p to stripL; 4 else if (p is in S2 and p.x - mid.x <= d) 5 append p to stripR; Let the points in stripL read more..

  • Page - 869

    846 Chapter 22 Developing Efficient Algorithms Note that Step 1 in Listing 22.8 is performed only once to presort the points. Assume that all the points are presorted. Let T(n) denote the time complexity for this algorithm. Thus, Step 2 Step 3 T(n) = 2T(n/2) + O(n) = O(n logn) Therefore, the closest pair of points can be found in O(n log n) time. The complete read more..

  • Page - 870

    22.9 Solving the Eight Queens Problem Using Backtracking 847 To see how the algorithm works, go to www.cs.armstrong.edu/liang/animation/ EightQueensAnimation.html . Listing 22.11 gives the program that displays a solution for the Eight Queens problem. LISTING 22.11 EightQueens.java 1 import javafx.application.Application; 2 import javafx.geometry.Pos; 3 import javafx.stage.Stage; 4 read more..

  • Page - 871

    848 Chapter 22 Developing Efficient Algorithms 56 queens[k] = j; 57 k++; 58 } 59 } 60 61 if (k == -1) 62 return false; // No solution 63 else 64 return true; // A solution is found 65 } 66 67 public int findPosition(int k) { 68 int start = queens[k] + 1; // Search for a new placement 69 70 for read more..

  • Page - 872

    22.10 Computational Geometry: Finding a Convex Hull 849 22.22 What is backtracking? Give an example. 22.23 If you generalize the Eight Queens problem to the n-Queens problem in an n-by-n chessboard, what will be the complexity of the algorithm? 22.10 Computational Geometry: Finding a Convex Hull This section presents efficient geometric algorithms for finding a convex hull for a read more..

  • Page - 873

    850 Chapter 22 Developing Efficient Algorithms Step 2: Let t1 be s0. For every point p in S, if p is on the right side of the direct line from t0 to t1, then let t1 be p. (After Step 2, no points lie on the right side of the direct line from t0 to t1, as shown in Figure 22.9b.) read more..

  • Page - 874

    Step 3: Push p0, p1, and p2 into stack H. (After the algorithm finishes, H contains all the points in the convex hull.) Step 4: i = 3; while (i < n) { Let t1 and t2 be the top first and second element in stack H; if (pi is on the left side of the direct line from t2 to t1) { read more..

  • Page - 875

    852 Chapter 22 Developing Efficient Algorithms 2. An input that results in the shortest execution time is called the best-case input and one that results in the longest execution time is called the worst-case input. Best case and worst case are not representative, but worst-case analysis is very useful. You can be assured that the algorithm will never be slower than read more..

  • Page - 876

    Programming Exercises 853 QUIZ Answer the quiz for this chapter online at www.cs.armstrong.edu/liang/intro10e/test.html . PROGRAMMING EXERCISES *22.1 (Maximum consecutive increasingly ordered substring) Write a program that prompts the user to enter a string and displays the maximum consecutive increasingly ordered substring. Analyze the time complexity of your program. Here is a sample run: read more..

  • Page - 877

    854 Chapter 22 Developing Efficient Algorithms *22.5 (Same-number subsequence) Write an O(n) program that prompts the user to enter a sequence of integers ending with 0 and finds the longest subsequence with the same number. Here is a sample run of the program: Enter a series of numbers ending with 0: 2 4 4 8 8 8 8 2 4 4 0 The longest same number sequence read more..

  • Page - 878

    Programming Exercises 855 /** Compute the distance between two points p1 and p2 */ public static double distance(Point p1, Point p2) /** Compute the distance between points (x1, y1) and (x2, y2) */ public static double distance(double x1, double y1, double x2, double y2) **22.8 (All prime numbers up to 10,000,000,000) Write a program that finds all prime numbers up read more..

  • Page - 879

    856 Chapter 22 Developing Efficient Algorithms **22.11 (Geometry: Graham’s algorithm for finding a convex hull) Section  22.10.2 introduced Graham’s algorithm for finding a convex hull for a set of points. Assume that the Java’s coordinate system is used for the points. Implement the algorithm using the following method: /** Return the points that form a convex hull */ read more..

  • Page - 880

    Programming Exercises 857 12,000,000, 14,000,000, 16,000,000, and 18,000,000 using the algorithms in Listings 22.5–22.7. Your program should print a table like this: 8000000 10000000 12000000 14000000 16000000 18000000 Listing 22.5 Listing 22.6 Listing 22.7 FIGURE 22.11 (a) Programming Exercise22.15 displays a non-crossed polygon for a set of points. (b) Two or more sides intersect in a read more..

  • Page - 881

    858 Chapter 22 Developing Efficient Algorithms **22.17 (Closest-pair animation) Write a program that enables the user to add/remove points by clicking the left/right mouse button, and displays a line that connects the pair of nearest points, as shown in Figure 22.4. **22.18 (Binary search animation) Write a program that animates the binary search algo- rithm. Create an array with read more..

  • Page - 882

    Programming Exercises 859 ***22.20 (Game: multiple Sudoku solutions) The complete solution for the Sudoku prob- lem is given in Supplement VI.A. A Sudoku problem may have multiple solu- tions. Modify Sudoku.java in Supplement VI.A to display the total number of the solutions. Display two solutions if multiple solutions exist. ***22.21 (Game: Sudoku) The complete solution for the read more..

  • Page - 883

    860 Chapter 22 Developing Efficient Algorithms ***22.25 (Game: Sudoku) Revise Programming Exercise 22.21 to display all solutions for the Sudoku game, as shown in Figure  22.17a. When you click the Solve button, the program stores all solutions in an ArrayList. Each element in the list is a two-dimensional 9-by-9 grid. If the program has multiple solutions, the Next button read more..

  • Page - 884

    SORTING Objectives ■ To study and analyze time complexity of various sorting algorithms (§§23.2–23.7). ■ To design, implement, and analyze insertion sort (§23.2). ■ To design, implement, and analyze bubble sort (§23.3). ■ To design, implement, and analyze merge sort (§23.4). ■ To design, implement, and analyze quick sort (§23.5). ■ To design and implement a binary heap read more..

  • Page - 885

    862 Chapter 23 Sorting 23.1 Introduction Sorting algorithms are good examples for studying algorithm design and analysis. When presidential candidate Barack Obama visited Google in 2007, Google CEO Eric Schmidt asked Obama the most efficient way to sort a million 32-bit integers (www.youtube .com/watch?v=k4RRi_ntQc8 ). Obama answered that the bubble sort would be the wrong way to go. read more..

  • Page - 886

    23.2 Insertion Sort 863 The algorithm can be expanded and implemented as in Listing 23.1. LISTING 23.1 InsertionSort.java 1 public class InsertionSort { 2 /** The method for sorting the numbers */ 3 public static void insertionSort(int[] list) { 4 for (int i = 1; i < list.length; i++) { 5 /** Insert list[i] into a sorted sublist list[0..i-1] so that 6 read more..

  • Page - 887

    864 Chapter 23 Sorting 11 } 12 13 // Insert the current element into list[k + 1] 14 list[k + 1] = currentElement; 15 } 16 } 17 } The insertionSort(int[] list) method sorts any array of int elements. The method is implemented with a nested for loop. The outer loop (with the loop control variable i) (line 4) is iterated in order read more..

  • Page - 888

    23.3 Bubble Sort 865 Figure 23.3a shows the first pass of a bubble sort on an array of six elements (2 9 5 4 8 1). Compare the elements in the first pair (2 and 9), and no swap is needed because they are already in order. Compare the elements in the second pair (9 and 5), and swap 9 with 5 because 9 is greater than 5. Compare the elements in the third pair (9 and 4), and swap read more..

  • Page - 889

    866 Chapter 23 Sorting The algorithm can be implemented in Listing 23.4. LISTING 23.4 BubbleSort.java 1 public class BubbleSort { 2 /** Bubble sort method */ 3 public static void bubbleSort(int[] list) { 4 boolean needNextPass = true; 5 6 for (int k = 1; k < list.length && needNextPass; k++) { 7 // Array may be sorted and next pass not needed 8 read more..

  • Page - 890

    23.4 Merge Sort 867 23.4 Merge Sort The merge sort algorithm can be described recursively as follows: The algorithm divides the array into two halves and applies a merge sort on each half recursively. After the two halves are sorted, merge them. The algorithm for a merge sort is given in Listing 23.5. LISTING 23.5 Merge Sort Algorithm 1 public static void mergeSort(int[] read more..

  • Page - 891

    868 Chapter 23 Sorting 5 // Merge sort the first half 6 int[] firstHalf = new int[list.length / 2]; 7 System.arraycopy(list, 0, firstHalf, 0, list.length / 2); 8 mergeSort(firstHalf); 9 10 // Merge sort the second half 11 int secondHalfLength = list.length - list.length / 2; 12 int[] secondHalf = new int[secondHalfLength]; 13 System.arraycopy(list, read more..

  • Page - 892

    23.4 Merge Sort 869 in list2. Finally, all the elements in one of the lists are moved to temp. If there are still unmoved elements in list1, copy them to temp (lines 35–36). If there are still unmoved ele- ments in list2, copy them to temp (lines 38–39). Figure 23.5 illustrates how to merge the two arrays list1 (2 4 5 9) and list2 (1 6 7 8). Initially the read more..

  • Page - 893

    870 Chapter 23 Sorting Let T(n) denote the time required for sorting an array of n elements using a merge sort. With- out loss of generality, assume n is a power of 2. The merge sort algorithm splits the array into two subarrays, sorts the subarrays using the same algorithm recursively, and then merges the subarrays. Therefore, T(n) = T ¢n 2 ≤ + T ¢n 2 ≤ + read more..

  • Page - 894

    23.5 Quick Sort 871 list2 pivot list1 5 all elements in list1 <= pivot and 6 all elements in list2 > pivot; 7 quickSort(list1); 8 quickSort(list2); 9 } 10 } Each partition places the pivot in the right place. The selection of the pivot affects the perfor- mance of the algorithm. Ideally, the read more..

  • Page - 895

    872 Chapter 23 Sorting 12 } 13 14 /** Partition the array list[first..last] */ 15 public static int partition(int[] list, int first, int last) { 16 int pivot = list[first]; // Choose the first element as the pivot 17 int low = first + 1; // Index for forward search 18 int high = last; // Index for backward search 19 20 while (high > low) { 21 // Search read more..

  • Page - 896

    23.5 Quick Sort 873 elements and repeats the same search and swap operations until all the elements are searched in a while loop (lines 20–35). The method returns the new index for the pivot that divides the partial array into two parts if the pivot has been moved (line 44). Otherwise, it returns the original index for the pivot (line 47). Figure 23.8 illustrates how read more..

  • Page - 897

    874 Chapter 23 Sorting In the best case, the pivot divides the array each time into two parts of about the same size. Let T(n) denote the time required for sorting an array of n elements using quick sort. Thus, recursive quick sort on partition time two subarrays O(n logn) best-case time FIGURE 23.9 A binary heap is a special complete binary tree. (a) A heap (b) read more..

  • Page - 898

    23.6 Heap Sort 875 Note Heap is a term with many meanings in computer science. In this chapter, heap means a binary heap. Pedagogical Note A heap can be implemented efficiently for inserting keys and for deleting the root. For an interactive demo on how a heap works, go to www.cs.armstrong.edu/liang/animation/web/ Heap.html , as shown in Figure 23.10. heap heap animation on read more..

  • Page - 899

    876 Chapter 23 Sorting Swap the current node with its parent; Now the current node is one level up; } Suppose a heap is initially empty. That heap is shown in Figure 23.12, after adding numbers 3, 5, 1, 19, 11, and 22 in this order. FIGURE 23.12 Elements 3, 5, 1, 19, 11, and 22 are inserted into the heap. (a) After adding 3 (b) After adding 5 (c) After read more..

  • Page - 900

    23.6 Heap Sort 877 Figure 23.15 shows the process of rebuilding a heap after the root, 59, is removed from Figure 23.14d. Move the last node, 17, to the root, as shown in Figure 23.15a. Swap 17 with 44, as shown in Figure 23.15b, and then swap 17 with 30, as shown in Figure 23.15c. FIGURE 23.14 Rebuild the heap after the root 62 is removed. 22 29 14 33 30 17 32 39 44 13 42 59 9 (a) After moving 9 to the root 22 read more..

  • Page - 901

    878 Chapter 23 Sorting LISTING 23.9 Heap.java 1 public class Heap<E extends Comparable<E>> { 2 private java.util.ArrayList<E> list = new java.util.ArrayList<>(); 3 4 /** Create a default heap */ 5 public Heap() { 6 } 7 8 /** Create a heap from an array of objects */ 9 public Heap(E[] objects) { 10 for (int i = 0; i < read more..

  • Page - 902

    23.6 Heap Sort 879 45 int leftChildIndex = 2 * currentIndex + 1; 46 int rightChildIndex = 2 * currentIndex + 2; 47 48 // Find the maximum between two children 49 if (leftChildIndex >= list.size()) break; // The tree is a heap 50 int maxIndex = leftChildIndex; 51 if (rightChildIndex < list.size()) { 52 if (list.get(maxIndex).compareTo( 53 read more..

  • Page - 903

    880 Chapter 23 Sorting 7 // Add elements to the heap 8 for (int i = 0; i < list.length; i++) 9 heap.add(list[i]); 10 11 // Remove elements from the heap 12 for (int i = list.length - 1; i >= 0 ; i--) 13 list[i] = heap.remove(); 14 } 15 16 /** A test method */ 17 public static void main(String[] args) { 18 read more..

  • Page - 904

    23.7 Bucket Sort and Radix Sort 881 23.18 Show the steps of creating a heap using {45, 11, 50, 59, 60, 2, 4, 7, 10}. 23.19 Given the following heap, show the steps of removing all nodes from the heap. 22 29 32 42 62 14 33 39 17 30 44 59 9 13 23.20 Which of the following statements are wrong? 1 Heap<Object> heap1 = new Heap<>(); 2 Heap<Number> heap2 read more..

  • Page - 905

    882 Chapter 23 Sorting // Now move the elements from the buckets back to list int k = 0; // k is an index for list for (int i = 0; i < bucket.length; i++) { if (bucket[i] != null) { for (int j = 0; j < bucket[i].size(); j++) list[k++] = bucket[i].get(j); } } } Clearly, it takes O(n + t) time to sort the list and uses read more..

  • Page - 906

    23.8 External Sort 883 After being removed from the buckets, the elements are in the following order: 9, 34, 45, 59, 230, 231, 331, 343, 345, 453, 454 The elements are now sorted. Radix sort takes O(dn) time to sort n elements with integer keys, where d is the maximum number of the radix positions among all keys. 23.21 Can you sort a list of strings using a read more..

  • Page - 907

    884 Chapter 23 Sorting int values are sorted. They are denoted as S1, S2, c , and Sk, where the last segment, Sk, may contain less than 100000 values. FIGURE 23.18 Sorted segments are merged iteratively. S1 S2 S3 S4 S5 S6 S7 S8 S1,S2 merged S1,S2,S3,S4 merged S5,S6,S7,S8 merged S3,S4 merged S5,S6 merged S7,S8 merged Merge step Merge step Merge step S1,S2,S3,S4,S5,S6,S7,S8 read more..

  • Page - 908

    23.8 External Sort 885 7 new BufferedInputStream(new FileInputStream(originalFile))); 8 DataOutputStream output = new DataOutputStream( 9 new BufferedOutputStream(new FileOutputStream(f1))); 10 11 int numberOfSegments = 0; 12 while (input.available() > 0 ) { 13 numberOfSegments++; 14 int i = 0; 15 for ( ; input.available() > 0 && i < segmentSize; i++) read more..

  • Page - 909

    886 Chapter 23 Sorting Note f1.dat may have one segment more than f2.dat. If so, move the last segment into f3.dat after the merge. Listing 23.13 gives a method that copies the first half of the segments in f1.dat to f2.dat. Listing 23.14 gives a method that merges a pair of segments in f1.dat and f2.dat. Listing 23.15 gives a method that merges two segments. LISTING read more..

  • Page - 910

    23.8 External Sort 887 26 else { 27 intFromF2 = f2.readInt(); 28 } 29 } 30 } 31 32 while (f1.available() > 0 && f1Count++ < segmentSize) { 33 f3.writeInt(f1.readInt()); 34 } 35 36 while (f2.available() > 0 && f2Count++ < segmentSize) { 37 f3.writeInt(f2.readInt()); 38 } 39 } read more..

  • Page - 911

    888 Chapter 23 Sorting 39 merge((numberOfSegments + 1) / 2, segmentSize * 2, 40 f3, f1, f2, targetfile); 41 } 42 else { // Rename f1 as the final sorted file 43 File sortedFile = new File(targetfile); 44 if (sortedFile.exists()) sortedFile.delete(); 45 new File(f1).renameTo(sortedFile); 46 } 47 } 48 49 private read more..

  • Page - 912

    23.8 External Sort 889 99 DataInputStream input = 100 new DataInputStream(new FileInputStream(filename)); 101 for (int i = 0; i < 100 ; i++) 102 System.out.print(input.readInt() + " "); 103 input.close(); 104 } 105 catch (IOException ex) { 106 ex.printStackTrace(); 107 } 108 read more..

  • Page - 913

    890 Chapter 23 Sorting merge steps, the number of segments is reduced to 1. Therefore, the total number of merge steps is log ¢n c ≤ . In each merge step, half the number of segments are read from file f1 and then written into a temporary file f2. The remaining segments in f1 are merged with the segments in f2. The number of I/Os in each merge step is O(n). read more..

  • Page - 914

    Programming Exercises 891 PROGRAMMING EXERCISES Sections 23.3–23.5 23.1 (Generic bubble sort) Write the following two generic methods using bubble sort. The first method sorts the elements using the Comparable interface and the second uses the Comparator interface. public static <E extends Comparable<E>> void bubbleSort(E[] list) public static <E> void bubbleSort(E[] read more..

  • Page - 915

    892 Chapter 23 Sorting Comparator<? super E> comparator) public static <E> boolean ordered(E[] list, Comparator<? super E> comparator, boolean ascending) Section 23.6 23.7 (Min-heap) The heap presented in the text is also known as a max-heap, in which each node is greater than or equal to any of its children. A min-heap is a heap in which each node is read more..

  • Page - 916

    Programming Exercises 893 Section 23.8 *23.14 (Execution time for external sorting) Write a program that obtains the execution time of external sorts for integers of size 5,000,000, 10,000,000, 15,000,000, 20,000,000, 25,000,000, and 30,000,000. Your program should print a table like this: File size 5,000,000 10,000,000 15,000,000 20,000,000 25,000,000 30,000,000 Time Comprehensive *23.15 (Selection read more..

  • Page - 917

    894 Chapter 23 Sorting them back to the array. When the algorithm is finished, clicking the Step button displays a message to inform the user. Clicking the Reset button creates a new random array for a new start. FIGURE 23.21 The program animates radix sort. *23.18 (Merge animation) Write a program that animates the merge of two sorted lists. Create two arrays, list1 and list2, read more..

  • Page - 918

    IMPLEMENTING LISTS, STACKS, QUEUES, AND  PRIORITY QUEUES Objectives ■ To design common features of lists in an interface and provide skeleton implementation in a convenience abstract class (§24.2). ■ To design and implement an array list using an array (§24.3). ■ To design and implement a linked list using a linked structure (§24.4). ■ To design and implement a stack read more..

  • Page - 919

    896 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 24.1 Introduction This chapter focuses on implementing data structures. Lists, stacks, queues, and priority queues are classic data structures typically covered in a data structures course. They are supported in the Java API, and their uses were presented in Chapter 20, Lists, Stacks, Queues, and Priority Queues. This chapter will read more..

  • Page - 920

    24.2 Common Features for Lists 897 LISTING 24.1 MyList.java 1 public interface MyList<E> extends java.lang.Iterable<E> { 2 /** Add a new element at the end of this list */ 3 public void add(E e); 4 5 /** Add a new element at the specified index in this list */ 6 public void add(int index, E e); 7 8 /** Clear the list */ 9 public void read more..

  • Page - 921

    898 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 31 public boolean remove(E e); 32 33 /** Remove the element at the specified position in this list. 34 * Shift any subsequent elements to the left. 35 * Return the element that was removed from the list. */ 36 public E remove(int index); 37 38 /** Replace the element at the read more..

  • Page - 922

    24.2 Common Features for Lists 899 LISTING 24.2 MyAbstractList.java 1 public abstract class MyAbstractList<E> implements MyList<E> { 2 protected int size = 0; // The size of the list 3 4 /** Create a default list */ 5 protected MyAbstractList() { 6 } 7 8 /** Create a list from an array of objects */ 9 protected MyAbstractList(E[] objects) read more..

  • Page - 923

    900 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 24.3 Array Lists An array list is implemented using an array. An array is a fixed-size data structure. Once an array is created, its size cannot be changed. Nevertheless, you can still use arrays to implement dynamic data structures. The trick is to create a larger new array to replace the current array, read more..

  • Page - 924

    24.3 Array Lists 901 LISTING 24.3 MyArrayList.java 1 public class MyArrayList<E> extends MyAbstractList<E> { 2 public static final int INITIAL_CAPACITY = 16; 3 private E[] data = (E[]) new Object[INITIAL_CAPACITY]; 4 5 /** Create a default list */ 6 public MyArrayList() { 7 } 8 9 /** Create a list from an array of read more..

  • Page - 925

    902 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 39 @Override /** Clear the list */ 40 public void clear() { 41 data = (E[])new Object[INITIAL_CAPACITY]; 42 size = 0; 43 } 44 45 @Override /** Return true if this list contains the element */ 46 public boolean contains(E e) { 47 for (int read more..

  • Page - 926

    24.3 Array Lists 903 99 100 return e; 101 } 102 103 @Override /** Replace the element at the specified position 104 * in this list with the specified element. */ 105 public E set(int index, E e) { 106 checkIndex(index); 107 E old = data[index]; 108 data[index] = e; 109 return old; 110 } 111 112 read more..

  • Page - 927

    904 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues The constant INITIAL_CAPACITY (line 2) is used to create an initial array data (line 3). Owing to generics type erasure, you cannot create a generic array using the syntax new e[INITIAL_CAPACITY]. To circumvent this limitation, an array of the Object type is cre- ated in line 3 and cast into E[]. Note read more..

  • Page - 928

    24.3 Array Lists 905 MyArrayList implements Iterable, the elements can be traversed using a for-each loop (lines 35–36). LISTING 24.4 TestMyArrayList.java 1 public class TestMyArrayList { 2 public static void main(String[] args) { 3 // Create a list 4 MyList<String> list = new MyArrayList<String>(); 5 6 // Add elements to the list 7 read more..

  • Page - 929

    906 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 24.7 Show the length of the array in MyArrayList after each of the following statements is executed. 1 MyArrayList<Double> list = new MyArrayList<>(); 2 list.add(1.5); 3 list.trimToSize(); 4 list.add(3.4); 5 list.add(7.4); 6 list.add(17.4); 24.8 What is wrong if lines 11–12 in Listing 24.3, read more..

  • Page - 930

    24.4 Linked Lists 907 add(E e) method for adding an element at the end of the list are efficient. However, the methods add(int index, E e) and remove(int index) are inefficient, because they require shifting a potentially large number of elements. You can use a linked structure to implement a list to improve efficiency for adding and removing an element at the read more..

  • Page - 931

    908 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Step 4: Create the third node and append it to the list, as shown in Figure 24.10a. To append the new node to the list, link the last node in the list with the new node. The new node is now the tail node, so you should move tail to point to this new node, as shown in Figure 24.10b. FIGURE read more..

  • Page - 932

    24.4 Linked Lists 909 Assuming that the class has been implemented, Listing 24.5 gives a test program that uses the class. LISTING 24.5 TestMyLinkedList.java 1 public class TestMyLinkedList { 2 /** Main method */ 3 public static void main(String[] args) { 4 // Create a list for strings 5 MyLinkedList<String> list = new MyLinkedList<>(); 6 7 // Add elements read more..

  • Page - 933

    910 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 32 33 list.remove(2); // Remove the element at index 2 34 System.out.println("(9) " + list); 35 36 list.remove(list.size() - 1); // Remove the last element 37 System.out.print("(10) " + list + "\n(11) "); 38 39 for (String s: list) 40 read more..

  • Page - 934

    24.4 Linked Lists 911 If the list is empty (line 7), both head and tail will point to this new node (line 8). After the node is created, size should be increased by 1 (line 5). 24.4.3.2 Implementing addLast(e) The addLast(e) method creates a node to hold the element and appends the node at the end of the list. It can be implemented as follows: 1 public read more..

  • Page - 935

    912 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 24.4.3.3 Implementing add(index, e) The add(index, e) method inserts an element into the list at the specified index. It can be implemented as follows: 1 public void add(int index, E e) { 2 if (index == 0) addFirst(e); // Insert first 3 else if (index >= size) addLast(e); // Insert last 4 read more..

  • Page - 936

    24.4 Linked Lists 913 4 Node<E> temp = head; // Keep the first node temporarily 5 head = head.next; // Move head to point to next node 6 size--; // Reduce size by 1 7 if (head == null) tail = null; // List becomes empty 8 return temp.element; // Return the deleted element 9 } 10 } Consider two cases: 1. If the list is empty, read more..

  • Page - 937

    914 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 24.4.3.5 Implementing removeLast() The removeLast() method removes the last element from the list. It can be implemented as follows: 1 public E removeLast() { 2 if (size == 0) return null; // Nothing to remove 3 else if (size == 1) { // Only one element in the list 4 Node<E> read more..

  • Page - 938

    24.4 Linked Lists 915 24.4.3.6 Implementing remove(index) The remove(index) method finds the node at the specified index and then removes it. It can be implemented as follows: 1 public E remove(int index) { 2 if (index < 0 || index >= size) return null; // Out of range 3 else if (index == 0) return removeFirst(); // Remove first 4 else if (index == read more..

  • Page - 939

    916 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues next, and remove (lines 134–149). This implementation uses current to point to the current position of the element being traversed (line 132). Initially, current points to the head of the list. LISTING 24.6 MyLinkedList.java 1 public class MyLinkedList<E> extends MyAbstractList<E> { 2 private read more..

  • Page - 940

    24.4 Linked Lists 917 55 /** Remove the last node and 56 * return the object that is contained in the removed node. */ 57 public E removeLast() { 58 // Implemented in Section 24.4.3.5, so omitted here 59 } 60 61 @Override /** Remove the element at the specified position in this 62 * list. Return the element that was removed read more..

  • Page - 941

    918 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 115 return 0; 116 } 117 118 @Override /** Replace the element at the specified position 119 * in this list with the specified element. */ 120 public E set(int index, E e) { 121 System.out.println("Implementation left as an exercise"); 122 return null; 123 } read more..

  • Page - 942

    24.4 Linked Lists 919 24.4.5 Variations of Linked Lists The linked list introduced in the preceding sections is known as a singly linked list. It contains a pointer to the list’s first node, and each node contains a pointer to the next node sequentially. Several variations of the linked list are useful in certain applications. A circular, singly linked list is like a read more..

  • Page - 943

    920 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues A doubly linked list contains nodes with two pointers. One points to the next node and the other to the previous node, as shown in Figure 24.18b. These two pointers are conveniently called a forward pointer and a backward pointer. Thus, a doubly linked list can be traversed for- ward and backward. The read more..

  • Page - 944

    24.5 Stacks and Queues 921 Pedagogical Note For an interactive demo on how stacks and queues work, go to www.cs.armstrong.edu/ liang/animation/web/Stack.html , and www.cs.armstrong.edu/liang/animation/web/Queue.html , as shown in Figure 24.20. stack and queue animation on Companion Website FIGURE 24.20 The animation tool enables you to see how stacks and queues work. (a) Stack animation read more..

  • Page - 945

    922 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues LISTING 24.7 GenericQueue.java 1 public class GenericQueue<E> { 2 private java.util.LinkedList<E> list 3= new java.util.LinkedList<>(); 4 5 public void enqueue(E e) { 6 list.addLast(e); 7 } 8 9 public E dequeue() { 10 return list.removeFirst(); 11 } 12 13 public read more..

  • Page - 946

    24.5 Stacks and Queues 923 18 // Remove elements from the stack 19 System.out.println("(4) " + stack.pop()); 20 System.out.println("(5) " + stack.pop()); 21 System.out.println("(6) " + stack); 22 23 // Create a queue 24 GenericQueue<String> queue = new GenericQueue<>(); 25 26 // Add elements to the queue 27 read more..

  • Page - 947

    924 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues 24.6 Priority Queues Priority queues can be implemented using heaps. An ordinary queue is a first-in, first-out data structure. Elements are appended to the end of the queue and removed from the beginning. In a priority queue, elements are assigned with priorities. When accessing elements, the element with the read more..

  • Page - 948

    12 priorityQueue.enqueue(patient3); 13 priorityQueue.enqueue(patient4); 14 15 while (priorityQueue.getSize() > 0 ) 16 System.out.print(priorityQueue.dequeue() + " "); 17 } 18 19 static class Patient implements Comparable<Patient> { 20 private String name; 21 private int priority; 22 23 public Patient(String name, int priority) { 24 this.name read more..

  • Page - 949

    926 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues QUIZ Answer the quiz for this chapter online at www.cs.armstrong.edu/liang/intro10e/test.html . PROGRAMMING EXERCISES 24.1 (Add set operations in MyList) Define the following methods in MyList and implement them in MyAbstractList: /** Adds the elements in otherList to this list. * Returns true if this list changed as read more..

  • Page - 950

    Programming Exercises 927 and listIterator(int index). Both return an  instance of java.util. ListIterator<E>. The former sets the cursor to the head of the list and the latter to the element at the specified index. 24.4 (Use the GenericStack class) Write a program that displays the first 50 prime numbers in descending order. Use a stack to store the prime numbers. 24.5 read more..

  • Page - 951

    928 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues *24.12 (Animation: queue) Write a program to animate the enqueue and dequeue operations on a queue, as shown in Figure 24.20b. *24.13 (Fibonacci number iterator) Define an iterator class named FibonacciIterator for iterating Fibonacci numbers. The constructor takes an argument that specifies the limit of the maximum read more..

  • Page - 952

    BINARY SEARCH TREES Objectives ■ To design and implement a binary search tree (§25.2). ■ To represent binary trees using linked data structures (§25.2.1). ■ To search an element in a binary search tree (§25.2.2). ■ To insert an element into a binary search tree (§25.2.3). ■ To traverse elements in a binary tree (§25.2.4). ■ To design and implement the Tree read more..

  • Page - 953

    930 Chapter 25 Binary Search Trees 25.1 Introduction A tree is a classic data structure with many important applications. A tree provides a hierarchical organization in which data are stored in the nodes. This chapter introduces binary search trees. You will learn how to construct a binary search tree, how to search an element, insert an element, delete an element, and read more..

  • Page - 954

    25.2 Binary Search Trees 931 25.2.1 Representing Binary Search Trees A binary tree can be represented using a set of linked nodes. Each node contains a value and two links named left and right that reference the left child and right child, respectively, as shown in Figure 25.3. FIGURE 25.2 The animation tool enables you to insert, delete, and search elements. FIGURE read more..

  • Page - 955

    932 Chapter 25 Binary Search Trees The variable root refers to the root node of the tree. If the tree is empty, root is null. The following code creates the first three nodes of the tree in Figure 25.3. // Create the root node TreeNode<Integer> root = new TreeNode<>(60); // Create the left child node root.left = new TreeNode<>(55); // Create the right read more..

  • Page - 956

    25.2 Binary Search Trees 933 8 if (e < the value in current.element) { 9 parent = current; // Keep the parent 10 current = current.left; // Go left 11 } 12 else if (e > the value in current.element) { 13 parent = current; // Keep the parent 14 current = read more..

  • Page - 957

    934 Chapter 25 Binary Search Trees Figure 25.5, each directory is an internal node and a file is a leaf node. You can apply postorder to get the size of each file and subdirectory before finding the size of the root directory. With preorder traversal, the current node is visited first, then recursively the left subtree of the current node, and finally the right subtree of the current node read more..

  • Page - 958

    25.2 Binary Search Trees 935 You can use the following tree to help remember inorder, postorder, and preorder. + 1 2 FIGURE 25.7 The Tree interface defines common operations for trees, and the AbstractTree class partially implements Tree. Returns true if the specified element is in the tree. Returns true if the element is added successfully. Returns true if the element is read more..

  • Page - 959

    936 Chapter 25 Binary Search Trees 9 /** Delete the specified element from the tree. 10 * Return true if the element is deleted successfully. */ 11 public boolean delete(E e); 12 13 /** Inorder traversal from the root*/ 14 public void inorder(); 15 16 /** Postorder traversal from the root */ 17 public void postorder(); 18 19 /** Preorder traversal from the root */ 20 read more..

  • Page - 960

    25.2 Binary Search Trees 937 16 public boolean isEmpty() { 17 return getSize() == 0; 18 } 19 } LISTING 25.5 BST.java 1 public class BST<E extends Comparable<E>> 2 extends AbstractTree<E> { 3 protected TreeNode<E> root; 4 protected int size = 0; 5 6 /** Create a default binary search tree */ 7 public BST() { read more..

  • Page - 961

    938 Chapter 25 Binary Search Trees 54 55 // Create the new node and attach it to the parent node 56 if (e.compareTo(parent.element) < 0 ) 57 parent.left = createNewNode(e); 58 else 59 parent.right = createNewNode(e); 60 } 61 62 size++; 63 return true; // Element inserted successfully 64 read more..

  • Page - 962

    25.2 Binary Search Trees 939 114 protected TreeNode<E> right; 115 116 public TreeNode(E e) { 117 element = e; 118 } 119 } 120 121 @Override /** Get the number of nodes in the tree */ 122 public int getSize() { 123 return size; 124 } 125 126 /** Returns the root of the tree */ 127 public TreeNode<E> getRoot() { 128 read more..

  • Page - 963

    940 Chapter 25 Binary Search Trees 174 175 // Case 1: current has no left child 176 if (current.left == null) { 177 // Connect the parent with the right child of the current node 178 if (parent == null) { 179 root = current.right; 180 } 181 else { 182 if (e.compareTo(parent.element) < 0 ) 183 parent.left read more..

  • Page - 964

    25.2 Binary Search Trees 941 234 } 235 236 /** Inorder traversal from a subtree */ 237 private void inorder(TreeNode<E> root) { 238 if (root == null) return; 239 inorder(root.left); 240 list.add(root.element); 241 inorder(root.right); 242 } 243 244 @Override /** More elements for traversing? */ 245 read more..

  • Page - 965

    942 Chapter 25 Binary Search Trees LISTING 25.6 TestBST.java 1 public class TestBST { 2 public static void main(String[] args) { 3 // Create a BST 4 BST<String> tree = new BST<>(); 5 tree.insert("George"); 6 tree.insert("Michael"); 7 tree.insert("Tom"); 8 tree.insert("Adam"); 9 read more..

  • Page - 966

    25.3 Deleting Elements from a BST 943 25.1 Show the result of inserting 44 into Figure 25.4b. 25.2 Show the inorder, preorder, and postorder of traversing the elements in the binary tree shown in Figure 25.1b. 25.3 If a set of elements is inserted into a BST in two different orders, will the two cor- responding BSTs look the same? Will the inorder traversal be the read more..

  • Page - 967

    944 Chapter 25 Binary Search Trees Note If the current node is a leaf, it falls into Case 1. For example, to delete element 16 in Figure 25.11a, connect its right child (in this case, it is null) to the parent of node 16. Case 2: The current node has a left child. Let rightMost point to the node that contains the largest element in the left subtree of the current node and read more..

  • Page - 968

    25.3 Deleting Elements from a BST 945 The algorithm for deleting an element from a binary search tree can be described in Listing 25.7. LISTING 25.7 Deleting an Element from a BST 1 boolean delete(E e) { 2 Locate element e in the tree; 3 if element e is not found delete method not in the tree FIGURE 25.12 Case 2: The current node has a left read more..

  • Page - 969

    946 Chapter 25 Binary Search Trees 4 return true; 5 6 Let current be the node that contains e and parent be 7 the parent of current; 8 9 if (current has no left child) // Case 1 10 Connect the right child of 11 current with parent; now current is not referenced, so 12 it is eliminated; 13 read more..

  • Page - 970

    25.3 Deleting Elements from a BST 947 23 printTree(tree); 24 } 25 26 public static void printTree(BST tree) { 27 // Traverse tree 28 System.out.print("Inorder (sorted): "); 29 tree.inorder(); 30 System.out.print("\nPostorder: "); 31 tree.postorder(); 32 System.out.print("\nPreorder: "); 33 read more..

  • Page - 971

    948 Chapter 25 Binary Search Trees Note It is obvious that the time complexity for the inorder, preorder, and postorder is O(n), since each node is traversed only once. The time complexity for search, insertion, and deletion is the height of the tree. In the worst case, the height of the tree is O(n). If a tree is well-balanced, the height would be O(logn). We will read more..

  • Page - 972

    25.4 Tree Visualization and MVC 949 25.4 Tree Visualization and MVC You can use recursion to display a binary tree. Pedagogical Note One challenge facing the data-structure course is to motivate students. Displaying a binary tree graphically will not only help you understand the working of a binary tree but perhaps also stimulate your interest in programming. This section read more..

  • Page - 973

    950 Chapter 25 Binary Search Trees 27 tfKey, btInsert, btDelete); 28 hBox.setAlignment(Pos.CENTER); 29 pane.setBottom(hBox); 30 31 btInsert.setOnAction(e -> { 32 int key = Integer.parseInt(tfKey.getText()); 33 if (tree.search(key)) { // key is in the tree already 34 view.displayTree(); 35 read more..

  • Page - 974

    25.4 Tree Visualization and MVC 951 21 public void displayTree() { 22 this.getChildren().clear(); // Clear the pane 23 if (tree.getRoot() != null) { 24 // Display tree recursively 25 displayTree(tree.getRoot(), getWidth() / 2, vGap, 26 getWidth() / 4); 27 } 28 } 29 30 /** Display a subtree rooted at position (x, y) */ 31 private void read more..

  • Page - 975

    952 Chapter 25 Binary Search Trees The MVC architecture separates data storage and handling from the visual representation of the data. It has two major benefits: ■ It makes multiple views possible so that data can be shared through the same model. For example, you can create a new view that displays the tree with the root on the left and tree grows horizontally read more..

  • Page - 976

    25.5 Iterators 953 The Tree interface extends java.lang.Iterable. Since BST is a subclass of AbstractTree and AbstractTree implements Tree, BST is a subtype of Iterable. The Iterable interface contains the iterator() method that returns an instance of java.util.Iterator. You can traverse a binary tree in inorder, preorder, or postorder. Since inorder is used frequently, we read more..

  • Page - 977

    954 Chapter 25 Binary Search Trees The implementation of the iterator is not efficient. Every time you remove an element through the iterator, the whole list is rebuilt (line 261 in Listing 25.5 BST.java). The client should always use the delete method in the BinraryTree class to remove an element. To prevent the user from using the remove method in the iterator, read more..

  • Page - 978

    25.6 Case Study: Data Compression 955 The coding tree is also used for decoding a sequence of bits into characters. To do so, start with the first bit in the sequence and determine whether to go to the left or right branch of the tree’s root based on the bit value. Consider the next bit and continue to go down to the left or right branch based on the bit read more..

  • Page - 979

    956 Chapter 25 Binary Search Trees The algorithm used here is an example of a greedy algorithm. A greedy algorithm is often used in solving optimization problems. The algorithm makes the choice that is optimal locally in the hope that this choice will lead to a globally optimal solution. In this case, the algorithm always chooses two trees with the smallest weight and read more..

  • Page - 980

    25.6 Case Study: Data Compression 957 20 i, (char)i + "", counts[i], codes[i]); 21 } 22 23 /** Get Huffman codes for the characters 24 * This method is called once after a Huffman tree is built 25 */ 26 public static String[] getCode(Tree.Node root) { 27 if (root == null) return null; 28 String[] codes read more..

  • Page - 981

    958 Chapter 25 Binary Search Trees 80 public Tree(Tree t1, Tree t2) { 81 root = new Node(); 82 root.left = t1.root; 83 root.right = t2.root; 84 root.weight = t1.root.weight + t2.root.weight; 85 } 86 87 /** Create a tree containing a leaf node */ 88 public Tree(int weight, read more..

  • Page - 982

    Quiz 959 The program obtains a Huffman coding tree based on counts (line 14). The tree con- sists of linked nodes. The Node class is defined in lines 102–118. Each node consists of properties element (storing character), weight (storing weight of the subtree under this node), left (linking to the left subtree), right (linking to the right subtree), and code read more..

  • Page - 983

    960 Chapter 25 Binary Search Trees PROGRAMMING EXERCISES Sections 25.2–25.6 *25.1 (Add new methods in BST) Add the following new methods in BST. /** Displays the nodes in a breadth-first traversal */ public void breadthFirstTraversal() /** Returns the height of this binary tree */ public int height() *25.2 (Test full binary tree) A full binary tree is a binary tree with read more..

  • Page - 984

    Programming Exercises 961 25.10 (Preorder iterator) Add the following method in the BST class that returns an iterator for traversing the elements in a BST in preorder. /** Returns an iterator for traversing the elements in preorder */ java.util.Iterator<E> preorderIterator() 25.11 (Display tree) Write a new view class that displays the tree horizontally with the root on the read more..

  • Page - 985

    962 Chapter 25 Binary Search Trees *25.14 (Generic BST using Comparator) Revise BST in Listing 25.5, using a generic parameter and a Comparator for comparing objects. Define a new constructor with a Comparator as its argument as follows: BST(Comparator<? super E> comparator) *25.15 (Parent reference for BST) Redefine TreeNode by adding a reference to a node’s read more..

  • Page - 986

    Programming Exercises 963 ***25.18 (Compress a file) Write a program that compresses a source file into a target file using the Huffman coding method. First use ObjectOutputStream to output the Huffman codes into the target file, and then use BitOutputStream in Programming Exercise 17.17 to output the encoded binary contents to the tar- get file. Pass the files from the read more..

  • Page - 987

    964 Chapter 25 Binary Search Trees objects and the weight of each object. The program displays the total number of containers needed to pack the objects and the contents of each container. Here is a sample run of the program: Enter the number of objects: 6 Enter the weights of the objects: 7 5 2 3 5 8 Container 1 contains objects with weight 2 3 5 Container 2 read more..

  • Page - 988

    AVL TREES Objectives ■ To know what an AVL tree is (§26.1). ■ To understand how to rebalance a tree using the LL rotation, LR rotation, RR rotation, and RL rotation (§26.2). ■ To design the AVLTree class by extending the BST class (§26.3). ■ To insert elements into an AVL tree (§26.4). ■ To implement tree rebalancing (§26.5). ■ To delete elements from an AVL read more..

  • Page - 989

    966 Chapter 26 AVL Trees 26.1 Introduction AVL Tree is a balanced binary search tree. Chapter  25 introduced binary search trees. The search, insertion, and deletion times for a binary tree depend on the height of the tree. In the worst case, the height is O(n). If a tree is perfectly balanced–i.e., a complete binary tree—its height is log n. Can we maintain a read more..

  • Page - 990

    26.2 Rebalancing Trees 967 LL rotation: An LL imbalance occurs at a node A, such that A has a balance factor of -2 and a left child B with a balance factor of -1 or 0, as shown in Figure 26.2a. This type of imbalance can be fixed by performing a single right rotation at A, as shown in Figure 26.2b. RR rotation: An RR imbalance occurs at a node A, read more..

  • Page - 991

    968 Chapter 26 AVL Trees FIGURE 26.4 An LR rotation fixes an LR imbalance. B 0 or 1 0 or 1 C 0 T2 T1 hh A T4 T3 h h (a) (b) A 2 B 1 T1 T4 h h 1, 0 or 1 C T3 T2 h h T2 and T3 may have different heights, but at least one has height of h. FIGURE 26.5 An RL rotation fixes an RL imbalance. A 0 or 1 0 or 1 C 0 T2 T1 hh B T4 T3 h h (a) (b) A 2 B 1 T4 T1 read more..

  • Page - 992

    26.3 Designing Classes for AVL Trees 969 26.3 Designing Classes for AVL Trees Since an AVL tree is a binary search tree, AVLTree is designed as a subclass of BST. An AVL tree is a binary tree, so you can define the AVLTree class to extend the BST class, as shown in Figure 26.7. The BST and TreeNode classes were defined in Section 25.2.5. Key Point FIGURE read more..

  • Page - 993

    970 Chapter 26 AVL Trees In the BST class, the createNewNode() method creates a TreeNode object. This method is overridden in the AVLTree class to create an AVLTreeNode. Note that the return type of the createNewNode() method in the BST class is TreeNode, but the return type of the createNewNode() method in the AVLTree class is AVLTreeNode. This is fine, read more..

  • Page - 994

    26.5 Implementing Rotations 971 26.8 For the AVL tree in Figure  26.6a, show the new AVL tree after adding element 50. What rotation do you perform in order to rebalance the tree? Which node was unbalanced? 26.9 For the AVL tree in Figure  26.6a, show the new AVL tree after adding element 80. What rotation do you perform in order to rebalance the tree? Which node read more..

  • Page - 995

    972 Chapter 26 AVL Trees 26.6 Implementing the delete Method Deleting an element from an AVL tree is the same as deleing it from a BST, except that the tree may need to be rebalanced. As discussed in Section 25.3, Deleting Elements from a BST, to delete an element from a binary tree, the algorithm first locates the node that contains the element. Let current point to read more..

  • Page - 996

    26.7 The AVLTree Class 973 4 } 5 6 /** Create an AVL tree from an array of objects */ 7 public AVLTree(E[] objects) { 8 super(objects); 9 } 10 11 @Override /** Override createNewNode to create an AVLTreeNode */ 12 protected AVLTreeNode<E> createNewNode(E e) { 13 return new AVLTreeNode<E>(e); 14 } 15 16 read more..

  • Page - 997

    974 Chapter 26 AVL Trees 63 if (balanceFactor((AVLTreeNode<E>)A.right) >= 0 ) { 64 balanceRR(A, parentOfA); // Perform RR rotation 65 } 66 else { 67 balanceRL(A, parentOfA); // Perform RL rotation 68 } 69 } 70 } 71 read more..

  • Page - 998

    26.7 The AVLTree Class 975 121 } 122 123 A.left = C.right; // Make T3 the left subtree of A 124 B.right = C.left; // Make T2 the right subtree of B 125 C.left = B; 126 C.right = A; 127 128 // Adjust heights 129 updateHeight((AVLTreeNode<E>)A); 130 updateHeight((AVLTreeNode<E>)B); 131 read more..

  • Page - 999

    976 Chapter 26 AVL Trees 179 updateHeight((AVLTreeNode<E>)A); 180 updateHeight((AVLTreeNode<E>)B); 181 updateHeight((AVLTreeNode<E>)C); 182 } 183 184 @Override /** Delete an element from the AVL tree. 185 * Return true if the element is deleted successfully 186 * Return false if the element is not in the tree */ 187 public read more..

  • Page - 1000

    26.7 The AVLTree Class 977 238 // Replace the element in current by the element in rightMost 239 current.element = rightMost.element; 240 241 // Eliminate rightmost node 242 if (parentOfRightMost.right == rightMost) 243 parentOfRightMost.right = rightMost.left; 244 else 245 // Special case: parentOfRightMost is current 246 read more..

  • Page - 1001

    978 Chapter 26 AVL Trees 26.8 Testing the AVLTree Class This section gives an example of using the AVLTree class. Listing 26.4 gives a test program. The program creates an AVLTree initialized with an array of the integers 25, 20, and 5 (lines 4–5), inserts elements in lines 9–18, and deletes elements in lines 22–28. Since AVLTree is a subclass of BST and read more..

  • Page - 1002

    26.8 Testing the AVLTree Class 979 Figure 26.10 shows how the tree evolves as elements are added to the tree. After 25 and 20 are added, the tree is as shown in Figure 26.10a. 5 is inserted as a left child of 20, as shown in Figure 26.10b. The tree is not balanced. It is left-heavy at node 25. Perform an LL rotation to result in an AVL tree, as shown in Figure 26.10c. After inserting 34, the tree is read more..

  • Page - 1003

    980 Chapter 26 AVL Trees Figure 26.11 shows how the tree evolves as elements are deleted. After deleting 34, 30, and 50, the tree is as shown in Figure 26.11b. The tree is not balanced. Perform an LL rotation to result in an AVL tree, as shown in Figure 26.11c. After deleting 5, the tree is as shown in Figure 26.11d. The tree is not balanced. Perform an RL rotation to result in an AVL tree, as shown read more..

  • Page - 1004

    26.9 AVL Tree Time Complexity Analysis 981 26.9 AVL Tree Time Complexity Analysis Since the height of an AVL tree is O(log n), the time complexity of the search, insert, and delete methods in AVLTree is O(log n). The time complexity of the search, insert, and delete methods in AVLTree depends on the height of the tree. We can prove that the height of the tree read more..

  • Page - 1005

    982 Chapter 26 AVL Trees CHAPTER SUMMARY 1. An AVL tree is a well-balanced binary tree. In an AVL tree, the difference between the heights of two subtrees for every node is 0 or 1. 2. The process for inserting or deleting an element in an AVL tree is the same as in a regu- lar binary search tree. The difference is that you may have to rebalance the read more..

  • Page - 1006

    Programming Exercises 983 a node v is one more than the sum of the sizes of its two children. Figure 26.12 shows an AVL tree and the size value for each node in the tree. FIGURE 26.12 The size data field in AVLTreeNode stores the number of nodes in the sub- tree rooted at the node. 20 5 25 34 30 50 size: 6 size: 1 size: 2 size: 1 size: 1 size: 3 read more..

  • Page - 1007

    This page intentionally left blank read more..

  • Page - 1008

    HASHING Objectives ■ To understand what hashing is and what hashing is used for (§27.2). ■ To obtain the hash code for an object and design the hash function to map a key to an index (§27.3). ■ To handle collisions using open addressing (§27.4). ■ To know the differences among linear probing, quadratic probing, and double hashing (§27.4). ■ To handle collisions read more..

  • Page - 1009

    986 Chapter 27 Hashing 27.1 Introduction Hashing is superefficient. It takes O(1) time to search, insert, and delete an element using hashing. The preceding chapter introduced binary search trees. An element can be found in O(log n) time in a well-balanced search tree. Is there a more efficient way to search for an element in a container? This chapter introduces a technique read more..

  • Page - 1010

    27.3 Hash Functions and Hash Codes 987 function. When two or more keys are mapped to the same hash value, we say that a collision has occurred. Although there are ways to deal with collisions, which are discussed later in this chapter, it is better to avoid collisions in the first place. Thus, you should design a fast and easy-to-compute hash function that minimizes read more..

  • Page - 1011

    988 Chapter 27 Hashing it will produce a lot of collisions if the search keys contain the same letters, such as tod and dot. A better approach is to generate a hash code that takes the position of characters into con- sideration. Specifically, let the hash code be s0*b (n - 1) + s1*b (n - 2) + c + sn-1 where si is s.charAt(i). This expression is a polynomial for read more..

  • Page - 1012

    27.4 Handling Collisions Using Open Addressing 989 This is the same as h(hashCode) = supplementalHash(hashCode) & (N – 1) since N is a value of the power of 2. 27.2 What is a hash code? What is the hash code for Byte, Short, Integer, and Character? 27.3 How is the hash code for a Float object computed? 27.4 How is the hash code for a Long object computed? read more..

  • Page - 1013

    990 Chapter 27 Hashing To search for an entry in the hash table, obtain the index, say k, from the hash function for the key. Check whether hashTable[k % N] contains the entry. If not, check whether hashTable[(k+1) % N] contains the entry, and so on, until it is found, or an empty cell is reached. To remove an entry from the hash table, search the entry that read more..

  • Page - 1014

    27.4 Handling Collisions Using Open Addressing 991 Quadratic probing works in the same way as linear probing except for a change in the search sequence. Quadratic probing avoids linear probing’s clustering problem, but it has its own clustering problem, called secondary clustering; that is, the entries that collide with an occupied entry use the same probe sequence. Linear read more..

  • Page - 1015

    992 Chapter 27 Hashing FIGURE 27.5 The animation tool shows how quadratic probing works. FIGURE 27.6 The secondary hash function in a double hashing determines the increment of the next index in the probe sequence. 0 1 2 3 4 5 6 7 8 9 10 key: 45 key: 4 key: 58 key: 28 key: 21 h(12) 0 1 2 3 4 5 6 7 8 9 10 key: 45 key: 4 key: 58 key: 28 key: 21 h(12) + h'(12) 0 1 2 read more..

  • Page - 1016

    27.6 Load Factor and Rehashing 993 27.12 What is secondary clustering? 27.13 Show the hash table of size 11 after inserting entries with keys 34, 29, 53, 44, 120, 39, 45, and 40, using linear probing. 27.14 Show the hash table of size 11 after inserting entries with keys 34, 29, 53, 44, 120, 39, 45, and 40, using quadratic probing. 27.15 Show the hash table of read more..

  • Page - 1017

    994 Chapter 27 Hashing As l increases, the probability of a collision increases. Studies show that you should maintain the load factor under 0.5 for the open addressing scheme and under 0.9 for the separate chaining scheme. Keeping the load factor under a certain threshold is important for the performance of hash- ing. In the implementation of the java.util.HashMap class read more..

  • Page - 1018

    27.7 Implementing a Map Using Hashing 995 27.19 Assume the hash table has the initial size 4 and its load factor is 0.5; show the hash table after inserting entries with the keys 34, 29, 53, 44, 120, 39, 45, and 40, using separate chaining. 27.7 Implementing a Map Using Hashing A map can be implemented using hashing. Now you understand the concept of hashing. You read more..

  • Page - 1019

    996 Chapter 27 Hashing How do you implement MyHashMap? If you use an ArrayList and store a new entry at the end of the list, the search time will be O(n). If you implement MyHashMap using a binary tree, the search time will be O(log n) if the tree is well balanced. Nevertheless, you can imple- ment MyHashMap using hashing to obtain an O(1) time search algorithm. read more..

  • Page - 1020

    27.7 Implementing a Map Using Hashing 997 53 @Override 54 public String toString() { 55 return "[" + key + ", " + value + "]"; 56 } 57 } 58 } LISTING 27.2 MyHashMap.java 1 import java.util.LinkedList; 2 3 public class MyHashMap<K, V> implements MyMap<K, V> { 4 // Define the default hash-table read more..

  • Page - 1021

    998 Chapter 27 Hashing 53 54 @Override /** Return true if the specified key is in the map */ 55 public boolean containsKey(K key) { 56 if (get(key) != null) 57 return true; 58 else 59 return false; 60 } 61 62 @Override /** Return true if this map contains the value */ 63 public boolean containsValue(V value) { 64 for (int read more..

  • Page - 1022

    27.7 Implementing a Map Using Hashing 999 113 114 for (int i = 0; i < capacity; i++) { 115 if (table[i] != null) { 116 LinkedList<Entry<K, V>> bucket = table[i]; 117 for (Entry<K, V> entry: bucket) 118 set.add(entry.getKey()); 119 } 120 } 121 122 return set; 123 } 124 125 read more..

  • Page - 1023

    1000 Chapter 27 Hashing 173 size—–; // Decrease size 174 break; // Remove just one entry that matches the key 175 } 176 } 177 } 178 179 @Override /** Return the number of entries in this map */ 180 public int size() { 181 return size; 182 } 183 184 @Override /** Return a set consisting read more..

  • Page - 1024

    27.7 Implementing a Map Using Hashing 1001 233 table = new LinkedList[capacity]; // Create a new hash table 234 size = 0; // Reset size to 0 235 236 for (Entry<K, V> entry: set) { 237 put(entry.getKey(), entry.getValue()); // Store to new table 238 } 239 } 240 241 @Override /** Return a string read more..

  • Page - 1025

    1002 Chapter 27 Hashing the key is new in the map, the new entry is created in the map (line 156). Before inserting the new entry, the method checks whether the size exceeds the load-factor threshold (line 141). If so, the program invokes rehash() (line 145) to increase the capacity and store entries into the new larger hash table. The rehash() method first copies all read more..

  • Page - 1026

    27.7 Implementing a Map Using Hashing 1003 9 map.put("Smith", 65); 10 11 System.out.println("Entries in map: " + map); 12 13 System.out.println("The age for Lewis is " + 14 map.get("Lewis")); 15 16 System.out.println("Is Smith in the map? " + 17 read more..

  • Page - 1027

    1004 Chapter 27 Hashing 27.8 Implementing Set Using Hashing A hash set can be implemented using a hash map. A set (introduced in Chapter 21) is a data structure that stores distinct values. The Java Collections Framework defines the java.util.Set interface for modeling sets. Three concrete implemen- tations are java.util.HashSet, java.util.LinkedHashSet, and java.util.TreeSet. java.util.HashSet is read more..

  • Page - 1028

    27.8 Implementing Set Using Hashing 1005 6 public boolean contains(E e); 7 8 /** Add an element to the set */ 9 public boolean add(E e); 10 11 /** Remove the element from the set */ 12 public boolean remove(E e); 13 14 /** Return true if the set doesn't contain any elements */ 15 public boolean isEmpty(); 16 17 /** Return the number of elements in the set read more..

  • Page - 1029

    1006 Chapter 27 Hashing 43 44 this.loadFactorThreshold = loadFactorThreshold; 45 table = new LinkedList[capacity]; 46 } 47 48 @Override /** Remove all elements from this set */ 49 public void clear() { 50 size = 0; 51 removeElements(); 52 } 53 54 @Override /** Return true if the element is read more..

  • Page - 1030

    27.8 Implementing Set Using Hashing 1007 103 LinkedList<E> bucket = table[bucketIndex]; 104 for (E element: bucket) 105 if (e.equals(element)) { 106 bucket.remove(element); 107 break; 108 } 109 } 110 111 size——; // Decrease size 112 113 return true; 114 } 115 116 @Override /** Return true read more..

  • Page - 1031

    1008 Chapter 27 Hashing 163 } 164 165 /** Hash function */ 166 private int hash(int hashCode) { 167 return supplementalHash(hashCode) & (capacity - 1); 168 } 169 170 /** Ensure the hashing is evenly distributed */ 171 private static int supplementalHash(int h) { 172 h ^= (h >>> 20) ^ (h >>> 12); 173 return h ^ (h >>> 7) ^ (h read more..

  • Page - 1032

    27.8 Implementing Set Using Hashing 1009 223 public String toString() { 224 java.util.ArrayList<E> list = setToList(); 225 StringBuilder builder = new StringBuilder("["); 226 227 // Add the elements except the last one to the string builder 228 for (int i = 0; i < list.size() - 1 ; i++) { 229 builder.append(list.get(i) + ", read more..

  • Page - 1033

    1010 Chapter 27 Hashing (line 141). The variable current points to the element in the list. Initially, current is 0 (line 135), which points to the first element in the list. MyHashSetIterator implements the methods hasNext(), next(), and remove() in java.util.Iterator. Invoking hasNext() returns true if current < list.size(). Invoking next() returns the current element and read more..

  • Page - 1034

    Chapter Summary 1011 The program creates a set using MyHashSet (line 4) and adds five elements to the set (lines 5–9). Line 5 adds Smith and line 9 adds Smith again. Since only nonduplicate elements are stored in the set, Smith appears in the set only once. The set actually has four elements. The program displays the elements (line 11), gets its size (line read more..

  • Page - 1035

    1012 Chapter 27 Hashing an integer value called a hash code, then compresses the hash code into an index to the hash table. 4. A collision occurs when two keys are mapped to the same index in a hash table. Gener- ally, there are two ways for handling collisions: open addressing and separate chaining. 5. Open addressing is the process of finding an open location in the hash table in the read more..

  • Page - 1036

    Programming Exercises 1013 **27.8 (Animate quadratic probing) Write a program that animates quadratic probing, as shown in Figure 27.5. Y ou can change the initial size of the hash-table in pro- gram. Assume the load-factor threshold is 0.75. **27.9 (Implement hashCode for string) Write a method that returns a hash code for string using the approach described in Section 27.3.2 with b read more..

  • Page - 1037

    This page intentionally left blank read more..

  • Page - 1038

    GRAPHS AND APPLICATIONS Objectives ■ To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem (§28.1). ■ To describe the graph terminologies: vertices, edges, simple graphs, weighted/unweighted graphs, and directed/undirected graphs (§28.2). ■ To represent vertices and edges using lists, edge arrays, edge objects, adjacency matrices, and adjacency lists read more..

  • Page - 1039

    1016 Chapter 28 Graphs and Applications 28.1 Introduction Many real-world problems can be solved using graph algorithms. Graphs are useful in modeling and solving real-world problems. For example, the problem to find the least number of flights between two cities can be modeled using a graph, where the vertices represent cities and the edges represent the flights between two read more..

  • Page - 1040

    28.2 Basic Graph Terminologies 1017 a dot, called a vertex or a node, and each bridge with a line, called an edge, as shown in Figure 28.2b. This structure with vertices and edges is called a graph. Looking at the graph, we ask whether there is a path starting from any vertex, traversing all edges exactly once, and returning to the starting vertex. Euler proved that for such a read more..

  • Page - 1041

    1018 Chapter 28 Graphs and Applications Edges may be weighted or unweighted. For example, you can assign a weight for each edge in the graph in Figure 28.1 to indicate the flight time between the two cities. Two vertices in a graph are said to be adjacent if they are connected by the same edge. Similarly, two edges are said to be adjacent if they are connected to the same read more..

  • Page - 1042

    28.3 Representing Graphs 1019 28.1 What is the famous Seven Bridges of Königsberg problem? 28.2 What is a graph? Explain the following terms: undirected graph, directed graph, weighted graph, degree of a vertex, parallel edge, simple graph, complete graph, connected graph, cycle, subgraph, tree, and spanning tree. 28.3 How many edges are in a complete graph with 5 vertices? read more..

  • Page - 1043

    1020 Chapter 28 Graphs and Applications public String getMayor() { return mayor; } public void setMayor(String mayor) { this.mayor = mayor; } public void setPopulation(int population) { this.population = population; } } The vertices can be conveniently labeled using natural numbers 0, 1, 2, c, n - 1, for a graph for n vertices. Thus, vertices[0] represents read more..

  • Page - 1044

    28.3 Representing Graphs 1021 {6, 5}, {6, 7}, {7, 4}, {7, 5}, {7, 6}, {7, 8}, {8, 4}, {8, 7}, {8, 9}, {8, 10}, {8, 11}, {9, 8}, {9, 11}, {10, 2}, {10, 4}, {10, 8}, {10, 11}, {11, 8}, {11, 9}, {11, 10} }; This representation is known as the edge array. The vertices and edges in Figure 28.3a can be represented as follows: read more..

  • Page - 1045

    1022 Chapter 28 Graphs and Applications {0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0}, // Los Angeles {1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0}, // Denver {0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0}, // Kansas City {1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0}, // Chicago {0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0}, // Boston {0, 0, 0, 0, read more..

  • Page - 1046

    28.3 Representing Graphs 1023 Note Adjacency vertex list is simpler for representing unweighted graphs. However, adjacency edge lists are more flexible for a wide range of graph applications. It is easy to add addi- tional constraints on edges using adjacency edge lists. For this reason, this book will use adjacency edge lists to represent graphs. You can use arrays, array read more..

  • Page - 1047

    1024 Chapter 28 Graphs and Applications neighbors.get(0).add(new Edge(0, 3)); neighbors.get(0).add(new Edge(0, 5)); neighbors.add(new ArrayList<Edge>()); neighbors.get(1).add(new Edge(1, 0)); neighbors.get(1).add(new Edge(1, 2)); neighbors.get(1).add(new Edge(1, 3)); ... ... neighbors.get(11).add(new Edge(11, 8)); neighbors.get(11).add(new Edge(11, 9)); neighbors.get(11).add(new Edge(11, 10)); 28.5 How do read more..

  • Page - 1048

    28.4 Modeling Graphs 1025 perform a breadth-first search. Depth-first search and breadth-first search will be introduced in the next section. Figure 28.9 illustrates these methods in the UML diagram. AbstractGraph does not introduce any new methods. A list of vertices and an edge adja- cency list are defined in the AbstractGraph class. With these data fields, it is sufficient to FIGURE read more..

  • Page - 1049

    1026 Chapter 28 Graphs and Applications implement all the methods defined in the Graph interface. For convenience, we assume the graph is a simple graph, i.e., a vertex has no edge to itself and there are no parallel edges from vertex u to v. AbstractGraph implements all the methods from Graph, and it does not introduce any new methods except a convenient read more..

  • Page - 1050

    28.4 Modeling Graphs 1027 35 java.util.ArrayList<AbstractGraph.Edge> edgeList 36 = new java.util.ArrayList<>(); 37 edgeList.add(new AbstractGraph.Edge(0, 2)); 38 edgeList.add(new AbstractGraph.Edge(1, 2)); 39 edgeList.add(new AbstractGraph.Edge(2, 4)); 40 edgeList.add(new AbstractGraph.Edge(3, 4)); 41 // Create a graph read more..

  • Page - 1051

    1028 Chapter 28 Graphs and Applications Now we turn our attention to implementing the interface and classes. Listings 28.2, 28.3, and 28.4 give the Graph interface, the AbstractGraph class, and the UnweightedGraph class, respectively. LISTING 28.2 Graph.java 1 public interface Graph<V> { 2 /** Return the number of vertices in the graph */ 3 public int getSize(); 4 read more..

  • Page - 1052

    28.4 Modeling Graphs 1029 14 for (int i = 0; i < vertices.length; i++) 15 addVertex(vertices[i]); 16 17 createAdjacencyLists(edges, vertices.length); 18 } 19 20 /** Construct a graph from vertices and edges stored in List */ 21 protected AbstractGraph(List<V> vertices, List<Edge> edges) { 22 for (int i = 0; i < read more..

  • Page - 1053

    1030 Chapter 28 Graphs and Applications 74 75 @Override /** Return the index for the specified vertex object */ 76 public int getIndex(V v) { 77 return vertices.indexOf(v); 78 } 79 80 @Override /** Return the neighbors of the specified vertex */ 81 public List<Integer> getNeighbors(int index) { 82 List<Integer> result = read more..

  • Page - 1054

    28.4 Modeling Graphs 1031 134 return true; 135 } 136 else { 137 return false; 138 } 139 } 140 141 @Override /** Add an edge to the graph */ 142 public boolean addEdge(int u, int v) { 143 return addEdge(new Edge(u, v)); 144 } 145 146 /** Edge inner class inside the AbstractGraph class */ 147 public static class Edge { 148 read more..

  • Page - 1055

    1032 Chapter 28 Graphs and Applications 194 195 @Override /** Starting bfs search from vertex v */ 196 /** To be discussed in Section 28.9 */ 197 public Tree bfs(int v) { 198 List<Integer> searchOrder = new ArrayList<>(); 199 int[] parent = new int[vertices.size()]; 200 for (int i = 0; i < parent.length; i++) 201 parent[i] = -1; // read more..

  • Page - 1056

    28.4 Modeling Graphs 1033 255 return searchOrder.size(); 256 } 257 258 /** Return the path of vertices from a vertex to the root */ 259 public List<V> getPath(int index) { 260 ArrayList<V> path = new ArrayList<>(); 261 262 do { 263 path.add(vertices.get(index)); 264 index = parent[index]; 265 read more..

  • Page - 1057

    1034 Chapter 28 Graphs and Applications 19 public UnweightedGraph(List<Edge> edges, int numberOfVertices) { 20 super(edges, numberOfVertices); 21 } 22 23 /** Construct a graph from integer vertices 0, 1, and edge array */ 24 public UnweightedGraph(int[][] edges, int numberOfVertices) { 25 super(edges, numberOfVertices); 26 } 27 } The code in the Graph interface in read more..

  • Page - 1058

    28.5 Graph Visualization 1035 LISTING 28.6 GraphView.java 1 import javafx.scene.layout.Pane; 2 import javafx.scene.shape.Circle; 3 import javafx.scene.shape.Line; 4 import javafx.scene.text.Text; 5 6 public class GraphView extends Pane { 7 private Graph<? extends Displayable> graph; 8 9 public GraphView(Graph<? extends Displayable> graph) { 10 this.graph = graph; 11 12 read more..

  • Page - 1059

    1036 Chapter 28 Graphs and Applications 9 new City("San Francisco", 50, 210), 10 new City("Los Angeles", 75, 275), new City("Denver", 275, 175), 11 new City("Kansas City" , 400, 245), 12 new City("Chicago", 450, 100), new City("Boston", 700, 80), 13 new City("New York" , 675, 120), new City("Atlanta", 575, 295), 14 read more..

  • Page - 1060

    28.6 Graph Traversals 1037 28.9 Will Listing 28.7 DisplayUSMap.java work, if the code in lines 30–34 in Listing 28.6 GraphView.java is replaced by the following code? if (i < v) { int x2 = graph.getVertex(v).getX(); int y2 = graph.getVertex(v).getY(); // Draw an edge for (i, v) getChildren().add(new Line(x1, y1, x2, y2)); } 28.10 For the graph1 object created in read more..

  • Page - 1061

    1038 Chapter 28 Graphs and Applications Sections 28.7 and 28.9 will introduce depth-first search and breadth-first search, respec- tively. Both searches will result in an instance of the Tree class. 28.11 Does AbstractGraph<V>.Tree implement the Tree interface defined in Listing 25.3 Tree.java? 28.12 What method do you use to find the parent of a vertex in the tree? 28.7 Depth-First Search read more..

  • Page - 1062

    28.7 Depth-First Search (DFS) 1039 3 for each neighbor w of v 4 if (w has not been visited) { 5 set v as the parent for w in the tree; 6 dfs(w); 7 } 8 } You can use an array named isVisited to denote whether a vertex has been visited. Initially, isVisited[i] is false for each vertex i. Once a read more..

  • Page - 1063

    1040 Chapter 28 Graphs and Applications The dfs(int v) method is implemented in lines 164–193 in Listing 28.3. It returns an instance of the Tree class with vertex v as the root. The method stores the vertices searched in the list searchOrder (line 165), the parent of each vertex in the array parent (line 166), and uses the isVisited array to indicate read more..

  • Page - 1064

    28.7 Depth-First Search (DFS) 1041 12 vertices are searched in this DFS order: Chicago Seattle San Francisco Los Angeles Denver Kansas City New York Boston Atlanta Miami Houston Dallas parent of Seattle is Chicago parent of San Francisco is Seattle parent of Los Angeles is San Francisco parent of Denver is Los Angeles parent of Kansas City is Denver parent of read more..

  • Page - 1065

    1042 Chapter 28 Graphs and Applications the graph is connected. Otherwise, the graph is not connected. (See Programming Exercise 28.1.) ■ Detecting whether there is a path between two vertices (see Programming Exercise 28.5). ■ Finding a path between two vertices (see Programming Exercise 28.5). ■ Finding all connected components. A connected component is a maximal read more..

  • Page - 1066

    28.8 Case Study: The Connected Circles Problem 1043 We will write a program that lets the user create a circle by clicking a mouse in a blank area that is not currently covered by a circle. As the circles are added, the circles are repainted filled if they are connected or unfilled otherwise. We will create a graph to model the problem. Each circle is a vertex read more..

  • Page - 1067

    1044 Chapter 28 Graphs and Applications 31 32 /** Returns true if the point is inside an existing circle */ 33 private boolean isInsideACircle(Point2D p) { 34 for (Node circle: this.getChildren()) 35 if (circle.contains(p)) 36 return true; 37 38 return false; 39 } 40 41 /** Color all circles if they are connected */ 42 private void colorIfConnected() { 43 if read more..

  • Page - 1068

    28.9 Breadth-First Search (BFS) 1045 vertices are connected if they overlap (line 51). The DFS of the graph results in a tree (line 60). The tree’s getNumberOfVerticesFound() returns the number of vertices searched. If it is equal to the number of circles, all circles are connected (lines 61–62). 28.18 How is a graph created for the connected circles problem? 28.19 When read more..

  • Page - 1069

    1046 Chapter 28 Graphs and Applications 28.9.2 Implementation of Breadth-First Search The bfs(int v) method is defined in the Graph interface and implemented in the AbstractGraph class in Listing 28.3 (lines 197–222). It returns an instance of the Tree class with vertex v as the root. The method stores the vertices searched in the list searchOrder (line 198), the read more..

  • Page - 1070

    28.9 Breadth-First Search (BFS) 1047 27 System.out.println(bfs.getNumberOfVerticesFound() + 28 " vertices are searched in this order:"); 29 for (int i = 0; i < searchOrders.size(); i++) 30 System.out.println(graph.getVertex(searchOrders.get(i))); 31 32 for (int i = 0; i < searchOrders.size(); i++) 33 if (bfs.getParent(i) != -1) 34 read more..

  • Page - 1071

    1048 Chapter 28 Graphs and Applications 28.10 Case Study: The Nine Tails Problem The nine tails problem can be reduced to the shortest path problem. The nine tails problem is as follows. Nine coins are placed in a three-by-three matrix with some face up and some face down. A legal move is to take a coin that is face up and reverse it, together with the coins read more..

  • Page - 1072

    28.10 Case Study: The Nine Tails Problem 1049 Each state of the nine coins represents a node in the graph. For example, the three states in Figure 28.17 correspond to three nodes in the graph. For convenience, we use a 3 * 3 matrix to represent all nodes and use 0 for heads and 1 for tails. Since there are nine cells and each cell is either 0 or 1, there are a read more..

  • Page - 1073

    1050 Chapter 28 Graphs and Applications The position is a value from 0 to 8, which points to a coin in the node, as shown in the following figure. FIGURE 28.19 If node u becomes node v after cells are flipped, assign an edge from v to u. 1 011 10 00 408 0 1 101 11 00 488 0 0 110 11 00 240 0 0 011 00 11 30 0 0 101 00 11 47 1 0 111 00 00 56 0 1 111 11 read more..

  • Page - 1074

    28.10 Case Study: The Nine Tails Problem 1051 Listing 28.13 shows the source code for NineTailModel.java. LISTING 28.13 NineTailModel.java 1 import java.util.*; 2 3 public class NineTailModel { 4 public final static int NUMBER_OF_NODES = 512; 5 protected AbstractGraph<Integer>.Tree tree; // Define a tree 6 7 /** Construct a model */ 8 public read more..

  • Page - 1075

    1052 Chapter 28 Graphs and Applications 57 else 58 node[row * 3 + column] = 'H'; // Flip from T to H 59 } 60 } 61 62 public static int getIndex(char[] node) { 63 int result = 0; 64 65 for (int i = 0; i < 9 ; i++) 66 if (node[i] == 'T') 67 result = result * 2 + read more..

  • Page - 1076

    Key Terms 1053 The getShortestpath(nodeIndex) method invokes the getPath(nodeIndex) method to get a vertices in a shortest path from the specified node to the target node (lines 89–91). The printNode(node) method displays a node on the console (lines 93–101). Listing 28.14 gives a program that prompts the user to enter an initial node and displays the steps to reach the read more..

  • Page - 1077

    1054 Chapter 28 Graphs and Applications CHAPTER SUMMARY 1. A graph is a useful mathematical structure that represents relationships among entities in the real world. You learned how to model graphs using classes and interfaces, how to represent vertices and edges using arrays and linked lists, and how to implement opera- tions for graphs. 2. Graph traversal is the process of read more..

  • Page - 1078

    Programming Exercises 1055 (Hint: Use new UnweightedGraph(list, numberOfVertices) to create a graph, where list contains a list of AbstractGraph.Edge objects. Use new AbstractGraph.Edge(u, v) to create an edge. Read the first line to get the number of vertices. Read each subsequent line into a string s and use s.split("[\\s+]") to extract the vertices from read more..

  • Page - 1079

    1056 Chapter 28 Graphs and Applications *28.5 (Find paths) Add a new method in AbstractGraph to find a path between two vertices with the following header: public List<Integer> getPath(int u, int v); The method returns a List<Integer> that contains all the vertices in a path from u to v in this order. Using the BFS approach, you can obtain a read more..

  • Page - 1080

    Programming Exercises 1057 **28.11 (Revise Listing 28.14, NineTail.java) The program in Listing 28.14 lets the user enter an input for the nine tails problem from the console and displays the result on the console. Write a program that lets the user set an initial state of the nine coins (see Figure 28.22a) and click the Solve button to display the solution, as shown in read more..

  • Page - 1081

    1058 Chapter 28 Graphs and Applications **28.16 (Induced subgraph) Given an undirected graph G = (V, E) and an integer k, find an induced subgraph H of G of maximum size such that all vertices of H have a degree 7 = k, or conclude that no such induced subgraph exists. Implement the method with the following header: public static Graph maxInducedSubgraph(Graph g, int read more..

  • Page - 1082

    Programming Exercises 1059 **28.21 (Display sets of connected circles) Modify Listing 28.10, ConnectedCircles.java, to display sets of connected circles in different colors. That is, if two circles are connected, they are displayed using the same color; otherwise, they are not in same color, as shown in Figure  28.25. (Hint: See Programming Exercise 28.4.) *28.22 (Move a circle) read more..

  • Page - 1083

    This page intentionally left blank read more..

  • Page - 1084

    WEIGHTED GRAPHS AND APPLICATIONS Objectives ■ To represent weighted edges using adjacency matrices and adjacency lists (§29.2). ■ To model weighted graphs using the WeightedGraph class that extends the AbstractGraph class (§29.3). ■ To design and implement the algorithm for finding a minimum spanning tree (§29.4). ■ To define the MST class that extends the Tree class read more..

  • Page - 1085

    1062 Chapter 29 Weighted Graphs and Applications 29.1 Introduction A graph is a weighted graph if each edge is assigned a weight. Weighted graphs have many practical applications. Figure  28.1 assumes that the graph represents the number of flights among cities. You can apply the BFS to find the fewest number of flights between two cities. Assume that the edges represent read more..

  • Page - 1086

    29.2 Representing Weighted Graphs 1063 29.2 Representing Weighted Graphs Weighted edges can be stored in adjacency lists. There are two types of weighted graphs: vertex weighted and edge weighted. In a vertex- weighted graph, each vertex is assigned a weight. In an edge-weighted graph, each edge is assigned a weight. Of the two types, edge-weighted graphs have more applications. read more..

  • Page - 1087

    1064 Chapter 29 Weighted Graphs and Applications 29.2.2 Weighted Adjacency Matrices Assume that the graph has n vertices. You can use a two-dimensional n * n matrix, say weights, to represent the weights on edges. weights[i][j] represents the weight on edge (i, j). If vertices i and j are not connected, weights[i][j] is null. For example, the weights in the read more..

  • Page - 1088

    29.3 The WeightedGraph Class 1065 AbstractGraph.Edge is an inner class defined in the AbstractGraph class. It represents an edge from vertex u to v. WeightedEdge extends AbstractGraph.Edge with a new property weight. To create a WeightedEdge object, use new WeightedEdge(i, j, w), where w is the weight on edge (i, j). Often you need to compare the weights of the read more..

  • Page - 1089

    1066 Chapter 29 Weighted Graphs and Applications adjacency lists are created (lines 47 and 57). The methods getMinimumSpanningTree() (lines 99–138) and getShortestPath() (lines 156–197) will be introduced in upcoming sections. LISTING 29.2 WeightedGraph.java 1 import java.util.*; 2 3 public class WeightedGraph<V> extends AbstractGraph<V> { 4 /** Construct an read more..

  • Page - 1090

    29.3 The WeightedGraph Class 1067 22 /** Construct a WeightedGraph for vertices 0, 1, 2 and edge list */ 23 public WeightedGraph(List<V> vertices, List<WeightedEdge> edges) { 24 createWeightedGraph(vertices, edges); 25 } 26 27 /** Construct a WeightedGraph from vertices 0, 1, and edge array */ 28 public WeightedGraph(List<WeightedEdge> edges, 29 read more..

  • Page - 1091

    1068 Chapter 29 Weighted Graphs and Applications 82 ", " + edge.v + ", " + ((WeightedEdge)edge).weight + ") "); 83 } 84 System.out.println(); 85 } 86 } 87 88 /** Add edges to the weighted graph */ 89 public boolean addEdge(int u, int v, double weight) { 90 return addEdge(new read more..

  • Page - 1092

    29.3 The WeightedGraph Class 1069 142 private double totalWeight; // Total weight of all edges in the tree 143 144 public MST(int root, int[] parent, List<Integer> searchOrder, 145 double totalWeight) { 146 super(root, parent, searchOrder); 147 this.totalWeight = totalWeight; 148 } 149 150 public double getTotalWeight() { 151 return totalWeight; 152 } 153 read more..

  • Page - 1093

    1070 Chapter 29 Weighted Graphs and Applications 202 203 /** Construct a path */ 204 public ShortestPathTree(int source, int[] parent, 205 List<Integer> searchOrder, double [] cost) { 206 super(source, parent, searchOrder); 207 this.cost = cost; 208 } 209 210 /** Return the cost for a path from the root to vertex v */ 211 public double getCost(int read more..

  • Page - 1094

    29.3 The WeightedGraph Class 1071 24 }; 25 26 WeightedGraph<String> graph1 = 27 new WeightedGraph<>(vertices, edges); 28 System.out.println("The number of vertices in graph1: " 29 + graph1.getSize()); 30 System.out.println("The vertex with index 1 is " 31 + graph1.getVertex(1)); 32 read more..

  • Page - 1095

    1072 Chapter 29 Weighted Graphs and Applications edges[i][1] and the weight for the edge is edges[i][2]. For example, {0, 1, 807} (line 8) represents the edge from vertex 0 (edges[0][0]) to vertex 1 (edges[0][1]) with weight 807 (edges[0][2]). {0, 5, 2097} (line 8) represents the edge from ver- tex 0 (edges[2][0]) to vertex 5 (edges[2][1]) with weight 2097 read more..

  • Page - 1096

    29.4 Minimum Spanning Trees 1073 LISTING 29.4 Prim’s Minimum Spanning Tree Algorithm Input: A connected undirected weighted G = (V, E) with non-negative weights Output: MST (a minimum spanning tree) 1 MST minimumSpanningTree() { 2 Let T be a set for the vertices in the spanning tree; 3 Initially, add the starting vertex to T; 4 5 while read more..

  • Page - 1097

    1074 Chapter 29 Weighted Graphs and Applications shown in Figure 29.6, and ( u, v) is the one with the smallest weight. Consider the graph in Figure 29.7. The algorithm adds the vertices to T in this order: 1. Add vertex 0 to T. 2. Add vertex 5 to T, since Edge(5, 0, 5) has the smallest weight among all edges inci- dent to a vertex in T, as shown in Figure 29.7a. The read more..

  • Page - 1098

    29.4 Minimum Spanning Trees 1075 5. Add vertex 2 to T, since Edge(2, 6, 5) has the smallest weight among all edges incident to a vertex in T, as shown in Figure 29.7d. 6. Add vertex 4 to T, since Edge(4, 6, 7) has the smallest weight among all edges incident to a vertex in T, as shown in Figure 29.7e. 7. Add vertex 3 to T, since Edge(3, 2, 8) has read more..

  • Page - 1099

    1076 Chapter 29 Weighted Graphs and Applications The refined version of the Prim’s algoruthm greatly simplifies the implementation. The getMinimumSpanningTree method was implemented using the refined version of the Prim’s algorithm in lines 99–138 in Listing 29.2. The getMinimumSpanningTree(int startingVertex) method sets cost[startingVertex] to 0 (line 105) and cost[v] to read more..

  • Page - 1100

    29.4 Minimum Spanning Trees 1077 12 {3, 5, 1003}, 13 {4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260}, 14 {4, 8, 864}, {4, 10, 496}, 15 {5, 0, 2097}, {5, 3, 1003}, {5, 4, 533}, 16 {5, 6, 983}, {5, 7, 787}, 17 {6, 5, 983}, {6, 7, 214}, 18 read more..

  • Page - 1101

    1078 Chapter 29 Weighted Graphs and Applications 29.5 Find a minimum spanning tree for the following graph. ✓ Point ✓Check FIGURE 29.9 The edges in a minimum spanning tree for the cities are highlighted. Seattle Los Angeles Denver Chicago Houston Boston New York Atlanta Miami 661 888 1187 810 Dallas 1331 2097 1003 807 381 1015 1267 1663 1435 239 496 781 864 1260 983 787 214 533 599 San read more..

  • Page - 1102

    29.5 Finding Shortest Paths 1079 shortest path from s to all vertices. So Dijkstra’s algorithm is known as a single-source shortest path algorithm. The algorithm uses cost[v] to store the cost of a shortest path from vertex v to the source vertex s. cost[s] is 0. Initially assign infinity to cost[v] for all other vertices. The algorithm repeatedly finds a read more..

  • Page - 1103

    1080 Chapter 29 Weighted Graphs and Applications Let us illustrate Dijkstra’s algorithm using the graph in Figure 29.11a. Suppose the source vertex is 1. Therefore, cost[1] = 0 and the costs for all other vertices are initially ∞, as shown in Figure 29.11b. We use the parent[i] to denote the parent of i in the path. For convenience, set the parent of the source node to read more..

  • Page - 1104

    29.5 Finding Shortest Paths 1081 Now T contains {1, 2}. Vertex 0 is the one in V-T with the smallest cost, so add 0 to T, as shown in Figure 29.14 and update the cost and parent for vertices in V-T and adjacent to 0 if applicable. cost[5] is now updated to 10 and its parent is set to 0 and cost[6] is now updated to 8 and its parent is set to 0. read more..

  • Page - 1105

    1082 Chapter 29 Weighted Graphs and Applications Now T contains {1, 2, 0, 6}. Vertex 3 or 5 is is the one in V-T with the smallest cost. You may add either 3 or 5 into T. Let us add 3 to T, as shown in Figure 29.16 and update the cost and parent for vertices in V-T and adjacent to 3 if applicable. cost[4] is now updated to 18 and its parent read more..

  • Page - 1106

    29.5 Finding Shortest Paths 1083 infinity for all other vertices (lines 159–161). The parent of sourceVertex is set to -1 (line 166). T is a list that stores the vertices added into the shortest path tree (line 169). We use a list for T rather than a set in order to record the order of the vertices added to T. Initially, T is empty. To expand T, the read more..

  • Page - 1107

    1084 Chapter 29 Weighted Graphs and Applications Pedagogical Note Go to www.cs.armstrong.edu/liang/animation/ShortestPathAnimation.html to use a GUI inter- active program to find a shortest path between any two cities, as shown in Figure 29.20. shortest path animation on Companion Website FIGURE 29.20 The animation tool displays a shortest path between two cities. Listing 29.8 gives a read more..

  • Page - 1108

    29.5 Finding Shortest Paths 1085 22 {10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239}, 23 {11, 8, 810}, {11, 9, 1187}, {11, 10, 239} 24 }; 25 26 WeightedGraph<String> graph1 = 27 new WeightedGraph<>(vertices, edges); 28 WeightedGraph<String>.ShortestPathTree tree1 = 29 read more..

  • Page - 1109

    1086 Chapter 29 Weighted Graphs and Applications The program creates a weighted graph for Figure  29.1 in line 27. It then invokes the getShortestPath(graph1.getIndex("Chicago")) method to return a Path object that contains all shortest paths from Chicago. Invoking printAllPaths() on the ShortestPathTree object displays all the paths (line 30). The graphical illustration of read more..

  • Page - 1110

    29.6 Case Study: The Weighted Nine Tails Problem 1087 The nine tails problem is to find the minimum number of the moves that lead to all coins facing down. Each move flips a head coin and its neighbors. The weighted nine tails problem assigns the number of flips as a weight on each move. For example, you can change the coins in Figure 29.22a to those in read more..

  • Page - 1111

    1088 Chapter 29 Weighted Graphs and Applications The NineTailModel class creates a Graph and obtains a Tree rooted at the target node 511. WeightedNineTailModel is the same as NineTailModel except that it creates a WeightedGraph and obtains a ShortestPathTree rooted at the target node 511. Weight- edNineTailModel extends NineTailModel. The method getEdges() finds all read more..

  • Page - 1112

    29.6 Case Study: The Weighted Nine Tails Problem 1089 49 public int getNumberOfFlips(int u) { 50 return (int)((WeightedGraph<Integer>.ShortestPathTree)tree) 51 .getCost(u); 52 } 53 } WeightedNineTailModel extends NineTailModel to build a WeightedGraph to model the weighted nine tails problem (lines 10–11). For each node u, the getEdges() method finds read more..

  • Page - 1113

    1090 Chapter 29 Weighted Graphs and Applications The program prompts the user to enter an initial node with nine letters with a combination of Hs and Ts as a string in line 8, obtains an array of characters from the string (line 9), creates a model (line 11), obtains the shortest path from the initial node to the target node (lines 12–13), displays the nodes in read more..

  • Page - 1114

    Programming Exercises 1091 when all vertices are in the tree. Design and implement an algorithm for finding an MST using Kruskal’s algorithm. *29.2 (Implement Prim’s algorithm using an adjacency matrix) The text implements Prim’s algorithm using lists for adjacent edges. Implement the algorithm using an adjacency matrix for weighted graphs. *29.3 (Implement Dijkstra’s algorithm read more..

  • Page - 1115

    1092 Chapter 29 Weighted Graphs and Applications an edge (u, v), it also has an edge (v, u). Only one edge is represented in the file. When you construct a graph, both edges need to be added. Your program should prompt the user to enter the name of the file, read data from the file, create an instance g of WeightedGraph, invoke g.printWeightedEdges() to read more..

  • Page - 1116

    Programming Exercises 1093 vertices. For example, for the graph in Figure 29.23, a shortest path between 0 and 1 can be displayed as 0 2 4 3 1. Here is a sample run of the program: Enter a file name: WeightedGraphSample2.txt Enter two vertices (integer indexes): 0 1 The number of vertices is 6 Vertex 0: (0, 2, 3) (0, 1, 100) Vertex 1: (1, 3, 20) (1, 0, 100) Vertex read more..

  • Page - 1117

    1094 Chapter 29 Weighted Graphs and Applications indices. You have to add the vertex indices 0, 1, . . ., and n, in this order. The user can specify two vertices and let the program display their shortest path in red. ***29.16 (Display a dynamic MST) Write a program that lets the user create a weighted graph dynamically. The user can create a vertex by entering read more..

  • Page - 1118

    Programming Exercises 1095 edge, and the distance between the two vertices is also displayed. (5) The user drags a vertex while pressing the CTRL key to move a vertex. (6) The verti- ces are numbers starting from 0. When a vertex is removed, the vertices are renumbered. (7) You can click the Show MST or Show All SP From the Source button to display an MST or SP tree read more..

  • Page - 1119

    1096 Chapter 29 Weighted Graphs and Applications ***29.19 (Find u with smallest cost[u] efficiently) The getShortestPath method finds a u with the smallest cost[u] using a linear search, which takes O( V ). The search time can be reduced to O(log V ) using an AVL tree. Modify the method using an AVL tree to store the vertices in V – T. Use Listing 29.7, read more..

  • Page - 1120

    MULTITHREADING AND PARALLEL PROGRAMMING Objectives ■ To get an overview of multithreading (§30.2). ■ To develop task classes by implementing the Runnable interface (§30.3). ■ To create threads to run tasks using the Thread class (§30.3). ■ To control threads using the methods in the Thread class (§30.4). ■ To control animations using threads and use Platform.runLater read more..

  • Page - 1121

    1098 Chapter 30 Multithreading and Parallel Programming 30.1 Introduction Multithreading enables multiple tasks in a program to be executed concurrently. One of the powerful features of Java is its built-in support for multithreading—the concurrent running of multiple tasks within a program. In many programming languages, you have to invoke system-dependent procedures and functions to read more..

  • Page - 1122

    30.3 Creating Tasks and Threads 1099 FIGURE 30.2 Define a task class by implementing the Runnable interface. // Client class public class Client { ... public void someMethod() { ... // Create an instance of TaskClass TaskClass task = new TaskClass(...); // Create a thread Thread thread = new Thread(task); // Start a thread read more..

  • Page - 1123

    1100 Chapter 30 Multithreading and Parallel Programming LISTING 30.1 TaskThreadDemo.java 1 public class TaskThreadDemo { 2 public static void main(String[] args) { 3 // Create tasks 4 Runnable printA = new PrintChar('a', 100); 5 Runnable printB = new PrintChar('b', 100); 6 Runnable print100 = new PrintNum(100); 7 8 // Create threads 9 read more..

  • Page - 1124

    30.3 Creating Tasks and Threads 1101 The program creates three tasks (lines 4–6). To run them concurrently, three threads are created (lines 9–11). The start() method (lines 14–16) is invoked to start a thread that causes the run() method in the task to be executed. When the run() method completes, the thread terminates. Because the first two tasks, printA read more..

  • Page - 1125

    1102 Chapter 30 Multithreading and Parallel Programming 30.4 The Thread Class The Thread class contains the constructors for creating threads for tasks and the methods for controlling threads. Figure 30.4 shows the class diagram for the Thread class. Key Point FIGURE 30.4 The Thread class contains the methods for controlling threads. java.lang.Thread «interface» java.lang.Runnable +Thread(task: read more..

  • Page - 1126

    30.4 The Thread Class 1103 This approach is, however, not recommended because it mixes the task and the mecha- nism of running the task. Separating the task from the thread is a preferred design. Note The Thread class also contains the stop(), suspend(), and resume() methods. As of Java 2, these methods were deprecated (or outdated) because they are known to be read more..

  • Page - 1127

    1104 Chapter 30 Multithreading and Parallel Programming You can use the join() method to force one thread to wait for another thread to finish. For example, suppose you modify the code in lines 53–57 in Listing 30.1 as follows: join() Thread print100 Wait for thread4 to finish Thread thread4 thread4 finished public void run() { Thread thread4 = new Thread( new read more..

  • Page - 1128

    30.5 Case Study: Flashing Text 1105 30.5 Case Study: Flashing Text You can use a thread to control an animation. The use of a Timeline object to control animations was introduced in Section 15.11, Ani- mation. Alternatively, you can also use a thread to control animation. Listing 30.2 gives an example that displays flashing text on a label, as shown in Figure 30.6. Key read more..

  • Page - 1129

    1106 Chapter 30 Multithreading and Parallel Programming 42 // Create a scene and place it in the stage 43 Scene scene = new Scene(pane, 200, 50); 44 primaryStage.setTitle("FlashText"); // Set the stage title 45 primaryStage.setScene(scene); // Place the scene in the stage 46 primaryStage.show(); // Display the stage 47 } read more..

  • Page - 1130

    30.6 Thread Pools 1107 This approach is convenient for a single task execution, but it is not efficient for a large number of tasks because you have to create a thread for each task. Starting a new thread for each task could limit throughput and cause poor performance. Using a thread pool is an ideal way to manage the number of tasks executing concurrently. Java read more..

  • Page - 1131

    1108 Chapter 30 Multithreading and Parallel Programming 4 public static void main(String[] args) { 5 // Create a fixed thread pool with maximum three threads 6 ExecutorService executor = Executors.newFixedThreadPool(3); 7 8 // Submit runnable tasks to the executor 9 executor.execute(new PrintChar('a', 100)); 10 executor.execute(new PrintChar('b', 100)); 11 read more..

  • Page - 1132

    30.7 Thread Synchronization 1109 LISTING 30.4 AccountWithoutSync.java 1 import java.util.concurrent.*; 2 3 public class AccountWithoutSync { 4 private static Account account = new Account(); 5 6 public static void main(String[] args) { 7 ExecutorService executor = Executors.newCachedThreadPool(); 8 9 // Create and launch 100 threads 10 for (int i = 0; i < 100 ; read more..

  • Page - 1133

    1110 Chapter 30 Multithreading and Parallel Programming 42 // data-corruption problem and make it easy to see. 43 try { 44 Thread.sleep(5); 45 } 46 catch (InterruptedException ex) { 47 } 48 49 balance = newBalance; 50 } 51 } 52 } The classes AddAPennyTask and Account in lines 24–51 are inner classes. Line read more..

  • Page - 1134

    30.7 Thread Synchronization 1111 In Step 1, Task 1 gets the balance from the account. In Step 2, Task 2 gets the same bal- ance from the account. In Step 3, Task 1 writes a new balance to the account. In Step 4, Task 2 writes a new balance to the account. The effect of this scenario is that Task 1 does nothing because in Step 4 Task 2 overrides Task 1’s read more..

  • Page - 1135

    1112 Chapter 30 Multithreading and Parallel Programming block of the code in a method. This block is referred to as a synchronized block. The general form of a synchronized statement is as follows: synchronized (expr) { statements; } The expression expr must evaluate to an object reference. If the object is already locked by another thread, the thread is blocked until read more..

  • Page - 1136

    30.8 Synchronization Using Locks 1113 ReentrantLock is a concrete implementation of Lock for creating mutually exclusive locks. You can create a lock with the specified fairness policy. True fairness policies guar- antee that the longest-waiting thread will obtain the lock first. False fairness policies grant a lock to a waiting thread arbitrarily. Programs using fair locks read more..

  • Page - 1137

    1114 Chapter 30 Multithreading and Parallel Programming 31 // An inner class for Account 32 public static class Account { 33 private static Lock lock = new ReentrantLock(); // Create a lock 34 private int balance = 0; 35 36 public int getBalance() { 37 return balance; 38 } 39 40 public void deposit(int amount) { 41 lock.lock(); // Acquire the lock 42 43 try read more..

  • Page - 1138

    30.9 Cooperation among Threads 1115 Let us use an example to demonstrate thread communications. Suppose that you create and launch two tasks: one that deposits into an account and one that withdraws from the same account. The withdraw task has to wait if the amount to be withdrawn is more than the cur- rent balance. Whenever new funds are deposited into the account, the read more..

  • Page - 1139

    1116 Chapter 30 Multithreading and Parallel Programming LISTING 30.6 ThreadCooperation.java 1 import java.util.concurrent.*; 2 import java.util.concurrent.locks.*; 3 4 public class ThreadCooperation { 5 private static Account account = new Account(); 6 7 public static void main(String[] args) { 8 // Create a thread pool with two threads 9 ExecutorService executor = read more..

  • Page - 1140

    30.9 Cooperation among Threads 1117 59 System.out.println("\t\t\tWait for a deposit"); 60 newDeposit.await(); 61 } 62 63 balance -= amount; 64 System.out.println("\t\t\tWithdraw " + amount + 65 "\t\t" + getBalance()); 66 } 67 catch (InterruptedException ex) { 68 read more..

  • Page - 1141

    1118 Chapter 30 Multithreading and Parallel Programming statement may lead to an incorrect withdraw. Using the loop statement, the withdraw task will have a chance to recheck the condition before performing a withdraw. Caution Once a thread invokes await() on a condition, the thread waits for a signal to resume. If you forget to call signal() or signalAll() on the read more..

  • Page - 1142

    30.10 Case Study: Producer/Consumer 1119 30.19 How do you create a condition on a lock? What are the await(), signal(), and signalAll() methods for? 30.20 What would happen if the while loop in line 58 of Listing 30.6 was changed to an if statement? ✓ Point ✓Check while (balance < amount) Replaced by if (balance < amount) 30.21 Why does the following class have read more..

  • Page - 1143

    1120 Chapter 30 Multithreading and Parallel Programming The buffer is actually a first-in, first-out queue (lines 52–53). The conditions notEmpty and notFull on the lock are created in lines 59–60. The conditions are bound to a lock. A lock must be acquired before a condition can be applied. If you use the wait() and notify() methods to rewrite this example, you have read more..

  • Page - 1144

    30.10 Case Study: Producer/Consumer 1121 36 try { 37 while (true) { 38 System.out.println("\t\t\tConsumer reads " + buffer.read()); 39 // Put the thread into sleep 40 Thread.sleep((int)(Math.random() * 10000)); 41 } 42 } 43 catch (InterruptedException ex) { 44 read more..

  • Page - 1145

    1122 Chapter 30 Multithreading and Parallel Programming 96 finally { 97 lock.unlock(); // Release the lock 98 return value; 99 } 100 } 101 } 102 } A sample run of the program is shown in Figure 30.19. release the lock FIGURE 30.20 BlockingQueue is a subinterface of Queue. +put(element: E): void +take(): E «interface» read more..

  • Page - 1146

    30.11 Blocking Queues 1123 Three concrete blocking queues—ArrayBlockingQueue, LinkedBlockingQueue, and PriorityBlockingQueue—are provided in Java, as shown in Figure  30.21. All are in the java.util.concurrent package. ArrayBlockingQueue implements a block- ing queue using an array. You have to specify a capacity or an optional fairness to con- struct an ArrayBlockingQueue. read more..

  • Page - 1147

    1124 Chapter 30 Multithreading and Parallel Programming 24 Thread.sleep((int)(Math.random() * 10000)); 25 } 26 } 27 catch (InterruptedException ex) { 28 ex.printStackTrace(); 29 } 30 } 31 } 32 33 // A task for reading and deleting an int from the buffer 34 private read more..

  • Page - 1148

    30.12 Semaphores 1125 To create a semaphore, you have to specify the number of permits with an optional fair- ness policy, as shown in Figure 30.23. A task acquires a permit by invoking the semaphore’s acquire() method and releases the permit by invoking the semaphore’s release() method. Once a permit is acquired, the total number of available permits in a semaphore is reduced by read more..

  • Page - 1149

    1126 Chapter 30 Multithreading and Parallel Programming 30.31 What are the similarities and differences between a lock and a semaphore? 30.32 How do you create a semaphore that allows three concurrent threads? How do you acquire a semaphore? How do you release a semaphore? 30.13 Avoiding Deadlocks Deadlocks can be avoided by using a proper resource ordering. Sometimes two or read more..

  • Page - 1150

    30.15 Synchronized Collections 1127 A thread can enter the Blocked state (i.e., become inactive) for several reasons. It may have invoked the join(), sleep(), or wait() method. It may be waiting for an I/O operation to finish. A blocked thread may be reactivated when the action inactivating it is reversed. For example, if a thread has been put to sleep and the sleep read more..

  • Page - 1151

    1128 Chapter 30 Multithreading and Parallel Programming Invoking synchronizedCollection(Collection c) returns a new Collection object, in which all the methods that access and update the original collection c are synchro- nized. These methods are implemented using the synchronized keyword. For example, the add method is implemented like this: public boolean add(E o) { synchronized read more..

  • Page - 1152

    30.16 Parallel Programming 1129 The framework defines a task using the ForkJoinTask class, as shown in Figure 30.28 and executes a task in an instance of ForkJoinPool, as shown in Figure 30.29. ForkJoinTask ForkJoinPool FIGURE 30.27 The nonoverlapping subproblems are solved in parallel. Subproblem Subproblem Subproblem Subproblem Problem Fork Solution Join FIGURE 30.28 The ForkJoinTask read more..

  • Page - 1153

    1130 Chapter 30 Multithreading and Parallel Programming ForkJoinTask is the abstract base class for tasks. A ForkJoinTask is a thread-like entity, but it is much lighter than a normal thread because huge numbers of tasks and sub- tasks can be executed by a small number of actual threads in a ForkJoinPool. The tasks are primarily coordinated using fork() and join(). read more..

  • Page - 1154

    30.16 Parallel Programming 1131 35 private int[] list; 36 37 SortTask(int[] list) { 38 this.list = list; 39 } 40 41 @Override 42 protected void compute() { 43 if (list.length < THRESHOLD) 44 java.util.Arrays.sort(list); 45 else { 46 // Obtain the first half 47 int[] firstHalf = new int[list.length / 2]; 48 System.arraycopy(list, 0, firstHalf, read more..

  • Page - 1155

    1132 Chapter 30 Multithreading and Parallel Programming an array of int values, but you can modify it to become a generic method (see Programming Exercise 30.13). In general, a problem can be solved in parallel using the following pattern: if (the program is small) solve it sequentially; else { divide the problem into nonoverlapping subproblems; solve the subproblems read more..

  • Page - 1156

    Chapter Summary 1133 46 } 47 else { 48 int mid = (low + high) / 2; 49 RecursiveTask<Integer> left = new MaxTask(list, low, mid); 50 RecursiveTask<Integer> right = new MaxTask(list, mid, high); 51 52 right.fork(); 53 left.fork(); 54 return new Integer(Math.max(left.join().intValue(), 55 right.join().intValue())); 56 read more..

  • Page - 1157

    1134 Chapter 30 Multithreading and Parallel Programming 3. A thread object never directly invokes the run method. The JVM invokes the run method when it is time to execute the thread. Your class must override the run method to tell the system what the thread will do when it runs. 4. To prevent threads from corrupting a shared resource, use synchronized methods or read more..

  • Page - 1158

    Programming Exercises 1135 30.2 (Racing cars) Rewrite Programming Exercise 15.29 using a thread to control car racing. Compare the program with Programming Exercise 15.29 by setting the delay time to 10 in both programs. Which one runs the animation faster? 30.3 (Raise flags) Rewrite Listing 15.13 using a thread to animate a flag being raised. Compare the program with Listing read more..

  • Page - 1159

    1136 Chapter 30 Multithreading and Parallel Programming 30.13 (Generic parallel merge sort) Revise Listing 30.10, ParallelMergeSort.java, to define a generic parallelMergeSort method as follows: public static <E extends Comparable<E>> void parallelMergeSort(E[] list) *30.14 (Parallel quick sort) Implement the following method in parallel to sort a list using quick sort (see read more..

  • Page - 1160

    Programming Exercises 1137 ***30.20 (Sudoku search animation) Modify Programming Exercise 22.21 to display the intermediate results of the search. Figure 30.32 gives a snapshot of an animation in progress with number 2 placed in the cell in Figure 30.32a, number 3 placed in the cell in Figure 30.32b, and number 3 placed in the cell in Figure 30.32c. The animation read more..

  • Page - 1161

    1138 Chapter 30 Multithreading and Parallel Programming 30.21 (Combine colliding bouncing balls) Rewrite Programming Exercise 20.5 using a thread to animate bouncing ball movements. ***30.22 (Eight Queens animation) Modify Listing 22.11, EightQueens.java, to display the intermediate results of the search. As shown in Figure 30.33, the current row being searched is highlighted. Every one read more..

  • Page - 1162

    NETWORKING Objectives ■ To explain terms: TCP, IP, domain name, domain name server, stream- based communications, and packet-based communications (§31.2). ■ To create servers using server sockets (§31.2.1) and clients using client sockets (§31.2.2). ■ To implement Java networking programs using stream sockets (§31.2.3). ■ To develop an example of a client/server application (§31.2.4). read more..

  • Page - 1163

    1140 Chapter 31 Networking 31.1 Introduction Computer networking is used to send and receive messages among computers on the Internet. To browse the Web or send an email, your computer must be connected to the Internet. The Internet is the global network of millions of computers. Your computer can connect to the Internet through an Internet Service Provider (ISP) using a read more..

  • Page - 1164

    31.2 Client/Server Computing 1141 For instance, the email server runs on port 25, and the Web server usually runs on port 80. You can choose any port number that is not currently used by other programs. The following statement creates a server socket serverSocket: ServerSocket serverSocket = new ServerSocket(port); Note Attempting to create a server socket on a port already read more..

  • Page - 1165

    1142 Chapter 31 Networking Note The Socket constructor throws a java.net.UnknownHostException if the host cannot be found. 31.2.3 Data Transmission through Sockets After the server accepts the connection, communication between the server and the client is conducted in the same way as for I/O streams. The statements needed to create the streams and to exchange data between them are read more..

  • Page - 1166

    31.2 Client/Server Computing 1143 31.2.4 A Client/Server Example This example presents a client program and a server program. The client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console. In this example, the data sent from the client comprise the read more..

  • Page - 1167

    1144 Chapter 31 Networking 4 import javafx.application.Application; 5 import javafx.application.Platform; 6 import javafx.scene.Scene; 7 import javafx.scene.control.ScrollPane; 8 import javafx.scene.control.TextArea; 9 import javafx.stage.Stage; 10 11 public class Server extends Application { 12 @Override // Override the start method in the Application class 13 public void read more..

  • Page - 1168

    31.2 Client/Server Computing 1145 LISTING 31.2 Client.java 1 import java.io.*; 2 import java.net.*; 3 import javafx.application.Application; 4 import javafx.geometry.Insets; 5 import javafx.geometry.Pos; 6 import javafx.scene.Scene; 7 import javafx.scene.control.Label; 8 import javafx.scene.control.ScrollPane; 9 import javafx.scene.control.TextArea; 10 import javafx.scene.control.TextField; read more..

  • Page - 1169

    1146 Chapter 31 Networking 59 } 60 catch (IOException ex) { 61 System.err.println(ex); 62 } 63 }); 64 65 try { 66 // Create a socket to connect to the server 67 Socket socket = new Socket("localhost", 8000); 68 // Socket socket = new Socket("130.254.204.36", 8000); 69 // Socket socket = new read more..

  • Page - 1170

    If you receive a java.net.BindException when you start the server, the server port is currently in use. You need to terminate the process that is using the server port and then restart the server. Note When you create a server socket, you have to specify a port (e.g., 8000) for the socket. When a client connects to the server (line 67 in Client.java), a socket is read more..

  • Page - 1171

    1148 Chapter 31 Networking System.out.println("Client's IP Address is " + inetAddress.getHostAddress()); You can also create an instance of InetAddress from a host name or IP address using the static getByName method. For example, the following statement creates an InetAddress for the host liang.armstrong.edu. InetAddress address = InetAddress.getByName("liang.armstrong.edu"); read more..

  • Page - 1172

    31.4 Serving Multiple Clients 1149 create a thread for each connection. Here is how the server handles the establishment of a connection: while (true) { Socket socket = serverSocket.accept(); // Connect to a client Thread thread = new ThreadClass(socket); thread.start(); } The server socket can have many connections. Each iteration of the while loop creates a new read more..

  • Page - 1173

    1150 Chapter 31 Networking 11 public class MultiThreadServer extends Application { 12 // Text area for displaying contents 13 private TextArea ta = new TextArea(); 14 15 // Number a client 16 private int clientNo = 0; 17 18 @Override // Override the start method in the Application class 19 public void start(Stage primaryStage) { 20 // Create a read more..

  • Page - 1174

    31.5 Sending and Receiving Objects 1151 72 /** Run a thread */ 73 public void run() { 74 try { 75 // Create data input and output streams 76 DataInputStream inputFromClient = new DataInputStream( 77 socket.getInputStream()); 78 DataOutputStream outputToClient = new DataOutputStream( 79 socket.getOutputStream()); 80 81 // Continuously serve the read more..

  • Page - 1175

    1152 Chapter 31 Networking LISTING 31.5 StudentAddress.java 1 public class StudentAddress implements java.io.Serializable { 2 private String name; 3 private String street; 4 private String city; 5 private String state; 6 private String zip; 7 8 public StudentAddress(String name, String street, String city, 9 String state, String zip) { 10 this.name = read more..

  • Page - 1176

    31.5 Sending and Receiving Objects 1153 LISTING 31.6 StudentClient.java 1 import java.io.*; 2 import java.net.*; 3 import javafx.application.Application; 4 import javafx.event.ActionEvent; 5 import javafx.event.EventHandler; 6 import javafx.geometry.HPos; 7 import javafx.geometry.Pos; 8 import javafx.scene.Scene; 9 import javafx.scene.control.Button; 10 import javafx.scene.control.Label; read more..

  • Page - 1177

    1154 Chapter 31 Networking 38 HBox hBox = new HBox(2); 39 pane.add(hBox, 1, 2); 40 hBox.getChildren().addAll(tfCity, new Label("State"), tfState, 41 new Label("Zip"), tfZip); 42 pane.add(btRegister, 1, 3); 43 GridPane.setHalignment(btRegister, HPos.RIGHT); 44 45 pane.setAlignment(Pos.CENTER); 46 read more..

  • Page - 1178

    31.5 Sending and Receiving Objects 1155 5 private ObjectOutputStream outputToFile; 6 private ObjectInputStream inputFromClient; 7 8 public static void main(String[] args) { 9 new StudentServer(); 10 } 11 12 public StudentServer() { 13 try { 14 // Create a server socket 15 ServerSocket serverSocket = new ServerSocket(8000); 16 System.out.println("Server read more..

  • Page - 1179

    1156 Chapter 31 Networking 31.9 How does a server receive connection from a client? How does a client connect to a server? 31.10 How do you find the host name of a client program from the server? 31.11 How do you send and receive an object? 31.6 Case Study: Distributed Tic-Tac-Toe Games This section develops a program that enables two players to play the tic-tac-toe game read more..

  • Page - 1180

    31.6 Case Study: Distributed Tic-Tac-Toe Games 1157 ■ TicTacToeClient models a player in Listing 31.10. ■ Cell models a cell in the game. It is an inner class in TicTacToeClient. ■ TicTacToeConstants is an interface that defines the constants shared by all the classes in the example in Listing 31.8. The relationships of these classes are shown in Figure 31.14. read more..

  • Page - 1181

    1158 Chapter 31 Networking 5 import javafx.application.Platform; 6 import javafx.scene.Scene; 7 import javafx.scene.control.ScrollPane; 8 import javafx.scene.control.TextArea; 9 import javafx.stage.Stage; 10 11 public class TicTacToeServer extends Application 12 implements TicTacToeConstants { 13 private int sessionNo = 1; // Number a session 14 15 read more..

  • Page - 1182

    31.6 Case Study: Distributed Tic-Tac-Toe Games 1159 29 Platform.runLater(() -> taLog.appendText(new Date() + 30 ": Server started at socket 8000\n")); 31 32 // Ready to create a session for every two players 33 while (true) { 34 Platform.runLater(() -> taLog.appendText(new Date() + 35 ": Wait for players to join read more..

  • Page - 1183

    1160 Chapter 31 Networking 89 private DataOutputStream toPlayer1; 90 private DataInputStream fromPlayer2; 91 private DataOutputStream toPlayer2; 92 93 // Continue to play 94 private boolean continueToPlay = true; 95 96 /** Construct a thread */ 97 public HandleASession(Socket player1, Socket player2) { 98 this.player1 = player1; 99 this.player2 = player2; 100 101 // read more..

  • Page - 1184

    31.6 Case Study: Distributed Tic-Tac-Toe Games 1161 149 // Send player 1's selected row and column to player 2 150 sendMove(toPlayer2, row, column); 151 } 152 153 // Receive a move from Player 2 154 row = fromPlayer2.readInt(); 155 column = fromPlayer2.readInt(); 156 cell[row][column] = read more..

  • Page - 1185

    1162 Chapter 31 Networking 209 if ((cell[0][j] == token) 210 && (cell[ 1][j] == token) 211 && (cell[ 2][j] == token)) { 212 return true; 213 } 214 215 /** Check major diagonal */ 216 if ((cell[0][0] == token) 217 && (cell[ 1][1] == token) 218 read more..

  • Page - 1186

    31.6 Case Study: Distributed Tic-Tac-Toe Games 1163 32 // Create and initialize a title label 33 private Label lblTitle = new Label(); 34 35 // Create and initialize a status label 36 private Label lblStatus = new Label(); 37 38 // Indicate selected row and column by the current move 39 private int rowSelected; 40 private int columnSelected; 41 42 read more..

  • Page - 1187

    1164 Chapter 31 Networking 92 93 // Control the game on a separate thread 94 new Thread(() -> { 95 try { 96 // Get notification from the server 97 int player = fromServer.readInt(); 98 99 // Am I player 1 or 2? 100 if (player == PLAYER1) { 101 myToken = 'X'; 102 otherToken = 'O'; 103 read more..

  • Page - 1188

    31.6 Case Study: Distributed Tic-Tac-Toe Games 1165 152 153 waiting = true; 154 } 155 156 /** Send this player's move to the server */ 157 private void sendMove() throws IOException { 158 toServer.writeInt(rowSelected); // Send the selected row 159 toServer.writeInt(columnSelected); // Send the selected column 160 } 161 162 /** Receive read more..

  • Page - 1189

    1166 Chapter 31 Networking 212 Platform.runLater(() -> cell[row][column].setToken(otherToken)); 213 } 214 215 // An inner class for a cell 216 public class Cell extends Pane { 217 // Indicate the row and column of this cell in the board 218 private int row; 219 private int column; 220 221 // Token used for this cell 222 private char token = ' '; 223 224 read more..

  • Page - 1190

    31.6 Case Study: Distributed Tic-Tac-Toe Games 1167 272 273 getChildren().add(ellipse); // Add the ellipse to the pane 274 } 275 } 276 277 /* Handle a mouse click event */ 278 private void handleMouseClick() { 279 // If cell is not occupied and the player has the turn 280 if (token == ' ' && myTurn) { 281 read more..

  • Page - 1191

    1168 Chapter 31 Networking the other player. If the game is won or a draw, the server sends the status (PLAYER1_WON, PLAYER2_WON, or DRAW) to both players. The implementation of Java network programs at the socket level is tightly synchronized. An operation to send data from one machine requires an operation to receive data from the other machine. As shown in this example, read more..

  • Page - 1192

    Programming Exercises 1169 PROGRAMMING EXERCISES Section 31.2 *31.1 (Loan server) Write a server for a client. The client sends loan informa- tion (annual interest rate, number of years, and loan amount) to the server (see Figure  31.17a). The server computes monthly payment and total pay- ment, and sends them back to the client (see Figure 31.17b). Name the client Exercise31_01Client read more..

  • Page - 1193

    1170 Chapter 31 Networking receives the count from the server and display a message, such as You are visi- tor number 11, as shown in Figure 31.19. Name the client Exercise31_04Client and the server Exercise31_04Server. FIGURE 31.19 The client displays how many times the server has been accessed. The server stores the count. FIGURE 31.20 You can view and add an address. 31.5 (Send read more..

  • Page - 1194

    Programming Exercises 1171 Section 31.7 **31.9 (Chat) Write a program that enables two users to chat. Implement one user as the server (Figure 31.21a) and the other as the client (Figure 31.21b). The server has two text areas: one for entering text and the other (noneditable) for displaying text received from the client. When the user presses the Enter key, the current line is sent read more..

  • Page - 1195

    This page intentionally left blank read more..

  • Page - 1196

    JAVA DATABASE PROGRAMMING Objectives ■ To understand the concepts of databases and database management systems (§32.2). ■ To understand the relational data model: relational data structures, constraints, and languages (§32.2). ■ To use SQL to create and drop tables and to retrieve and modify data (§32.3). ■ To learn how to load a driver, connect to a database, execute read more..

  • Page - 1197

    1174 Chapter 32 Java Database Programming 32.1 Introduction Java provides the API for developing database applications that works with any relational database systems. You may have heard a lot about database systems. Database systems are everywhere. Your social security information is stored in a database by the government. If you shop online, your purchase information is stored in a read more..

  • Page - 1198

    32.2 Relational Database Systems 1175 Structure defines the representation of the data. Integrity imposes constraints on the data. Language provides the means for accessing and manipulating data. 32.2.1 Relational Structures The relational model is built around a simple and natural structure. A relation is actually a table that consists of nonduplicate rows. Tables are easy to read more..

  • Page - 1199

    1176 Chapter 32 Java Database Programming Figures 32.4 and 32.5. The Course table and the Enrollment table are related through their common attribute courseId, and the Enrollment table and the Student table are related through ssn. FIGURE 32.4 A Student table stores student information. deptID 444111110 Jacob R Smith 9129219434 1985-04-09 99 read more..

  • Page - 1200

    32.2 Relational Database Systems 1177 Domain Constraints Domain constraints specify the permissible values for an attribute. Domains can be specified using standard data types, such as integers, floating-point numbers, fixed-length strings, and variant-length strings. The standard data type specifies a broad range of values. Additional constraints can be specified to narrow the ranges. read more..

  • Page - 1201

    1178 Chapter 32 Java Database Programming As shown in Figure 32.6, courseId is the foreign key in Enrollment that references the primary key courseId in Course. Every courseId value must match a courseId value in Course. Enforcing Integrity Constraints The database management system enforces integrity constraints and rejects operations that would violate them. For example, if read more..

  • Page - 1202

    32.3 SQL 1179 32.3.1 Creating a User Account on MySQL Assume that you have installed MySQL 5 with the default configuration. To match all the examples in this book, you should create a user named scott with the password tiger. You can perform the administrative tasks using the MySQL Workbench or using the command line. MySQL Workbench is a GUI tool for managing MySQL read more..

  • Page - 1203

    1180 Chapter 32 Java Database Programming Note On Windows, your MySQL database server starts every time your computer starts. You can stop it by typing the command net stop mysql and restart it by typing the command net start mysql. By default, the server contains two databases named mysql and test. The mysql database contains the tables that store information about read more..

  • Page - 1204

    32.3 SQL 1181 FIGURE 32.9 You can run SQL commands in a script file. Note You can populate the javabook database using the script from Supplement IV.A. 32.3.3 Creating and Dropping Tables Tables are the essential objects in a database. To create a table, use the create table state- ment to specify a table name, attributes, and types, as in the following example: create read more..

  • Page - 1205

    1182 Chapter 32 Java Database Programming If a table is no longer needed, it can be dropped permanently using the drop table com- mand. For example, the following statement drops the Course table: drop table Course; If a table to be dropped is referenced by other tables, you have to drop the other tables first. For example, if you have created the tables Course, read more..

  • Page - 1206

    32.3 SQL 1183 For example, the following statement inserts a record into the Course table. The new record has the courseId ‘11113’, subjectId ‘CSCI’, courseNumber ‘3720’, title ‘Database Systems’, and creditHours 3. insert into Course (courseId, subjectId, courseNumber, title, numOfCredits) values ('11113', 'CSCI', '3720', 'Database Systems', 3); The column names are read more..

  • Page - 1207

    1184 Chapter 32 Java Database Programming 32.3.6 Comparison and Boolean Operators SQL has six comparison operators, as shown in Table 32.1, and three Boolean operators, as shown in Table 32.2. Operator Description = Equal to <> or != Not equal to < Less than <= Less than or equal to > Greater than >= Greater than or equal to TABLE 32.1 Comparison Operators Operator read more..

  • Page - 1208

    32.3 SQL 1185 32.3.7 The like, between-and, and is null Operators SQL has a like operator that can be used for pattern matching. The syntax to check whether a string s has a pattern p is s like p or s not like p You can use the wildcard characters % (percent symbol) and _ (underline symbol) in the pattern p. % matches zero or more characters, and _ read more..

  • Page - 1209

    1186 Chapter 32 Java Database Programming select lastName as "Last Name" , zipCode as "Zip Code" from Student where deptId = 'CS'; Note The as keyword is optional in MySQL and Oracle, but it is required in MS Access. 32.3.9 The Arithmetic Operators You can use the arithmetic operators * (multiplication), / (division), + (addition), and – (subtraction) in read more..

  • Page - 1210

    32.3 SQL 1187 When there is more than one column in the select clause, the distinct keyword applies to the whole tuple in the result. For example, the following statement displays all tuples with distinct subjectId and title, as shown in Figure 32.16. Note that some tuples may have the same subjectId but different title. These tuples are distinct. select distinct subjectId, read more..

  • Page - 1211

    1188 Chapter 32 Java Database Programming select lastName, firstName, deptId from Student where deptId = 'CS' order by lastName desc, firstName asc; 32.3.12 Joining Tables Often you need to get information from multiple tables, as demonstrated in the next query. Query 7: List the courses taken by the student Jacob Smith. To solve this query, you need to join tables read more..

  • Page - 1212

    32.4 JDBC 1189 For more features of SQL, see Supplements IV.H and IV.I. 32.7 Create the tables Course, Student, and Enrollment using the create table statements in Section  32.3.3, Creating and Dropping Tables. Insert rows into the Course, Student, and Enrollment tables using the data in Figures 32.3–32.5. 32.8 List all CSCI courses with at least four credit hours. 32.9 List read more..

  • Page - 1213

    1190 Chapter 32 Java Database Programming to access the Oracle database. For the Access database, use the JDBC-ODBC bridge driver included in the JDK. ODBC is a technology developed by Microsoft for accessing databases on the Windows platform. An ODBC driver is preinstalled on Windows. The JDBC-ODBC bridge driver allows a Java program to access any ODBC data source. 32.4.1 read more..

  • Page - 1214

    32.4 JDBC 1191 Oracle drivers, you have to add mysql-connector-java-5.1.26.jar and ojdbc6.jar in the classpath using the following DOS command on Windows: set classpath=%classpath%;c:\book\lib\mysql-connector-java-5.1.26.jar; c:\book\lib\ojdbc6.jar If you use an IDE such as Eclipse or NetBeans, you need to add these jar files into the library in the IDE. Note com.mysql.jdbc.Driver is a class read more..

  • Page - 1215

    1192 Chapter 32 Java Database Programming Suppose a data source named ExampleMDBDataSource has been created for an Access database. The following statement creates a Connection object: Connection connection = DriverManager.getConnection ("jdbc:odbc:ExampleMDBDataSource"); The databaseURL for a MySQL database specifies the host name and database name to locate a database. For read more..

  • Page - 1216

    32.4 JDBC 1193 System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3)); The getString(1), getString(2), and getString(3) methods retrieve the col- umn values for firstName, mi, and lastName, respectively. Alternatively, you can use getString("firstName"), getString("mi"), and getString("lastName") to read more..

  • Page - 1217

    1194 Chapter 32 Java Database Programming The classpath directory and jar files are separated by commas. The period (.) represents the current directory. For convenience, the driver files are placed under the c:\book\lib directory. Caution Do not use a semicolon (;) to end the Oracle SQL command in a Java program. The semicolon may not work with the Oracle JDBC drivers. It read more..

  • Page - 1218

    32.4 JDBC 1195 10 11 public class FindGrade extends Application { 12 // Statement for executing queries 13 private Statement stmt; 14 private TextField tfSSN = new TextField(); 15 private TextField tfCourseId = new TextField(); 16 private Label lblStatus = new Label(); 17 18 @Override // Override the start method in the Application class 19 public void start(Stage read more..

  • Page - 1219

    1196 Chapter 32 Java Database Programming 70 "where Student.ssn = '" + ssn + "' and Enrollment.courseId " 71 + "= '" + courseId + 72 "' and Enrollment.courseId = Course.courseId " + 73 " and Enrollment.ssn = Student.ssn"; 74 75 ResultSet rset = stmt.executeQuery(queryString); 76 77 if (rset.next()) { 78 String lastName = read more..

  • Page - 1220

    32.5 PreparedStatement PreparedStatement enables you to create parameterized SQL statements. Once a connection to a particular database is established, it can be used to send SQL statements from your program to the database. The Statement interface is used to execute static SQL statements that don’t contain any parameters. The PreparedStatement interface, extend- ing Statement, is read more..

  • Page - 1221

    1198 Chapter 32 Java Database Programming 11 public class FindGradeUsingPreparedStatement extends Application { 12 // PreparedStatement for executing queries 13 private PreparedStatement preparedStatement; 14 private TextField tfSSN = new TextField(); 15 private TextField tfCourseId = new TextField(); 16 private Label lblStatus = new Label(); 17 18 @Override // Override the start read more..

  • Page - 1222

    71 String courseId = tfCourseId.getText(); 72 try { 73 preparedStatement.setString(1, ssn); 74 preparedStatement.setString(2, courseId); 75 ResultSet rset = preparedStatement.executeQuery(); 76 77 if (rset.next()) { 78 String lastName = rset.getString(1); 79 String mi = rset.getString(2); 80 String firstName = rset.getString(3); 81 read more..

  • Page - 1223

    1200 Chapter 32 Java Database Programming Note The syntax of stored procedures is vendor specific. We use both Oracle and MySQL for demonstrations of stored procedures in this book. A CallableStatement object can be created using the prepareCall(String call) method  in the Connection interface. For example, the following code cre- ates a CallableStatement cstmt on Connection read more..

  • Page - 1224

    from Student where Student.firstName = first and Student.lastName = last; return result; end; // delimiter ; /* Please note that there is a space between delimiter and ; */ If you use an Oracle database, the function can be defined as follows: create or replace function studentFound (first varchar2, last varchar2) /* Do not name firstName and lastName. */ return read more..

  • Page - 1225

    1202 Chapter 32 Java Database Programming 28 29 if (callableStatement.getInt(1) >= 1 ) 30 System.out.println(firstName + " " + lastName + 31 " is in the database"); 32 else 33 System.out.println(firstName + " " + lastName + 34 " is not in the database"); 35 } 36 } get OUT parameter Enter student's first read more..

  • Page - 1226

    32.7 Retrieving Metadata 1203 LISTING 32.5 TestDatabaseMetaData.java 1 import java.sql.*; 2 3 public class TestDatabaseMetaData { 4 public static void main(String[] args) 5 throws SQLException, ClassNotFoundException { 6 // Load the JDBC driver 7 Class.forName("com.mysql.jdbc.Driver"); 8 System.out.println("Driver loaded"); 9 10 // Connect to a database read more..

  • Page - 1227

    1204 Chapter 32 Java Database Programming 32.7.2 Obtaining Database Tables You can identify the tables in the database through database metadata using the getTables method. Listing 32.6 displays all the user tables in the javabook database on a local MySQL database. Figure 32.25 shows a sample output of the program. LISTING 32.6 FindUserTables.java 1 import java.sql.*; 2 3 public class read more..

  • Page - 1228

    32.7 Retrieving Metadata 1205 You can use the getColumnCount() method to find the number of columns in the result and the getColumnName(int) method to get the column names. For example, Listing 32.7 dis- plays all the column names and contents resulting from the SQL SELECT statement select * from Enrollment. The output is shown in Figure 32.26. LISTING 32.7 read more..

  • Page - 1229

    1206 Chapter 32 Java Database Programming 32.24 What is DatabaseMetaData for? Describe the methods in DatabaseMetaData. How do you get an instance of DatabaseMetaData? 32.25 What is ResultSetMetaData for? Describe the methods in ResultSetMetaData. How do you get an instance of ResultSetMetaData? 32.26 How do you find the number of columns in a result set? How do you find the read more..

  • Page - 1230

    Programming Exercises 1207 QUIZ Answer the quiz for this chapter online at www.cs.armstrong.edu/liang/intro10e/quiz.html . PROGRAMMING EXERCISES *32.1 (Access and update a Staff table) Write a program that views, inserts, and updates staff information stored in a database, as shown in Figure  32.27a. The View button displays a record with a specified ID. The Insert button inserts a read more..

  • Page - 1231

    1208 Chapter 32 Java Database Programming *32.4 (Find grades) Listing 32.2, FindGrade.java, presented a program that finds a stu- dent’s grade for a specified course. Rewrite the program to find all the grades for a specified student, as shown in Figure 32.29. FIGURE 32.28 The DBConnectionPane component enables the user to enter database information. FIGURE 32.29 The program read more..

  • Page - 1232

    Programming Exercises 1209 choiceb varchar(1000), choicec varchar(1000), choiced varchar(1000), answer varchar(5)); The Quiz table stores multiple-choice questions. Suppose the multiple-choice questions are stored in a text file accessible from www.cs.armstrong.edu/liang/data/ Quiz.txt in the following format: 1. question1 a. choice a b. choice b c. choice c d. choice d Answer:cd read more..

  • Page - 1233

    1210 Chapter 32 Java Database Programming copies table Student1 into Student2. Your task is to split a full name into firstname, mi, and lastname for each record in Student1 and store a new record into Student2. *32.10 (Record unsubmitted exercises) The following three tables store information on students, assigned exercises, and exercise submission in LiveLab. LiveLab is read more..

  • Page - 1234

    Programming Exercises 1211 *32.11 (Baby names) Create the following table: create table Babyname ( year integer, name varchar(50), gender char(1), count integer, constraint pkBabyname primary key (year, name, gender) ); The baby name ranking data was described in Programming Exercise 12.31. Write a program to read data from the following URL and store into the read more..

  • Page - 1235

    This page intentionally left blank read more..

  • Page - 1236

    JAVASERVER FACES Objectives ■ To explain what JSF is (§33.1). ■ To create a JSF project in NetBeans (§33.2.1). ■ To create a JSF page (§33.2.2). ■ To create a JSF managed bean (§33.2.3). ■ To use JSF expressions in a facelet (§33.2.4). ■ To use JSF GUI components (§33.3). ■ To obtain and process input from a form (§33.4). ■ To develop a calculator read more..

  • Page - 1237

    1214 Chapter 33 JavaServer Faces 33.1 Introduction JavaServer Faces (JSF) is a new technology for developing server-side Web applications using Java. JSF enables you to completely separate Java code from HTML. You can quickly build Web applications by assembling reusable UI components in a page, connecting these components to Java programs and wiring client-generated events to read more..

  • Page - 1238

    33.2 Getting Started with JSF 1215 FIGURE 33.2 The New Web Application dialog box enables you to create a new Web project. (a) (b) FIGURE 33.3 Check JavaServer Faces and JSF 2.2 to create a Web project. 33.2.2 A Basic JSF Page A new project was just created with a default page named index.xhtml, as shown in Figure 33.4. This page is known as a facelet, which read more..

  • Page - 1239

    1216 Chapter 33 JavaServer Faces 6 xmlns:h="http://xmlns.jcp.org/jsf/html"> 7 <h:head> 8 <title>Facelet Title</title> 9 </h:head> 10 <h:body> 11 Hello from Facelets 12 </h:body> 13 </html> Line 1 is an XML declaration to state that the document conforms to the XML read more..

  • Page - 1240

    33.2 Getting Started with JSF 1217 Each xmlns attribute has a name and a value separated by an equal sign (=). The following declaration (line 5) xmlns="http://www.w3.org/1999/xhtml" specifies that any unqualified tag names are defined in the default standard XHTML namespace. The following declaration (line 6) xmlns:h="http://xmlns.jcp.org/jsf/html" allows the tags defined in read more..

  • Page - 1241

    1218 Chapter 33 JavaServer Faces Step 1. Right-click the project node jsf2demo to display a context menu as shown in Figure 33.6. Choose New, JSF Managed Bean to display the New JSF Managed Bean dialog box, as shown in Figure 33.7. (Note: if you don’t see JSF Managed Bean in the menu, choose Other to locate it in the JavaServer Faces category.) Step 2. Enter and select the read more..

  • Page - 1242

    33.2 Getting Started with JSF 1219 9 public TimeBean() { 10 } 11 12 public String getTime() { 13 return new java.util.Date().toString(); 14 } 15 } time property FIGURE 33.7 Specify the name, location, scope for the bean. FIGURE 33.8 A JavaBean for JSF was created. read more..

  • Page - 1243

    1220 Chapter 33 JavaServer Faces TimeBean is a JavaBeans with the @Named annotation, which indicates that the JSF frame- work will create and manage the TimeBean objects used in the application. You have learned to use the @Override annotation in Chapter 11. The @Override annotation tells the com- piler that the annotated method is required to override a method in a read more..

  • Page - 1244

    33.2 Getting Started with JSF 1221 5 xmlns:h="http://xmlns.jcp.org/jsf/html"> 6 <h:head> 7 <title>Display Current Time</title> 8 <meta http-equiv="refresh" content ="60" /> 9 </h:head> 10 <h:body> 11 The current time is #{timeBean.time} 12 </h:body> 13 </html> Line read more..

  • Page - 1245

    1222 Chapter 33 JavaServer Faces JSF expressions bind JavaBeans objects with facelets. You will see more use of JSF expres- sions in the upcoming examples in this chapter. 33.1 What is JSF? 33.2 How do you create a JSF project in NetBeans? 33.3 How do you create a JSF page in a JSF project? 33.4 What is a facelet? 33.5 What is the file extension name for a read more..

  • Page - 1246

    33.3 JSF GUI Components 1223 LISTING 33.4 StudentRegistrationForm.xhtml 1 <?xml version='1.0' encoding='UTF-8' ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 <html xmlns="http://www.w3.org/1999/xhtml" 5 xmlns:h="http://xmlns.jcp.org/jsf/html" 6 read more..

  • Page - 1247

    1224 Chapter 33 JavaServer Faces 30 <h:selectOneRadio id="genderSelectOneRadio"> 31 <f:selectItem itemValue="Male" 32 itemLabel="Male"/> 33 <f:selectItem itemValue="Female" 34 read more..

  • Page - 1248

    33.3 JSF GUI Components 1225 Step 2: Enter resources as the Folder Name and click Finish to create the resources folder, as shown in Figure 33.12. Step 3: Right-click the resources node in the project pane to create the image folder under resources. You can now place usIcon.gif under the image folder. FIGURE 33.12 The resources folder was created. JSF provides read more..

  • Page - 1249

    1226 Chapter 33 JavaServer Faces 33.9 What is the name space for JSF tags with prefix h and prefix f? 33.10 Describe the use of the following tags? h:form, h:panelGroup, h:panelGrid, h:inputText, h:outputText, h:inputTextArea, h:inputSecret, h:outputLabel, h:outputLink, h:selectOneMenu, h:selectOneRadio, h:selectManyCheckbox, h:selectOneListbox, h:selectManyListbox, h:selectItem, h:message, h:dataTable, h:columm, read more..

  • Page - 1250

    33.4 Processing the Form 1227 37 public String getMi() { 38 return mi; 39 } 40 41 public void setMi(String mi) { 42 this.mi = mi; 43 } 44 45 public String getGender() { 46 return gender; 47 } 48 49 public void setGender(String gender) { 50 this.gender = gender; 51 } 52 53 public String getMajor() { read more..

  • Page - 1251

    1228 Chapter 33 JavaServer Faces 99 return "<p style=\"color:red\">You entered <br />" + 100 "Last Name: " + lastName + "<br />" + 101 "First Name: " + firstName + "<br />" + 102 "MI: " + mi + "<br />" + 103 "Gender: " + gender + "<br />" + 104 "Major: " + read more..

  • Page - 1252

    33.4 Processing the Form 1229 40 </h:panelGrid> 41 42 <!-- Use combo box and list --> 43 <h:panelGrid columns="4"> 44 <h:outputLabel value="Major "/> 45 <h:selectOneMenu id="majorSelectOneMenu" 46 value="#{registration.major}"> 47 read more..

  • Page - 1253

    1230 Chapter 33 JavaServer Faces The h:selectManyCheckbox element is bound to the hobby property (line 63). When the page is sent to the server, the checked boxes are returned as an array of itemValues and set to the hobby property. The h:selectTextarea element is bound to the remarks property (line 75). When the page is sent to the server, the content in the read more..

  • Page - 1254

    33.5 Case Study: Calculator 1231 Here are the steps to develop this project: Step 1. Create a new managed bean named calculator with the request scope as shown in Listing 33.7, CalculatorJSFBean.java. Step 2. Create a JSF facelet in Listing 33.8, Calculator.xhtml. LISTING 33.7 CalculatorJSFBean.java 1 package jsf2demo; 2 3 import javax.inject.Named; 4 import read more..

  • Page - 1255

    1232 Chapter 33 JavaServer Faces 40 public void add() { 41 result = number1 + number2; 42 } 43 44 public void subtract() { 45 result = number1 - number2; 46 } 47 48 public void divide() { 49 result = number1 / number2; 50 } 51 52 public void multiply() { 53 result = number1 * number2; 54 } read more..

  • Page - 1256

    33.6 Session Tracking 1233 Three text input components along with their labels are placed in the grid panel (lines 11–24). Four button components are placed in the grid panel (lines 26–35). The bean property number1 is bound to the text input for Number 1 (line 15). The CSS style text-align: right (line 14) specifies that the text is right-aligned in the input read more..

  • Page - 1257

    1234 Chapter 33 JavaServer Faces 23 24 public String getResponse() { 25 if (guessString == null) 26 return ""; // No user input yet 27 28 int guess = Integer.parseInt(guessString); 29 if (guess < number) 30 return "Too low"; 31 else if (guess == number) 32 return "You got it" ; 33 else 34 return "Too high" ; 35 } 36 } The managed bean read more..

  • Page - 1258

    33.7 Validating Input 1235 The getResponse method converts guessString from the user input to an integer (line 28) and determines if the guess is too low (line 30), too high (line 34), and just right (line 32). LISTING 33.10 GuessNumber.xhtml 1 <?xml version='1.0' encoding='UTF-8' ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 read more..

  • Page - 1259

    1236 Chapter 33 JavaServer Faces standard validator tags in the JSF Core Tag Library or create custom validators. Table 33.2 lists some JSF input validator tags. JSF Tag Description f:validateLength validates the length of the input. f:validateDoubleRange validates whether numeric input falls within acceptable range of double values. f:validateLongRange validates whether numeric input falls read more..

  • Page - 1260

    33.7 Validating Input 1237 LISTING 33.11 ValidateForm.xhtml 1 <?xml version='1.0' encoding='UTF-8' ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 <html xmlns="http://www.w3.org/1999/xhtml" 5 xmlns:h="http://xmlns.jcp.org/jsf/html" 6 read more..

  • Page - 1261

    1238 Chapter 33 JavaServer Faces 41 <h:inputText id="heightInputText" required="true" 42 requiredMessage="Height is required" 43 validatorMessage="Height must be between 3.5 and 9.5" 44 value="#{validateForm.heightString}"> 45 read more..

  • Page - 1262

    33.8 Binding Database with Facelets 1239 24 } 25 26 public void setSsn(String ssn) { 27 this.ssn = ssn; 28 } 29 30 public String getAgeString() { 31 return ageString; 32 } 33 34 public void setAgeString(String ageString) { 35 this.ageString = ageString; 36 } 37 38 public String getHeightString() { 39 return heightString; 40 } 41 42 public void read more..

  • Page - 1263

    1240 Chapter 33 JavaServer Faces are bound to the combo box and the query result for the students enrolled in the course is bound to the table. Here are the steps to create this project: Step 1. Create a managed bean named courseName with application scope, as shown in Listing 33.13. Step 2. Create a JSF page in Listing 33.14, DisplayStudent.xhtml. Step 3. Create a read more..

  • Page - 1264

    33.8 Binding Database with Facelets 1241 Step 3.3. Enter tablestyle as the File Name and click Finish to create tablestyle.css under the resources node. Step 3.4. Define the CSS style as shown in Listing 33.15. FIGURE 33.20 You can create CSS files for Web project in NetBenas. FIGURE 33.21 The New Cascading Style Sheet dialog box creates a new style sheet file. read more..

  • Page - 1265

    1242 Chapter 33 JavaServer Faces LISTING 33.13 CourseNameJSFBean.java 1 package jsf2demo; 2 3 import java.sql.*; 4 import java.util.ArrayList; 5 import javax.enterprise.context.ApplicationScoped; 6 import javax.inject.Named; 7 8 @Named(value = "courseName") 9 @ApplicationScoped 10 public class CourseNameJSFBean { 11 private PreparedStatement studentStatement = null; 12 private read more..

  • Page - 1266

    33.8 Binding Database with Facelets 1243 59 60 public String[] getTitles() { 61 return titles; 62 } 63 64 public String getChoice() { 65 return choice; 66 } 67 68 public void setChoice(String choice) { 69 this.choice = choice; 70 } 71 72 public ResultSet getStudents() throws SQLException { 73 if (choice == null) { 74 if (titles.length == 0) 75 return read more..

  • Page - 1267

    1244 Chapter 33 JavaServer Faces 12 <h:form> 13 <h:outputLabel value="Choose a Course: " /> 14 <h:selectOneMenu value="#{courseName.choice}"> 15 <f:selectItems value="#{courseName.titles}" /> 16 </h:selectOneMenu> 17 18 <h:commandButton style="margin-left: 20px" read more..

  • Page - 1268

    33.9 Opening New JSF Pages 1245 Line 14 binds the choice property in the courseName bean with the combo box. The selection values in the combo box are bound with the titles array property (line 15). Line 22 binds the table value with a database result set using the attribute value="#{courseName.students}". The var="student" attribute associ- ates a row in read more..

  • Page - 1269

    1246 Chapter 33 JavaServer Faces FIGURE 33.22 This page lets the user enter input. FIGURE 33.23 This page lets the user confirm the input. FIGURE 33.24 This page displays the status of the user input. read more..

  • Page - 1270

    33.9 Opening New JSF Pages 1247 For this project, you need to create three JSF pages named AddressRegistration.xhtml, ConfirmAddress.xhtml, AddressStoredStatus.xhtml in Listings 33.16–33.18. The project starts with AddressRegistration.xhtml. When clicking the Submit button, the action for the button returns ”ConfirmAddress” if the last name and first name are not empty, which causes read more..

  • Page - 1271

    1248 Chapter 33 JavaServer Faces 50 <h:outputLabel value="State"/> 51 <h:selectOneMenu id="stateSelectOneMenu" 52 value="#{addressRegistration.state}"> 53 <f:selectItem itemLabel="Georgia-GA" itemValue="GA" /> 54 read more..

  • Page - 1272

    33.9 Opening New JSF Pages 1249 13 </h:form> 14 </h:body> 15 </html> LISTING 33.19 AddressRegistrationJSFBean.java 1 package jsf2demo; 2 3 import javax.inject.Named; 4 import javax.enterprise.context.SessionScoped; 5 import java.sql.*; 6 import java.io.Serializable; 7 8 @Named(value = "addressRegistration") 9 read more..

  • Page - 1273

    1250 Chapter 33 JavaServer Faces 55 56 public void setTelephone(String telephone) { 57 this.telephone = telephone; 58 } 59 60 public String getEmail() { 61 return email; 62 } 63 64 public void setEmail(String email) { 65 this.email = email; 66 } 67 68 public String getStreet() { 69 return street; 70 } 71 72 read more..

  • Page - 1274

    33.9 Opening New JSF Pages 1251 115 return ""; 116 else 117 return "Last Name and First Name are required"; 118 } 119 120 public String getInput() { 121 return "<p style=\"color:red\">You entered <br />" 122 + "Last Name: " + lastName + "<br />" 123 + read more..

  • Page - 1275

    1252 Chapter 33 JavaServer Faces 175 176 return "AddressStoredStatus"; 177 } 178 179 public String getStatus() { 180 return status; 181 } 182 } A session-scoped managed bean must implement the java.io.Serializable interface. So, the AddressRegistration class is defined as a subtype of java.io.Serializable. The action for the Register button in the read more..

  • Page - 1276

    Programming Exercises 1253 5. In JSF, the facelets are the view for presenting data. Data are obtained from Java objects. Objects are defined using Java classes. 6. In JSF, the objects that are accessed from a facelet are JavaBeans objects. 7. The JSF expression can either use the property name or invoke the method to obtain the current time. 8. JSF provides many elements read more..

  • Page - 1277

    1254 Chapter 33 JavaServer Faces FIGURE 33.26 The JSF page displays the multiplication table. FIGURE 33.25 The JSF page displays factorials for the numbers from 0 to 10 in a table. read more..

  • Page - 1278

    Programming Exercises 1255 FIGURE 33.27 The JSF page computes the tax. (a) (b) *33.8 (Guess capitals) Write a JSF that prompts the user to enter a capital for a state, as shown in Figure 33.31a. Upon receiving the user input, the program reports whether the answer is correct, as shown in Figure 33.31b. You can click the Next button to display another question. You can use a read more..

  • Page - 1279

    1256 Chapter 33 JavaServer Faces state char(2), telephone char(10), email varchar(40), primary key (id) ); *33.10 (Random cards) Write a JSF that displays four random cards from a deck of 52 cards, as shown in Figure 33.33. When the user clicks the Refresh button, four new random cards are displayed. ***33.11 (Game: the 24-point card game) Rewrite Exercise 20.13 using read more..

  • Page - 1280

    Programming Exercises 1257 FIGURE 33.29 The program displays addition questions in (a) and answers in (b). (a) (b) *33.13 (Day of week) Write a program that displays the day of the week for a given day, month, and year, as shown in Figure 33.36. The program lets the user select a day, month, and year, and click the Get Day of Week button to display the day of week. The read more..

  • Page - 1281

    1258 Chapter 33 JavaServer Faces FIGURE 33.30 (a) The program displays five sets of numbers for the user to check the boxes. (b) The program displays the date. (b) (a) FIGURE 33.31 (a) The program displays a question. (b) The program displays the answer to the question. (b) (a) read more..

  • Page - 1282

    Programming Exercises 1259 FIGURE 33.32 The web page lets you view, insert, and update staff information. FIGURE 33.33 This JSF application displays four random cards. read more..

  • Page - 1283

    1260 Chapter 33 JavaServer Faces FIGURE 33.34 The JSF application solves a 24-Point card game. FIGURE 33.35 The user enters four numbers and the program finds a solution. read more..

  • Page - 1284

    Programming Exercises 1261 FIGURE 33.36 The user enters a day, month, and year and the program finds the day of the week. read more..

  • Page - 1285

    This page intentionally left blank read more..

  • Page - 1286

    1263 APPENDIXES Appendix A Java Keywords Appendix B The ASCII Character Set Appendix C Operator Precedence Chart Appendix D Java Modifiers Appendix E Special Floating-Point Values Appendix F Number Systems Appendix G Bitwise Operations Appendix H Regular Expressions Appendix I Enumerated Types read more..

  • Page - 1287

    This page intentionally left blank read more..

  • Page - 1288

    1265 Java Keywords The following fifty keywords are reserved for use by the Java language: APPENDIX A abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp* super switch synchronized this throw throws transient try read more..

  • Page - 1289

    1266 APPENDIX B The ASCII Character Set Tables B.1 and B.2 show ASCII characters and their respective decimal and hexadecimal codes. The decimal or hexadecimal code of a character is a combination of its row index and column index. For example, in Table B.1, the letter A is at row 6 and column 5, so its decimal equivalent is 65; in Table B.2, letter A is at row read more..

  • Page - 1290

    1267 TABLE B.1 ASCII Character Set in the Decimal Index 0123456789 0 nul soh stx etx eot enq ack bel bs ht 1 nl vt ff cr so si dle dcl dc2 dc3 2 dc4 nak syn etb can em sub esc fs gs 3rs us sp ! ” #$% & ’ 4 ()* + , - ./ 0 1 523456789: ; 6 6 = 7 ? @ A BCD E 7 F GHI J K L M NO 8 P QR S T UVW XY 9Z [ \ ] ¿ - ’a b c 10 d e f g h ijk lm 11 nopqr s t uvw 12 xyz { } ∼ read more..

  • Page - 1291

    1268 APPENDIX C Operator Precedence Chart The operators are shown in decreasing order of precedence from top to bottom. Operators in the same group have the same precedence, and their associativity is shown in the table. Operator Name Associativity () Parentheses Left to right () Function call Left to right [] Array subscript Left to right . Object member access Left to right ++ read more..

  • Page - 1292

    Appendix C 1269 Operator Name Associativity == Equal comparison Left to right != Not equal Left to right & (Unconditional AND) Left to right ^ (Exclusive OR) Left to right | (Unconditional OR) Left to right && Conditional AND Left to right || Conditional OR Left to right ?: Ternary condition Right to left = Assignment Right to left += Addition assignment Right to left –= Subtraction read more..

  • Page - 1293

    1270 APPENDIX D Java Modifiers Modifiers are used on classes and class members (constructors, methods, data, and class-level blocks), but the final modifier can also be used on local variables in a method. A modifier that can be applied to a class is called a class modifier. A modifier that can be applied to a method is called a method modifier. A modifier that can be read more..

  • Page - 1294

    Appendix D 1271 The modifiers default (no modifier), public, private, and protected are known as visibility or accessibility modifiers because they specify how classes and class members are accessed. The modifiers public, private, protected, static, final, and abstract can also be applied to inner classes. Modifier Class Constructor Method Data Block Explanation synchronized UU Only one read more..

  • Page - 1295

    1272 APPENDIX E Special Floating-Point Values Dividing an integer by zero is invalid and throws ArithmeticException, but dividing a floating-point value by zero does not cause an exception. Floating-point arithmetic can over- flow to infinity if the result of the operation is too large for a double or a float, or under- flow to zero if the result is too small for a double read more..

  • Page - 1296

    1273 Number Systems F.1 Introduction Computers use binary numbers internally, because computers are made naturally to store and process 0s and 1s. The binary number system has two digits, 0 and 1. A number or character is stored as a sequence of 0s and 1s. Each 0 or 1 is called a bit (binary digit). In our daily life we use decimal numbers. When we write a number read more..

  • Page - 1297

    1274 Appendix F F.2 Conversions Between Binary and Decimal Numbers Given a binary number bnbn - 1bn - 2 c b2b1b0, the equivalent decimal value is bn * 2n + bn - 1 * 2n - 1 + bn - 2 * 2n - 2 + c + b2 * 22 + b1 * 21 + b0 * 20 Here are some examples of converting binary numbers to decimals: binary to decimal Binary Conversion Formula Decimal 10 1 * 21 + read more..

  • Page - 1298

    Appendix F 1275 F.3 Conversions Between Hexadecimal and Decimal Numbers Given a hexadecimal number hnhn - 1hn - 2 c h2h1h0, the equivalent decimal value is hn * 16n + hn - 1 * 16n - 1 + hn - 2 * 16n - 2 + c + h2 * 162 + h1 * 161 + h0 * 160 Here are some examples of converting hexadecimal numbers to decimals: hex to decimal Hexadecimal Conversion Formula read more..

  • Page - 1299

    1276 Appendix F Note Octal numbers are also useful. The octal number system has eight digits, 0 to 7. A deci- mal number 8 is represented in the octal system as 10. Here are some good online resources for practicing number conversions: ■ http://forums.cisco.com/CertCom/game/binary_game_page.htm ■ http://people.sinclair.edu/nickreeder/Flash/binDec.htm ■ read more..

  • Page - 1300

    1277 Bitwise Operations To write programs at the machine-level, often you need to deal with binary numbers directly and perform operations at the bit-level. Java provides the bitwise operators and shift operators defined in Table G.1. The bit operators apply only to integer types (byte, short, int, and long). A character involved in a bit operation is converted to an integer. read more..

  • Page - 1301

    1278 APPENDIX H Regular Expressions Often you need to write the code to validate user input such as to check whether the input is a number, a string with all lowercase letters, or a social security number. How do you write this type of code? A simple and effective way to accomplish this task is to use the regular expression. A regular expression (abbreviated regex) is read more..

  • Page - 1302

    Appendix H 1279 TABLE H.1 Frequently Used Regular Expressions Regular Expression Matches Example x a specified character x Java matches Java . any single character Java matches J..a (ab|cd) ab or cd ten matches t(en|im) [abc] a, b, or c Java matches Ja[uvwx]a [^abc] any character except a, b, or c Java matches Ja[^ars]a [a-z] a through z Java matches [A-M]av[a-d] [^a-z] any read more..

  • Page - 1303

    1280 Appendix H Caution Do not use spaces in the repeat quantifiers. For example, A{3,6} cannot be written as A{3, 6} with a space after the comma. Note You may use parentheses to group patterns. For example, (ab){3} matches ababab, but ab{3} matches abbb. Let us use several examples to demonstrate how to construct regular expressions. Example 1 The pattern for social read more..

  • Page - 1304

    Appendix H 1281 For example, "Smith".matches("[A-Z][a-zA-Z]{1,24}") returns true. "Jones123".matches("[A-Z][a-zA-Z]{1,24}") returns false. Example 5 Java identifiers are defined in Section 2.4, “Identifiers.” ■ An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. ■ An identifier is a sequence read more..

  • Page - 1305

    1282 Appendix H The following code System.out.println("Java Java Java".replaceFirst("v\\w", "wi")); displays Jawi Java Java There are two overloaded split methods. The split(regex) method splits a string into substrings delimited by the matches. For example, the following statement String[] tokens = "Java1HTML2Perl".split("\\d"); splits string read more..

  • Page - 1306

    1283 Enumerated Types I.1 Simple Enumerated Types An enumerated type defines a list of enumerated values. Each value is an identifier. For exam- ple, the following statement declares a type, named MyFavoriteColor, with values RED, BLUE, GREEN, and YELLOW in this order. enum MyFavoriteColor {RED, BLUE, GREEN, YELLOW}; A value of an enumerated type is like a constant and so, by read more..

  • Page - 1307

    1284 Appendix I Listing I.1 gives a program that demonstrates the use of enumerated types. LISTING I.1 EnumeratedTypeDemo.java 1 public class EnumeratedTypeDemo { 2 static enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, 3 FRIDAY, SATURDAY}; 4 5 public static void main(String[] args) { 6 Day day1 = Day.FRIDAY; 7 Day day2 = Day.THURSDAY; read more..

  • Page - 1308

    Appendix I 1285 9 System.out.println("day2's ordinal is " + day2.ordinal()); 10 11 System.out.println("day1.equals(day2) returns " + 12 day1.equals(day2)); 13 System.out.println("day1.toString() returns " + 14 day1.toString()); 15 System.out.println("day1.compareTo(day2) returns " + 16 day1.compareTo(day2)); 17 read more..

  • Page - 1309

    1286 Appendix I I.3 Processing Enumerated Values Using a Foreach Loop Each enumerated type has a static method values() that returns all enumerated values for the type in an array. For example, Day[] days = Day.values(); You can use a regular for loop in (a) or a foreach loop in (b) to process all the values in the array. I.4 Enumerated Types with Data Fields, read more..

  • Page - 1310

    Appendix I 1287 An enumerated value TrafficLight.red is assigned to variable light (line 3). Accessing TrafficLight.RED causes the JVM to invoke the constructor with argument “please stop”. The methods in enumerated type are invoked in the same way as the methods in a class. light.getDescription() returns the description for the enumerated value (line 4). Note The Java read more..

  • Page - 1311

    This page intentionally left blank read more..

  • Page - 1312

    1289 INDEX Symbols — (decrement operator), 55–56 - (subtraction operator), 46, 50–51 . (dot operator), 330 . (object member access operator), 330, 429 / (division operator), 46, 50 //, in line comment syntax, 18 /*, in block comment syntax, 18 /**.*/ (Javadoc comment syntax), 18 /= (division assignment operator), 54–55 ; (semicolons), common errors, 84 \ (backslash character), as read more..

  • Page - 1313

    1290 Index APIs (Application Program Interfaces) Java API for accessing relational databases. see JDBC (Java Database Connectivity) libraries as, 11 Application Program Interfaces (APIs), 11 Application-scoped bean, 1233 Apps, developing on Web servers, 11 Arc overview, 567 ShowArc.java, 568–569 Arguments defining methods and, 205 passing by values, 212–215 receiving string arguments from command read more..

  • Page - 1314

    Index 1291 Assignment statements (assignment expressions) assigning value to variables, 36 overview of, 41–43 Associative arrays. see Maps Associativity, of operators, 105, 1268–1269 atan method, trigonometry, 120–121 Attributes columns in relational structures, 1175 object, 322 table, 1181 Audio files case study: national flags and anthems, 665–667 MediaDemo.java, 663–664 Auto commit, SQL read more..

  • Page - 1315

    1292 Index TestBSTWithIterator.java example, 953–954 tree traversal, 933–934 TreeControl.java example, 949–952 Tree.java example, 935–936 Binary trees, 930 binarySearch method applying to lists, 774 Arrays class, 270–271 BindException, server sockets and, 1141 Binding properties BindingDemo.java, 544 ShowCircleCentered.java, 542–543 Bit operators, 1277 Bits (binary digits), 3 Bitwise operators, 1277 read more..

  • Page - 1316

    Index 1293 Catching exceptions. see also try-catch blocks catch block omitted when finally clause is used, 467 CircleWithException.java example, 463 InputMismatchExceptionDemo.java example, 454–455 overview of, 459–461 QuotientWithException.java example, 521–522 CDs (compact discs), as storage device, 5 Cells in Sudoku grid, 298 in tic-tac-toe case study, 657–662 Celsius, converting to/from read more..

  • Page - 1317

    1294 Index clone method, shallow and deep copies, 515–516 Cloneable interface House.java example, 514–517 overview, 513–514 Closest-pair animation, 858 Closest pair problem, two-dimensional array applied to, 296–297COBOL, high-level languages, 8 Code arrays for simplifying, 250–251 comments and, 101 incremental development, 161 programming. see Programs/programming reuse. see Reusable code sharing. read more..

  • Page - 1318

    Index 1295 naming conventions, overview of, 629–630 quiz and exercises, 668–676 scroll bars, 651–652 ScrollBarDemo.java, 652–653 SliderDemo.java, 655–656 sliders, 654 summary, 668 text area, 641–642 TextAreaDemo.java, 644 Composition, in designing stacks and queues, 921 Composition relationships between ArrayList and MyStack, 439–440 aggregation and, 374–375 Compound expressions case study: read more..

  • Page - 1319

    1296 Index Cursor, mouse, 6 Cycle, connected graphs, 1018 D .dat files (binary), 680 Data, arrays for referencing, 246 Data compression Huffman coding for, 954–956 HuffmanCode.java example, 956–959 Data definition language (DDL), 1192 Data fields accessing object data, 330–331 encapsulating, 344–345, 526 in interfaces, 508 object state represented by, 322–323 protected in abstract classes, 899 read more..

  • Page - 1320

    Index 1297 Declaring methods generic methods, 743 static methods, 337 Declaring variables array variables, 246 overview of, 40–41 specifying data types and, 35–36 two-dimensional array variables, 288–289 Decrement (––) operator, 55–56 Deep copies, 516 Default field values, for data fields, 331–332 Degree of vertex, 1018 Delete key, on keyboards, 6 delete method, AVLTree class, 981 read more..

  • Page - 1321

    1298 Index Edge-weighted graphs overview of, 1062 WeightedGraph class, 1064 Eight Queens puzzle EightQueens.java, 847–848 parallel, 1136 recursion, 734–735 single-dimensional arrays, 281 solving, 846–847 Element type, specifying for arrays, 246 Emirp, 240 Empty element, 1221 Encapsulation in CircleWithPrivateDataFields.java example, 345–346 class design guidelines, 525–526 of classes, 366–367 of read more..

  • Page - 1322

    Index 1299 Feet, converting to/from meters, 236 fib method, 710–712 Fibonacci, Leonardo, 710 Fibonacci numbers algorithm for finding, 831 case study: computing, 709–710 ComputeFibonacci.java, 710–712 computing recursively, 729 ImprovedFibonacci.java example, 832 recurrence relations and, 829 FigurePanel class File class, 473–475, 678 File I/O. see I/O (input/output) File pointers, read more..

  • Page - 1323

    1300 Index restrictions on generic types, 750–752 summary, 757–758 wildcards for specifying range of generic types, 747–750 Genome, 367 GeometricObject class Circle.java and Rectangle.java, 498 overview of, 496 TestGeometricObject.java, 498–499 getAbsolutePath method, File class, 574–575 getArea method, SimpleCircle example, 325 getArray method, 293–294 getBMI method, BMI class, 372 read more..

  • Page - 1324

    Index 1301 TestMyHashMap.java example of map implementation, 1002–1003 TestMyHashSet.java example of set implementation, 1010–1011 what it is, 986–987 HashMap class concrete implementation of Map class, 810–812 implementation of Map class, 986 load factor thresholds, 994 overview of, 813 TestMap.javaexample, 813–815 types of maps, 810–811 HashSet class case study: counting keywords, 809–810 read more..

  • Page - 1325

    1302 Index MyList.java, 897–898 string index range, 131 indexOf method, 136–137 List interface, 769 MyArrayList.java example, 901, 905 Indirect recursion, 709 InetAddress class, 1147–1148 Infinite loops, 160 Infinite recursion, 709 Information getting information about exceptions, 461–462 hiding (encapsulation), 225 Inheritance ArrayList object, 432–433 calling subclass constructors, 416–417 calling read more..

  • Page - 1326

    Index 1303 generic method for sorting array of Comparable objects, 744 greatest common denominator of, 833 hash codes for primitive types, 987 IntegerMatrix.java example, 755–756 java.util.Random, 335–336 numeric types for, 44–45 sorting, 881 sorting int values, 887 specifying data types, 35 TestIntegerMatrix.java example, 756 Integrated development environments (IDEs), 11–12, 15–16 for read more..

  • Page - 1327

    1304 Index Java database programming accessing databases using JavaFX, 1194–1196 CallableStatement for executing SQL stored procedures, 1199–1202 column aliases, 1185–1186 creating databases, 1180–1181 creating tables, 1181–1182 creating user account in MySQL, 1179–1180 database metadata, 1202–1203 developing database applications using JDBC, 1190–1193 insert, update, and delete statements, read more..

  • Page - 1328

    Index 1305 Random class, 335–336 Scanner class, 38, 578–480 jdb debugger, 106 JDBC (Java Database Connectivity) developing database applications, 1190–1193 overview of, 1189–1190 SimpleJDBC.java, 1193–1194 JDK (Java Development Toolkit) Fork/Join Framework in JDK 7, 1128–1129 jdb debugger in, 106 overview of, 11–12 join method, Thread class, 1104 Joins Fork/Join Framework and, 1128 read more..

  • Page - 1329

    1306 Index Line overview, 562 ShowLine.java, 562–563 Line comments, in Welcome.java, 13 Line numbers, in Welcome.java, 12 Linear probing, collision handling, 989–990 Linear search algorithm, 857–858 comparing growth functions, 829–830 recurrence relations and, 829 Linear searches, arrays, 265–266 Linked data structures binary search trees, 930–931 blocking queues, 1122–1123 hash maps. see read more..

  • Page - 1330

    Index 1307 creating arrays, 257 deciding which to use, 174–176 design strategies, 163 do-while loop, 168–170 examples of determining Big O, 824–827 graph edges, 1018 input and output redirections, 167–168 iteration compared with recursion, 726 key terms, 190 for loop, 170–174 minimizing numeric errors related to, 178–179 nesting, 176–177 overview of, 158 quiz and exercises, read more..

  • Page - 1331

    1308 Index Mersenne prime, 240 MessagePanel class DisplayClock.java, 573–574 ClockPane.java, 574–576 Metadata retrieval, from databases database metadata, 1202–1203 obtaining tables, 1204 overview of, 1202 result set metadata, 1204–1205 Meters, converting to/from feet, 236 Method header, 205 Method modifiers, 205, 1270–1271 Method signature, 205 Methods abstraction and, 225–226 accessing object read more..

  • Page - 1332

    Index 1309 Multi-way if-else statements in computing taxes, 90–93 overview of, 81–83 Mutator methods. see Setter (mutator) methods MySQL creating databases, 1180–1181 creating tables, 1181–1182 creating user account in, 1179–1180 JDBC drivers for accessing Oracle databases, 1189–1192 stopping/starting, 1180 tutorials on, 1178 N Named constants. see Constants Naming conventions class design read more..

  • Page - 1333

    1310 Index O Object class, 422–423, 431–432 Object I/O. see ObjectInputStream/ObjectOutputStream classes Object member access operator (.), 330, 429 Object reference variables, 330 ObjectInputStream/ObjectOutputStream classes overview of, 692–693 serializable interface, 695–696 Serializing arrays, 696–697 TestObjectInputStream.java, 694 TestObjectOutputStream.java, 693–694 Object-oriented programming (OOP), read more..

  • Page - 1334

    Index 1311 Overflows Rational class, 524 variables, 45 Overloading methods, 219–222 Overriding methods, 419–422, 970 P p (pi), estimating, 237 Package-private (package-access) visibility modifiers, 342 Packages organizing classes in, 343 organizing programs in, 18 Packet-based communication, Java supporting, 1140 Page Down key, on keyboards, 5 Page Up key, on keyboards, 5 Pair of read more..

  • Page - 1335

    1312 Index Priority queues implementing, 924 MyPriorityQueue.java example, 924 overview of, 783 PriorityQueue class, 784–785 for storing weighted edges, 1063 TestPriorityQueue.java example, 924–925 PriorityBlockingQueue class, 1122–1123 PriorityQueue class, 784–785 private encapsulation of data fields and, 344–345 visibility modifier, 343–344, 440–443 Problems breaking into subproblems, 190 creating read more..

  • Page - 1336

    Index 1313 random method case study: generating random numbers, 223–225 case study: lottery, 98–99 Math class, 87–88, 122 Random numbers case study: generating random numbers, 223–225 case study: lottery, 98–99 generating, 87–88 Random-access files overview of, 697–699 TestRandomAccessFile.java, 699–700 Random-access memory (RAM), 4–5 Rational class case study: designing class for matrix read more..

  • Page - 1337

    1314 Index Right subtree, of binary trees, 930 Right-heavy, balancing AVL nodes, 966 RL imbalance, AVL nodes, 967–968 RL rotation AVLTree class, 972–973 balancing nodes on a path, 970 options for balancing AVL nodes, 967–968 Root, of binary trees, 930–931 Rotation AVLTree class, 972–973 balancing nodes on a path, 970–971 implementing, 971 methods for performing, 977 options for read more..

  • Page - 1338

    Index 1315 setPriority method, Thread class, 1104 setRadius method CircleWithPrivateDataFields.java example, 346 SimpleCircle example, 325 Sets case study: counting keywords, 809–810 as collection type, 762 comparing list performance with, 806–808 HashSet class, 798–799 key terms, 817 LinkedHashSet class, 802 overview of, 798 questions and exercises, 818–820 singleton and unmodifiable, 8816–817 read more..

  • Page - 1339

    1316 Index Specific import, 18 split method, strings, 388, 389 SQL (Structured Query Language) CallableStatement for executing SQL stored procedures, 1199–1202 column aliases, 1185–1186 creating databases, 1180–1181 creating tables, 1181–1182 creating user account in MySQL, 1179–1180 for defining and accessing databases, 1174 insert, update, and delete statements, 1182–1183 JDBC and, 1190–1194 read more..

  • Page - 1340

    Index 1317 Structure, in relational data model, 1174–1175 Structured Query Language. see SQL (Structured Query Language) Subclasses abstract methods and, 496 abstracting, 500 constructors, 416–417 of Exception class, 456–457 inheritance and, 410–411 of RuntimeException class, 457 Subdirectories, 717 Subgraphs, 1018 Subinterfaces, 518 substring method, 135, 714 Substrings, 135–136 Subtraction (-) read more..

  • Page - 1341

    1318 Index Three-dimensional arrays. see Arrays, multi-dimensional throw keyword chained exceptions, 470 throw ex for rethrowing exceptions, 469 for throwing exceptions, 459 Throwable class generic classes not extending, 752 getting information about exceptions, 461–462 java.lang, 455–456 Throwing exceptions CircleWithException.java example, 463 QuotientWithException.java example, 453 rethrowing, 468–469 read more..

  • Page - 1342

    Index 1319 Underflow, floating point numbers, 66 Undirected graphs, 1017 Unicode character data type (char) and, 125–129 data input and output streams, 685 generating random numbers and, 223 text encoding, 678 text I/O vs. binary I/O, 679 Unified Modeling Language. see UML (Unified Modeling Language) Uniform Resource Locators. see URLs (Uniform Resource Locators) Unique addresses, for read more..

  • Page - 1343

    1320 Index representing, 1063 shortest paths, 1078 summary, 1090 TestMinimumSpanningTree.java, 1076–1078 TestShortestPath.java, 1084–1086 TestWeightedGraph.java, 1070–1072 weighted adjacency matrices, 1064 weighted edges using edge array, 1063–1064 WeightedGraph class, 1065–1066 WeightedGraph.java, 1066–1070 WeightedEdge class, 1064 WeightedGraph class getMinimumSpanningTree method, 1075, 1077–1078 overview of, read more..

  • Page - 1344

    Console Input Scanner input = new Scanner(System.in); int intValue = input.nextInt(); long longValue = input.nextLong(); double doubleValue = input.nextDouble(); float floatValue = input.nextFloat(); String string = input.next(); String line = input.nextLine(); Console Output System.out.println(anyValue); Primitive Data Types byte 8 bits short 16 bits int 32 bits long 64 bits float 32 bits double 64 read more..

  • Page - 1345

    Frequently Used Static Constants/Methods Math.PI Math.random() Math.pow(a, b) Math.abs(a) Math.max(a, b) Math.min(a, b) Math.sqrt(a) Math.sin(radians) Math.asin(a) Math.toRadians(degrees) Math.toDegress(radians) System.currentTimeMillis() Integer.parseInt(string) Integer.parseInt(string, radix) Double.parseDouble(string) Arrays.sort(type[] list) Arrays.binarySearch(type[] list, type key) Array/Length/Initializer int [] list = new int [10]; read more..

Write Your Review