Download presentation
Presentation is loading. Please wait.
Published byScott Atkinson Modified over 7 years ago
1
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 1 Introduction Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
2
Focus of the Course Object-Oriented Software Development
problem solving program design, implementation, and testing object-oriented concepts classes objects encapsulation inheritance polymorphism graphical user interfaces the Java programming language Copyright © 2012 Pearson Education, Inc.
3
Introduction We start with the fundamentals of computer processing
Chapter 1 focuses on: components of a computer how computers store and manipulate information computer networks the Internet and the World Wide Web programming and programming languages an introduction to Java an overview of object-oriented concepts Copyright © 2012 Pearson Education, Inc.
4
Outline Computer Processing Hardware Components Networks
The Java Programming Language Program Development Object-Oriented Programming Copyright © 2012 Pearson Education, Inc.
5
Hardware and Software Hardware Software
the physical, tangible parts of a computer keyboard, monitor, disks, wires, chips, etc. Software programs and data a program is a series of instructions A computer requires both hardware and software Each is essentially useless without the other Copyright © 2012 Pearson Education, Inc.
6
CPU and Main Memory Central Processing Unit Main Memory
Chip that executes program commands Primary storage area for programs and data that are in active use Synonymous with RAM Copyright © 2012 Pearson Education, Inc.
7
Input / Output Devices Monitor screen Keyboard Central Mouse
Touch screen Central Processing Unit Main Memory I/O devices facilitate user interaction Copyright © 2012 Pearson Education, Inc.
8
Secondary Memory Devices
Information is moved between main and secondary memory as needed Central Processing Unit Main Memory Hard Disk USB Flash Drive Secondary memory devices provide long-term storage Copyright © 2012 Pearson Education, Inc.
9
Software Categories Operating System Application program
controls all machine activities provides the user interface to the computer manages resources such as the CPU and memory Windows, Mac OS, Unix, Linux, Application program generic term for any other kind of software word processors, missile control systems, games Most operating systems and application programs have a graphical user interface (GUI) Copyright © 2012 Pearson Education, Inc.
10
Analog vs. Digital There are two basic ways to store and manage data:
continuous, in direct proportion to the data represented music on a record album - a needle rides on ridges in the grooves that are directly proportional to the voltages sent to the speaker Digital the information is broken down into pieces, and each piece is represented separately sampling – record discrete values of the analog representation music on a compact disc - the disc stores numbers representing specific voltage levels sampled at specific times Copyright © 2012 Pearson Education, Inc.
11
Analog Information Copyright © 2012 Pearson Education, Inc.
12
Sampling Copyright © 2012 Pearson Education, Inc.
13
Digital Information Computers store all information digitally:
numbers text graphics and images audio video program instructions In some way, all information is digitized - broken down into pieces and represented as numbers Copyright © 2012 Pearson Education, Inc.
14
Representing Text Digitally
For example, every character is stored as a number, including spaces, digits, and punctuation Corresponding upper and lower case letters are separate characters H i , H e a t h e r . Copyright © 2012 Pearson Education, Inc.
15
Binary Numbers Once information has been digitized, it is represented and stored in memory using the binary number system A single binary digit (0 or 1) is called a bit Devices that store and move information are cheaper and more reliable if they have to represent only two states A single bit can represent two possible states, like a light bulb that is either on (1) or off (0) Permutations of bits are used to store values Copyright © 2012 Pearson Education, Inc.
16
Bit Permutations 1 bit 1 2 bits 00 01 10 11 3 bits 000 001 010 011 100
1 2 bits 00 01 10 11 3 bits 000 001 010 011 100 101 110 111 4 bits 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 Each additional bit doubles the number of possible permutations Copyright © 2012 Pearson Education, Inc.
17
Bit Permutations Each permutation can represent a particular item
There are 2N permutations of N bits Therefore, N bits are needed to represent 2N unique items 1 bit ? 2 bits ? 3 bits ? 4 bits ? 5 bits ? How many items can be represented by 21 = 2 items 22 = 4 items 23 = 8 items 24 = 16 items 25 = 32 items Copyright © 2012 Pearson Education, Inc.
18
Quick Check How many bits would you need to represent each of the 50 United States using a unique permutation of bits? Copyright © 2012 Pearson Education, Inc.
19
Quick Check How many bits would you need to represent each of the 50 United States using a unique permutation of bits? Alabama Alaska Arizona Arkansas California Colorado etc. Five bits wouldn't be enough, because 25 is 32. Six bits would give us 64 permutations, and some wouldn't be used. Copyright © 2012 Pearson Education, Inc.
20
Outline Computer Processing Hardware Components Networks
The Java Programming Language Program Development Object-Oriented Programming Copyright © 2012 Pearson Education, Inc.
21
A Computer Specification
Consider the following specification for a personal computer: 3.07 GHz Intel Core i7 processor 4 GB RAM 750 GB Hard Disk 16x Blu-ray / HD DVD-ROM & 16x DVD+R DVD Burner 17” Flat Screen Video Display with 1280 x 1024 resolution Network Card Copyright © 2012 Pearson Education, Inc.
22
Computer Architecture
Copyright © 2012 Pearson Education, Inc.
23
Memory Main memory is divided into many memory locations (or cells) 9278 9279 9280 9281 9282 9283 9284 9285 9286 Each memory cell has a numeric address, which uniquely identifies it Copyright © 2012 Pearson Education, Inc.
24
Storing Information 9278 9279 9280 9281 9282 9283 9284 9285 9286 Each memory cell stores a set number of bits (usually 8 bits, or one byte) Large values are stored in consecutive memory locations Copyright © 2012 Pearson Education, Inc.
25
Storage Capacity Every memory device has a storage capacity, indicating the number of bytes it can hold Capacities are expressed in various units: Unit Symbol Number of Bytes kilobyte KB 210 = 1024 megabyte MB 220 (over one million) gigabyte GB 230 (over one billion) terabyte TB 240 (over one trillion) petabyte PB 250 (a whole bunch) Copyright © 2012 Pearson Education, Inc.
26
Memory Main memory is volatile - stored information is lost if the electric power is removed Secondary memory devices are nonvolatile Main memory and disks are direct access devices - information can be reached directly The terms direct access and random access often are used interchangeably A magnetic tape is a sequential access device since its data is arranged in a linear order - you must get by the intervening data in order to access other information Copyright © 2012 Pearson Education, Inc.
27
Hard Disk Drive Copyright © 2012 Pearson Education, Inc.
28
RAM vs. ROM RAM - Random Access Memory (direct access)
ROM - Read-Only Memory The terms RAM and main memory are basically interchangeable ROM could be a set of memory chips, or a separate device, such as a CD ROM Both RAM and ROM are random (direct) access devices! RAM probably should be called Read-Write Memory Copyright © 2012 Pearson Education, Inc.
29
Compact Discs A CD-ROM is portable read-only memory
A microscopic pit on a CD represents a binary 1 and a smooth area represents a binary 0 A low-intensity laser reflects strongly from a smooth area and weakly from a pit A CD-Recordable (CD-R) drive can be used to write information to a CD once A CD-Rewritable (CD-RW) can be erased and reused The speed of a CD drive indicates how fast (max) it can read and write information to a CD Copyright © 2012 Pearson Education, Inc.
30
DVDs A DVD is the same physical size as a CD, but can store much more information The format of a DVD stores more bits per square inch A CD can store 650 MB, while a standard DVD can store 4.7 GB A double sided DVD can store 9.4 GB Other advanced techniques can bring the capacity up to 17.0 GB Like CDs, there are DVD-R and DVD-RW discs Copyright © 2012 Pearson Education, Inc.
31
The Central Processing Unit
A CPU is on a chip called a microprocessor It continuously follows the fetch-decode-execute cycle: fetch Retrieve an instruction from main memory decode Determine what the instruction is execute Carry out the instruction Copyright © 2012 Pearson Education, Inc.
32
The Central Processing Unit
Arithmetic / Logic Unit Performs calculations and makes decisions Coordinates processing steps Control Unit Small storage areas Registers Copyright © 2012 Pearson Education, Inc.
33
The Central Processing Unit
The speed of a CPU is controlled by the system clock The system clock generates an electronic pulse at regular intervals The pulses coordinate the activities of the CPU The speed is usually measured in gigahertz (GHz) Copyright © 2012 Pearson Education, Inc.
34
Monitor The size of a monitor (17") is measured diagonally, like a television screen A monitor has a certain maximum resolution , indicating the number of picture elements, called pixels, that it can display (such as 1280 by 1024) High resolution (more pixels) produces sharper pictures Copyright © 2012 Pearson Education, Inc.
35
Outline Computer Processing Hardware Components Networks
The Java Programming Language Program Development Object-Oriented Programming Copyright © 2012 Pearson Education, Inc.
36
Networks A network is two or more computers that are connected so that data and resources can be shared Most computers are connected to some kind of network Each computer has its own network address, which uniquely identifies it among the others A file server is a network computer dedicated to storing programs and data that are shared among network users Copyright © 2012 Pearson Education, Inc.
37
Network Connections Each computer in a network could be directly connected to every other computer in the network These are called point-to-point connections Adding a computer requires a new communication line for each computer already in the network This technique is not practical for more than a few close machines Copyright © 2012 Pearson Education, Inc.
38
Network Connections Most networks share a single communication line
Adding a new computer to the network is relatively easy Network traffic must take turns using the line, which introduces delays Often information is broken down in parts, called packets, which are sent to the receiving machine and then reassembled Copyright © 2012 Pearson Education, Inc.
39
A Computer Network Copyright © 2012 Pearson Education, Inc.
40
Local-Area Networks A Local-Area Network (LAN) covers a small
distance and a small number of computers A LAN often connects the machines in a single room or building Copyright © 2012 Pearson Education, Inc.
41
Wide-Area Networks A Wide-Area Network (WAN)
connects two or more LANs, often over long distances LAN LAN Copyright © 2012 Pearson Education, Inc.
42
The Internet The Internet is a WAN which spans the planet
The word Internet comes from the term internetworking It started as a United States government project, sponsored by the Advanced Research Projects Agency (ARPA) originally it was called the ARPANET The Internet grew quickly throughout the 1980s and 90s Copyright © 2012 Pearson Education, Inc.
43
TCP/IP A protocol is a set of rules that determine how things communicate with each other The software that manages Internet communication follows a suite of protocols called TCP/IP The Internet Protocol (IP) determines the format of the information as it is transferred The Transmission Control Protocol (TCP) dictates how messages are reassembled and handles lost information Copyright © 2012 Pearson Education, Inc.
44
IP and Internet Addresses
Each computer on the Internet has a unique IP address, such as: Most computers also have a unique Internet name, which also is referred to as an Internet address: hector.vt.edu kant.gestalt-llc.com The first part indicates a particular computer (hector) The rest is the domain name, indicating the organization (vt.edu) Copyright © 2012 Pearson Education, Inc.
45
Domain Names The last part of a domain name, called a top-level domain (TLD), supposedly indicates the type of organization: edu educational institution com commercial entity org non-profit organization net network-based organization Sometimes the suffix indicates the country: uk United Kingdom au Australia ca Canada se Sweden Additional TLDs have been added: biz, info, tv, name Copyright © 2012 Pearson Education, Inc.
46
Domain Names A domain name can have several parts
Unique domain names mean that multiple sites can have individual computers with the same local name When used, an Internet address is translated to an IP address by software called the Domain Name System (DNS) There is no one-to-one correspondence between the sections of an IP address and the sections of an Internet address Copyright © 2012 Pearson Education, Inc.
47
The World Wide Web Resources presented include:
The World Wide Web allows many different types of information to be accessed using a common interface A browser is a program which accesses network resources and presents them Popular browsers: Internet Explorer, Safari, Firefox Resources presented include: text, graphics, video, sound, audio, executable programs A Web document usually contains links to other Web documents, creating a hypermedia environment The term Web comes from the fact that information is not organized in a linear fashion Copyright © 2012 Pearson Education, Inc.
48
The World Wide Web Web documents are often defined using the HyperText Markup Language (HTML) Information on the Web is found using a Uniform Resource Locator (URL): ftp://java.sun.com/applets/animation.zip A URL specifies a protocol (http), a domain, and possibly specific documents Copyright © 2012 Pearson Education, Inc.
49
Outline Computer Processing Hardware Components Networks
The Java Programming Language Program Development Object-Oriented Programming Copyright © 2012 Pearson Education, Inc.
50
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming language specifies the words and symbols that we can use to write a program A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements Copyright © 2012 Pearson Education, Inc.
51
Java Program Structure
In the Java programming language: A program is made up of one or more classes A class contains one or more methods A method contains program statements These terms will be explored in detail throughout the course A Java application always contains a method called main See Lincoln.java Copyright © 2012 Pearson Education, Inc.
52
//********************************************************************
// Lincoln.java Author: Lewis/Loftus // // Demonstrates the basic structure of a Java application. public class Lincoln { // // Prints a presidential quote. public static void main (String[] args) System.out.println ("A quote by Abraham Lincoln:"); System.out.println ("Whatever you are, be a good one."); } Copyright © 2012 Pearson Education, Inc.
53
Output A quote by Abraham Lincoln: Whatever you are, be a good one.
//******************************************************************** // Lincoln.java Author: Lewis/Loftus // // Demonstrates the basic structure of a Java application. public class Lincoln { // // Prints a presidential quote. public static void main (String[] args) System.out.println ("A quote by Abraham Lincoln:"); System.out.println ("Whatever you are, be a good one."); } Copyright © 2012 Pearson Education, Inc.
54
Java Program Structure
// comments about the class public class MyProgram { } class header class body Comments can be placed almost anywhere Copyright © 2012 Pearson Education, Inc.
55
Java Program Structure
// comments about the class public class MyProgram { } // comments about the method public static void main (String[] args) { } method header method body Copyright © 2012 Pearson Education, Inc.
56
Comments Comments should be included to explain the purpose of the program and describe processing steps They do not affect how a program works Java comments can take three forms: // this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */ /** this is a javadoc comment */ Copyright © 2012 Pearson Education, Inc.
57
Identifiers Identifiers are the "words" in a program
A Java identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive: Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as title case for class names - Lincoln upper case for constants - MAXIMUM Copyright © 2012 Pearson Education, Inc.
58
Identifiers Sometimes the programmer chooses the identifer(such as Lincoln) Sometimes we are using another programmer's code, so we use the identifiers that he or she chose (such as println) Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way Copyright © 2012 Pearson Education, Inc.
59
Reserved Words The Java reserved words: abstract assert boolean break
byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while Copyright © 2012 Pearson Education, Inc.
60
Quick Check Which of the following are valid Java identifiers? grade
quizGrade NetworkConnection frame2 3rdTestScore MAXIMUM MIN_CAPACITY student# Shelves1&2 Copyright © 2012 Pearson Education, Inc.
61
Quick Check Which of the following are valid Java identifiers? grade
quizGrade NetworkConnection frame2 3rdTestScore MAXIMUM MIN_CAPACITY student# Shelves1&2 Valid Invalid – cannot begin with a digit Invalid – cannot contain the '#' character Invalid – cannot contain the '&' character Copyright © 2012 Pearson Education, Inc.
62
White Space Spaces, blank lines, and tabs are called white space
White space is used to separate words and symbols in a program Extra white space is ignored A valid Java program can be formatted many ways Programs should be formatted to enhance readability, using consistent indentation See Lincoln2.java and Lincoln3.java Copyright © 2012 Pearson Education, Inc.
63
Outline Computer Processing Hardware Components Networks
The Java Programming Language Program Development Object-Oriented Programming Copyright © 2012 Pearson Education, Inc.
64
Program Development The mechanics of developing a program include several activities: writing the program in a specific programming language (such as Java) translating the program into a form that the computer can execute investigating and fixing various types of errors that can occur Software tools can be used to help with all parts of this process Copyright © 2012 Pearson Education, Inc.
65
Language Levels There are four programming language levels:
machine language assembly language high-level language fourth-generation language Each type of CPU has its own specific machine language The other levels were created to make it easier for a human being to read and write programs Copyright © 2012 Pearson Education, Inc.
66
Programming Languages
Each type of CPU executes only a particular machine language A program must be translated into machine language before it can be executed A compiler is a software tool which translates source code into a specific target language Often, that target language is the machine language for a particular CPU type The Java approach is somewhat different Copyright © 2012 Pearson Education, Inc.
67
Java Translation The Java compiler translates Java source code into a special representation called bytecode Java bytecode is not the machine language for any traditional CPU Another software tool, called an interpreter, translates bytecode into machine language and executes it Therefore the Java compiler is not tied to any particular machine Java is considered to be architecture-neutral Copyright © 2012 Pearson Education, Inc.
68
Java Translation Java source code Java bytecode Java compiler Bytecode
interpreter Bytecode compiler Machine code Copyright © 2012 Pearson Education, Inc.
69
Development Environments
There are many programs that support the development of Java software, including: Java Development Kit (JDK) Eclipse NetBeans BlueJ jGRASP Though the details of these environments differ, the basic compilation and execution process is essentially the same Copyright © 2012 Pearson Education, Inc.
70
Syntax and Semantics The syntax rules of a language define how we can put together symbols, reserved words, and identifiers to make a valid program The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do Copyright © 2012 Pearson Education, Inc.
71
Errors A program can have three types of errors
The compiler will find syntax errors and other basic problems (compile-time errors) If compile-time errors exist, an executable version of the program is not created A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors) A program may run, but produce incorrect results, perhaps using an incorrect formula (logical errors) Copyright © 2012 Pearson Education, Inc.
72
Basic Program Development
Edit and save program errors? errors? Compile program Execute program and evaluate results Copyright © 2012 Pearson Education, Inc.
73
Outline Computer Processing Hardware Components Networks
The Java Programming Language Program Development Object-Oriented Programming Copyright © 2012 Pearson Education, Inc.
74
Problem Solving The purpose of writing a program is to solve a problem
Solving a problem consists of multiple activities: Understand the problem Design a solution Consider alternatives and refine the solution Implement the solution Test the solution These activities are not purely linear – they overlap and interact Copyright © 2012 Pearson Education, Inc.
75
Problem Solving The key to designing a solution is breaking it down into manageable pieces When writing software, we design separate pieces that are responsible for certain parts of the solution An object-oriented approach lends itself to this kind of solution decomposition We will dissect our solutions into pieces called objects and classes Copyright © 2012 Pearson Education, Inc.
76
Object-Oriented Programming
Java is an object-oriented programming language As the term implies, an object is a fundamental entity in a Java program Objects can be used effectively to represent real- world entities For instance, an object might represent a particular employee in a company Each employee object handles the processing and data management related to that employee Copyright © 2012 Pearson Education, Inc.
77
Objects An object has: state - descriptive characteristics behaviors - what it can do (or what can be done to it) The state of a bank account includes its account number and its current balance The behaviors associated with a bank account include the ability to make deposits and withdrawals Note that the behavior of an object might change its state Copyright © 2012 Pearson Education, Inc.
78
Classes An object is defined by a class
A class is the blueprint of an object The class uses methods to define the behaviors of the object The class that contains the main method of a Java program represents the entire program A class represents a concept, and an object represents the embodiment of that concept Multiple objects can be created from the same class Copyright © 2012 Pearson Education, Inc.
79
Class = Blueprint One blueprint to create several similar, but different, houses: Copyright © 2012 Pearson Education, Inc.
80
Objects and Classes An object (the realization) A class (the concept)
John’s Bank Account Balance: $5,257 An object (the realization) Bank Account A class (the concept) Bill’s Bank Account Balance: $1,245,069 Mary’s Bank Account Balance: $16,833 Multiple objects from the same class Copyright © 2012 Pearson Education, Inc.
81
Inheritance One class can be used to derive another via inheritance
Classes can be organized into hierarchies Bank Account Account Charge Account Savings Account Checking Account Copyright © 2012 Pearson Education, Inc.
82
Summary Chapter 1 focused on: components of a computer
how those components interact how computers store and manipulate information computer networks the Internet and the World Wide Web programming and programming languages an introduction to Java an overview of object-oriented concepts Copyright © 2012 Pearson Education, Inc.
83
Chapter 2 Data and Expressions
Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
84
Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: character strings primitive data the declaration and use of variables expressions and operator precedence data conversions accepting input from the user Java applets introduction to graphics Copyright © 2012 Pearson Education, Inc.
85
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
86
Character Strings A string literal is represented by putting double quotes around the text Examples: "This is a string literal." "123 Main Street" "X" Every character string is an object in Java, defined by the String class Every string literal represents a String object Copyright © 2012 Pearson Education, Inc.
87
System.out.println ("Whatever you are, be a good one.");
The println Method In the Lincoln program from Chapter 1, we invoked the println method to print a character string The System.out object represents a destination (the monitor screen) to which we can send output System.out.println ("Whatever you are, be a good one."); method name object information provided to the method (parameters) Copyright © 2012 Pearson Education, Inc.
88
The print Method The System.out object provides another service as well The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line See Countdown.java Copyright © 2012 Pearson Education, Inc.
89
//********************************************************************
// Countdown.java Author: Lewis/Loftus // // Demonstrates the difference between print and println. public class Countdown { // // Prints two lines of output representing a rocket countdown. public static void main (String[] args) System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... "); System.out.println ("Liftoff!"); // appears on first output line System.out.println ("Houston, we have a problem."); } Copyright © 2012 Pearson Education, Inc.
90
Output Three... Two... One... Zero... Liftoff!
Houston, we have a problem. //******************************************************************** // Countdown.java Author: Lewis/Loftus // // Demonstrates the difference between print and println. public class Countdown { // // Prints two lines of output representing a rocket countdown. public static void main (String[] args) System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... "); System.out.println ("Liftoff!"); // appears on first output line System.out.println ("Houston, we have a problem."); } Copyright © 2012 Pearson Education, Inc.
91
"Peanut butter " + "and jelly"
String Concatenation The string concatenation operator (+) is used to append one string to the end of another "Peanut butter " + "and jelly" It can also be used to append a number to a string A string literal cannot be broken across two lines in a program See Facts.java Copyright © 2012 Pearson Education, Inc.
92
//********************************************************************
// Facts.java Author: Lewis/Loftus // // Demonstrates the use of the string concatenation operator and the // automatic conversion of an integer to a string. public class Facts { // // Prints various facts. public static void main (String[] args) // Strings can be concatenated into one long string System.out.println ("We present the following facts for your " + "extracurricular edification:"); System.out.println (); // A string can contain numeric digits System.out.println ("Letters in the Hawaiian alphabet: 12"); continue Copyright © 2012 Pearson Education, Inc.
93
// A numeric value can be concatenated to a string
continue // A numeric value can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " ); System.out.println ("Speed of ketchup: " " km per year"); } Copyright © 2012 Pearson Education, Inc.
94
Output We present the following facts for your extracurricular edification: Letters in the Hawaiian alphabet: 12 Dialing code for Antarctica: 672 Year in which Leonardo da Vinci invented the parachute: 1515 Speed of ketchup: 40 km per year continue // A numeric value can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " ); System.out.println ("Speed of ketchup: " " km per year"); } Copyright © 2012 Pearson Education, Inc.
95
String Concatenation The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, it adds them The + operator is evaluated left to right, but parentheses can be used to force the order See Addition.java Copyright © 2012 Pearson Education, Inc.
96
//********************************************************************
// Addition.java Author: Lewis/Loftus // // Demonstrates the difference between the addition and string // concatenation operators. public class Addition { // // Concatenates and adds two numbers and prints the results. public static void main (String[] args) System.out.println ("24 and 45 concatenated: " ); System.out.println ("24 and 45 added: " + ( )); } Copyright © 2012 Pearson Education, Inc.
97
Output 24 and 45 concatenated: 2445 24 and 45 added: 69
//******************************************************************** // Addition.java Author: Lewis/Loftus // // Demonstrates the difference between the addition and string // concatenation operators. public class Addition { // // Concatenates and adds two numbers and prints the results. public static void main (String[] args) System.out.println ("24 and 45 concatenated: " ); System.out.println ("24 and 45 added: " + ( )); } Copyright © 2012 Pearson Education, Inc.
98
Quick Check What output is produced by the following?
System.out.println ("X: " + 25); System.out.println ("Y: " + ( )); System.out.println ("Z: " ); Copyright © 2012 Pearson Education, Inc.
99
Quick Check What output is produced by the following?
System.out.println ("X: " + 25); System.out.println ("Y: " + ( )); System.out.println ("Z: " ); X: 25 Y: 65 Z: 30050 Copyright © 2012 Pearson Education, Inc.
100
Escape Sequences What if we wanted to print the quote character?
The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\) System.out.println ("I said \"Hello\" to you."); Copyright © 2012 Pearson Education, Inc.
101
Escape Sequences Some Java escape sequences: See Roses.java
\b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash See Roses.java Copyright © 2012 Pearson Education, Inc.
102
//********************************************************************
// Roses.java Author: Lewis/Loftus // // Demonstrates the use of escape sequences. public class Roses { // // Prints a poem (of sorts) on multiple lines. public static void main (String[] args) System.out.println ("Roses are red,\n\tViolets are blue,\n" + "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tAt this point in our " + "relationship."); } Copyright © 2012 Pearson Education, Inc.
103
Output Roses are red, Violets are blue, Sugar is sweet,
But I have "commitment issues", So I'd rather just be friends At this point in our relationship. //******************************************************************** // Roses.java Author: Lewis/Loftus // // Demonstrates the use of escape sequences. public class Roses { // // Prints a poem (of sorts) on multiple lines. public static void main (String[] args) System.out.println ("Roses are red,\n\tViolets are blue,\n" + "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tAt this point in our " + "relationship."); } Copyright © 2012 Pearson Education, Inc.
104
Quick Check Write a single println statement that produces the following output: "Thank you all for coming to my home tonight," he said mysteriously. Copyright © 2012 Pearson Education, Inc.
105
Quick Check Write a single println statement that produces the following output: "Thank you all for coming to my home tonight," he said mysteriously. System.out.println ("\"Thank you all for " + "coming to my home\ntonight,\" he said " + "mysteriously."); Copyright © 2012 Pearson Education, Inc.
106
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
107
Multiple variables can be created in one declaration
A variable is a name for a location in memory that holds a value A variable declaration specifies the variable's name and the type of information that it will hold data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration Copyright © 2012 Pearson Education, Inc.
108
Variable Initialization
A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; When a variable is referenced in a program, its current value is used See PianoKeys.java Copyright © 2012 Pearson Education, Inc.
109
//********************************************************************
// PianoKeys.java Author: Lewis/Loftus // // Demonstrates the declaration, initialization, and use of an // integer variable. public class PianoKeys { // // Prints the number of keys on a piano. public static void main (String[] args) int keys = 88; System.out.println ("A piano has " + keys + " keys."); } Copyright © 2012 Pearson Education, Inc.
110
Output A piano has 88 keys. //******************************************************************** // PianoKeys.java Author: Lewis/Loftus // // Demonstrates the declaration, initialization, and use of an // integer variable. public class PianoKeys { // // Prints the number of keys on a piano. public static void main (String[] args) int keys = 88; System.out.println ("A piano has " + keys + " keys."); } Copyright © 2012 Pearson Education, Inc.
111
Assignment An assignment statement changes the value of a variable
The assignment operator is the = sign total = 55; The value that was in total is overwritten You can only assign a value to a variable that is consistent with the variable's declared type See Geometry.java Copyright © 2012 Pearson Education, Inc.
112
//********************************************************************
// Geometry.java Author: Lewis/Loftus // // Demonstrates the use of an assignment statement to change the // value stored in a variable. public class Geometry { // // Prints the number of sides of several geometric shapes. public static void main (String[] args) int sides = 7; // declaration with initialization System.out.println ("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides."); sides = 12; System.out.println ("A dodecagon has " + sides + " sides."); } Copyright © 2012 Pearson Education, Inc.
113
Output A heptagon has 7 sides. A decagon has 10 sides.
a dodecagon has 12 sides. //******************************************************************** // Geometry.java Author: Lewis/Loftus // // Demonstrates the use of an assignment statement to change the // value stored in a variable. public class Geometry { // // Prints the number of sides of several geometric shapes. public static void main (String[] args) int sides = 7; // declaration with initialization System.out.println ("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides."); sides = 12; System.out.println ("A dodecagon has " + sides + " sides."); } Copyright © 2012 Pearson Education, Inc.
114
final int MIN_HEIGHT = 69;
Constants A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant, not variable The compiler will issue an error if you try to change the value of a constant In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; Copyright © 2012 Pearson Education, Inc.
115
Constants Constants are useful for three important reasons
First, they give meaning to otherwise unclear literal values Example: MAX_LOAD means more than the literal 250 Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be set in one place Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers Copyright © 2012 Pearson Education, Inc.
116
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
117
Primitive Data There are eight primitive data types in Java
Four of them represent integers: byte, short, int, long Two of them represent floating point numbers: float, double One of them represents characters: char And one of them represents boolean values: boolean Copyright © 2012 Pearson Education, Inc.
118
Numeric Primitive Data
The difference between the numeric primitive types is their size and the values they can store: Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018 Copyright © 2012 Pearson Education, Inc.
119
Characters A char variable stores a single character
Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; Note the difference between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters Copyright © 2012 Pearson Education, Inc.
120
Character Sets A character set is an ordered list of characters, with each character corresponding to a unique number A char variable in Java can store any character from the Unicode character set The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters It is an international character set, containing symbols and characters from many world languages Copyright © 2012 Pearson Education, Inc.
121
Characters The ASCII character set is older and smaller than Unicode, but is still quite popular The ASCII characters are a subset of the Unicode character set, including: uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, \, … carriage return, tab, ... Copyright © 2012 Pearson Education, Inc.
122
Boolean A boolean value represents a true or false condition
The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable can also be used to represent any two states, such as a light bulb being on or off Copyright © 2012 Pearson Education, Inc.
123
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
124
Expressions An expression is a combination of one or more operators and operands Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder + - * / % If either or both operands are floating point values, then the result is a floating point value Copyright © 2012 Pearson Education, Inc.
125
Division and Remainder
If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / equals 4 8 / equals 0 The remainder operator (%) returns the remainder after dividing the first operand by the second 14 % equals 2 8 % equals 8 Copyright © 2012 Pearson Education, Inc.
126
Quick Check What are the results of the following expressions? 12 / 2
12.0 / 2.0 10 / 4 10 / 4.0 4 / 10 4.0 / 10 12 % 3 10 % 3 3 % 10 Copyright © 2012 Pearson Education, Inc.
127
Quick Check What are the results of the following expressions? 12 / 2
12.0 / 2.0 10 / 4 10 / 4.0 4 / 10 4.0 / 10 12 % 3 10 % 3 3 % 10 = 6 = 6.0 = 2 = 2.5 = 0 = 0.4 = 1 Copyright © 2012 Pearson Education, Inc.
128
result = total + count / max - offset;
Operator Precedence Operators can be combined into larger expressions result = total + count / max - offset; Operators have a well-defined precedence which determines the order in which they are evaluated Multiplication, division, and remainder are evaluated before addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order Copyright © 2012 Pearson Education, Inc.
129
Quick Check In what order are the operators evaluated in the following expressions? a + b + c + d + e a + b * c - d / e a / (b + c) - d % e a / (b * (c + (d - e))) Copyright © 2012 Pearson Education, Inc.
130
Quick Check In what order are the operators evaluated in the following expressions? a + b + c + d + e a + b * c - d / e 1 4 3 2 a / (b + c) - d % e a / (b * (c + (d - e))) Copyright © 2012 Pearson Education, Inc.
131
Expression Trees The evaluation of a particular expression can be shown using an expression tree The operators lower in the tree have higher precedence for that expression a + / - d b c a + (b – c) / d Copyright © 2012 Pearson Education, Inc.
132
Assignment Revisited The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side Copyright © 2012 Pearson Education, Inc.
133
Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value) Copyright © 2012 Pearson Education, Inc.
134
Increment and Decrement
The increment (++) and decrement (--) operators use only one operand The statement count++; is functionally equivalent to count = count + 1; Copyright © 2012 Pearson Education, Inc.
135
Increment and Decrement
The increment and decrement operators can be applied in postfix form: count++ or prefix form: ++count When used as part of a larger expression, the two forms can have different effects Because of their subtleties, the increment and decrement operators should be used with care Copyright © 2012 Pearson Education, Inc.
136
Assignment Operators Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count; Copyright © 2012 Pearson Education, Inc.
137
Assignment Operators There are many assignment operators in Java, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y Copyright © 2012 Pearson Education, Inc.
138
Assignment Operators The right hand side of an assignment operator can be a complex expression The entire right-hand expression is evaluated first, then the result is combined with the original variable Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num); Copyright © 2012 Pearson Education, Inc.
139
Assignment Operators The behavior of some assignment operators depends on the types of the operands If the operands to the += operator are strings, the assignment operator performs string concatenation The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+) Copyright © 2012 Pearson Education, Inc.
140
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
141
Data Conversion Sometimes it is convenient to convert data from one type to another For example, in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation Copyright © 2012 Pearson Education, Inc.
142
Data Conversion Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) In Java, data conversions can occur in three ways: assignment conversion promotion casting Copyright © 2012 Pearson Education, Inc.
143
Data Conversion Widening Conversions Narrowing Conversions
Copyright © 2012 Pearson Education, Inc.
144
Assignment Conversion
Assignment conversion occurs when a value of one type is assigned to a variable of another Example: int dollars = 20; double money = dollars; Only widening conversions can happen via assignment Note that the value or type of dollars did not change Copyright © 2012 Pearson Education, Inc.
145
Promotion Promotion happens automatically when operators in expressions convert their operands Example: int count = 12; double sum = ; result = sum / count; The value of count is converted to a floating point value to perform the division calculation Copyright © 2012 Pearson Education, Inc.
146
Casting Casting is the most powerful, and dangerous, technique for conversion Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted int total = 50; float result = (float) total / 6; Without the cast, the fractional part of the answer would be lost Copyright © 2012 Pearson Education, Inc.
147
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
148
Interactive Programs Programs generally need input on which to operate
The Scanner class provides convenient methods for reading input values of various types A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard Keyboard input is represented by the System.in object Copyright © 2012 Pearson Education, Inc.
149
Reading Input The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner (System.in); The new operator creates the Scanner object Once created, the Scanner object can be used to invoke various input methods, such as: answer = scan.nextLine(); Copyright © 2012 Pearson Education, Inc.
150
Reading Input The Scanner class is part of the java.util class library, and must be imported into a program to be used The nextLine method reads all of the input until the end of the line is found See Echo.java The details of object creation and class libraries are discussed further in Chapter 3 Copyright © 2012 Pearson Education, Inc.
151
//********************************************************************
// Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. import java.util.Scanner; public class Echo { // // Reads a character string from the user and prints it. public static void main (String[] args) String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Copyright © 2012 Pearson Education, Inc.
152
Sample Run Enter a line of text: You want fries with that?
You entered: "You want fries with that?" //******************************************************************** // Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. import java.util.Scanner; public class Echo { // // Reads a character string from the user and prints it. public static void main (String[] args) String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Copyright © 2012 Pearson Education, Inc.
153
Input Tokens Unless specified otherwise, white space is used to separate the elements (called tokens) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types See GasMileage.java Copyright © 2012 Pearson Education, Inc.
154
//********************************************************************
// GasMileage.java Author: Lewis/Loftus // // Demonstrates the use of the Scanner class to read numeric data. import java.util.Scanner; public class GasMileage { // // Calculates fuel efficiency based on values entered by the // user. public static void main (String[] args) int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); continue Copyright © 2012 Pearson Education, Inc.
155
System.out.print ("Enter the number of miles: ");
continue System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } Copyright © 2012 Pearson Education, Inc.
156
Sample Run Enter the number of miles: 328
Enter the gallons of fuel used: 11.2 Miles Per Gallon: continue System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } Copyright © 2012 Pearson Education, Inc.
157
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
158
Introduction to Graphics
The last few sections of each chapter of the textbook focus on graphics and graphical user interfaces A picture or drawing must be digitized for storage on a computer A picture is made up of pixels (picture elements), and each pixel is stored separately The number of pixels used to represent a picture is called the picture resolution The number of pixels that can be displayed by a monitor is called the monitor resolution Copyright © 2012 Pearson Education, Inc.
159
Representing Images A digitized picture with a small portion magnified: Copyright © 2012 Pearson Education, Inc.
160
Coordinate Systems Each pixel can be identified using a two-dimensional coordinate system When referring to a pixel in a Java program, we use a coordinate system with the origin in the top-left corner 112 Y X (0, 0) 40 (112, 40) Copyright © 2012 Pearson Education, Inc.
161
Representing Color A black and white picture could be stored using one bit per pixel (0 = white and 1 = black) A colored picture requires more information; there are several techniques for representing colors Every color can be represented as a mixture of the three additive primary colors Red, Green, and Blue Each color is represented by three numbers between 0 and 255 that collectively are called an RGB value Copyright © 2012 Pearson Education, Inc.
162
The Color Class A color in a Java program is represented as an object created from the Color class The Color class also contains several predefined colors, including the following: Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0 Copyright © 2012 Pearson Education, Inc.
163
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
164
Applets A Java application is a stand-alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to be transported over the Web and executed using a web browser An applet also can be executed using the appletviewer tool of the Java SDK An applet doesn't have a main method Instead, there are several special methods that serve specific purposes Copyright © 2012 Pearson Education, Inc.
165
Applets The paint method is executed automatically whenever the applet’s contents are drawn The paint method accepts a parameter that is an object of the Graphics class A Graphics object defines a graphics context on which we can draw shapes and text The Graphics class has several methods for drawing shapes Copyright © 2012 Pearson Education, Inc.
166
Applets We create an applet by extending the JApplet class
The JApplet class is part of the javax.swing package This makes use of inheritance, which is explored in more detail in Chapter 8 See Einstein.java Copyright © 2012 Pearson Education, Inc.
167
//********************************************************************
// Einstein.java Author: Lewis/Loftus // // Demonstrates a basic applet. import javax.swing.JApplet; import java.awt.*; public class Einstein extends JApplet { // // Draws a quotation by Albert Einstein among some shapes. public void paint (Graphics page) page.drawRect (50, 50, 40, 40); // square page.drawRect (60, 80, 225, 30); // rectangle page.drawOval (75, 65, 20, 20); // circle page.drawLine (35, 60, 100, 120); // line page.drawString ("Out of clutter, find simplicity.", 110, 70); page.drawString ("-- Albert Einstein", 130, 100); } Copyright © 2012 Pearson Education, Inc.
168
//********************************************************************
// Einstein.java Author: Lewis/Loftus // // Demonstrates a basic applet. import javax.swing.JApplet; import java.awt.*; public class Einstein extends JApplet { // // Draws a quotation by Albert Einstein among some shapes. public void paint (Graphics page) page.drawRect (50, 50, 40, 40); // square page.drawRect (60, 80, 225, 30); // rectangle page.drawOval (75, 65, 20, 20); // circle page.drawLine (35, 60, 100, 120); // line page.drawString ("Out of clutter, find simplicity.", 110, 70); page.drawString ("-- Albert Einstein", 130, 100); } Copyright © 2012 Pearson Education, Inc.
169
The HTML applet Tag An applet is embedded into an HTML file using a tag that references the bytecode file of the applet The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser <html> <head> <title>The Einstein Applet</title> </head> <body> <applet code="Einstein.class" width=350 height=175> </applet> </body> </html> Copyright © 2012 Pearson Education, Inc.
170
Outline Character Strings Variables and Assignment
Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes Copyright © 2012 Pearson Education, Inc.
171
Drawing Shapes Let's explore some of the methods of the Graphics class that draw shapes in more detail A shape can be filled or unfilled, depending on which method is invoked The method parameters specify coordinates and sizes Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle An arc can be thought of as a section of an oval Copyright © 2012 Pearson Education, Inc.
172
Drawing a Line page.drawLine (10, 20, 150, 45); or
X Y 10 150 20 45 page.drawLine (10, 20, 150, 45); page.drawLine (150, 45, 10, 20); or Copyright © 2012 Pearson Education, Inc.
173
Drawing a Rectangle page.drawRect (50, 20, 100, 40); 50 X 20 40 100 Y
Copyright © 2012 Pearson Education, Inc.
174
Drawing an Oval bounding rectangle page.drawOval (175, 20, 50, 80);
X Y 175 20 80 bounding rectangle 50 page.drawOval (175, 20, 50, 80); Copyright © 2012 Pearson Education, Inc.
175
Drawing an Arc An arc is defined by an oval, a start angle, and an arc angle: Copyright © 2012 Pearson Education, Inc.
176
Drawing Shapes Every drawing surface has a background color
Every graphics context has a current foreground color Both can be set explicitly See Snowman.java Copyright © 2012 Pearson Education, Inc.
177
//********************************************************************
// Snowman.java Author: Lewis/Loftus // // Demonstrates basic drawing methods and the use of color. import javax.swing.JApplet; import java.awt.*; public class Snowman extends JApplet { // // Draws a snowman. public void paint (Graphics page) final int MID = 150; final int TOP = 50; setBackground (Color.cyan); page.setColor (Color.blue); page.fillRect (0, 175, 300, 50); // ground page.setColor (Color.yellow); page.fillOval (-40, -40, 80, 80); // sun continued Copyright © 2012 Pearson Education, Inc.
178
page.setColor (Color.white);
continued page.setColor (Color.white); page.fillOval (MID-20, TOP, 40, 40); // head page.fillOval (MID-35, TOP+35, 70, 50); // upper torso page.fillOval (MID-50, TOP+80, 100, 60); // lower torso page.setColor (Color.black); page.fillOval (MID-10, TOP+10, 5, 5); // left eye page.fillOval (MID+5, TOP+10, 5, 5); // right eye page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hat page.fillRect (MID-15, TOP-20, 30, 25); // top of hat } Copyright © 2012 Pearson Education, Inc.
179
page.setColor (Color.white);
continued page.setColor (Color.white); page.fillOval (MID-20, TOP, 40, 40); // head page.fillOval (MID-35, TOP+35, 70, 50); // upper torso page.fillOval (MID-50, TOP+80, 100, 60); // lower torso page.setColor (Color.black); page.fillOval (MID-10, TOP+10, 5, 5); // left eye page.fillOval (MID+5, TOP+10, 5, 5); // right eye page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hat page.fillRect (MID-15, TOP-20, 30, 25); // top of hat } Copyright © 2012 Pearson Education, Inc.
180
Summary Chapter 2 focused on: character strings primitive data
the declaration and use of variables expressions and operator precedence data conversions accepting input from the user Java applets introduction to graphics Copyright © 2012 Pearson Education, Inc.
181
Chapter 3 Using Classes and Objects
Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
182
Using Classes and Objects
We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: object creation and object references the String class and its methods the Java API class library the Random and Math classes formatting output enumerated types wrapper classes graphical components and containers labels and images Copyright © 2012 Pearson Education, Inc.
183
Outline Creating Objects The String Class The Random and Math Classes
Formatting Output Enumerated Types Wrapper Classes Components and Containers Images Copyright © 2012 Pearson Education, Inc.
184
Creating Objects A variable holds either a primitive value or a reference to an object A class name can be used as a type to declare an object reference variable String title; No object is created with this declaration An object reference variable holds the address of an object The object itself must be created separately Copyright © 2012 Pearson Education, Inc.
185
Creating Objects Generally, we use the new operator to create an object Creating an object is called instantiation An object is an instance of a particular class title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object Copyright © 2012 Pearson Education, Inc.
186
numChars = title.length()
Invoking Methods We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods numChars = title.length() A method may return a value, which can be used in an assignment or expression A method invocation can be thought of as asking an object to perform a service Copyright © 2012 Pearson Education, Inc.
187
References Note that a primitive variable contains the value itself, but an object variable contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically "Steve Jobs" name1 num1 38 Copyright © 2012 Pearson Education, Inc.
188
Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable For primitive types: num1 38 num2 96 Before: num2 = num1; num1 38 num2 After: Copyright © 2012 Pearson Education, Inc.
189
Reference Assignment For object references, assignment copies the address: name1 name2 Before: "Steve Jobs" "Steve Wozniak" name2 = name1; name1 name2 After: "Steve Jobs" Copyright © 2012 Pearson Education, Inc.
190
Aliases Two or more references that refer to the same object are called aliases of each other That creates an interesting situation: one object can be accessed using multiple reference variables Aliases can be useful, but should be managed carefully Changing an object through one reference changes it for all of its aliases, because there is really only one object Copyright © 2012 Pearson Education, Inc.
191
Garbage Collection When an object no longer has any valid references to it, it can no longer be accessed by the program The object is useless, and therefore is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In other languages, the programmer is responsible for performing garbage collection Copyright © 2012 Pearson Education, Inc.
192
Outline Creating Objects The String Class The Random and Math Classes
Formatting Output Enumerated Types Wrapper Classes Components and Containers Images Copyright © 2012 Pearson Education, Inc.
193
title = "Java Software Solutions";
The String Class Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; This is special syntax that works only for strings Each string literal (enclosed in double quotes) represents a String object Copyright © 2012 Pearson Education, Inc.
194
String Methods Once a String object has been created, neither its value nor its length can be changed Therefore we say that an object of the String class is immutable However, several methods of the String class return new String objects that are modified versions of the original Copyright © 2012 Pearson Education, Inc.
195
String Indexes It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The indexes begin at zero in each string In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4 See StringMutation.java Copyright © 2012 Pearson Education, Inc.
196
//********************************************************************
// StringMutation.java Author: Lewis/Loftus // // Demonstrates the use of the String class and its methods. public class StringMutation { // // Prints a string and various mutations of it. public static void main (String[] args) String phrase = "Change is inevitable"; String mutation1, mutation2, mutation3, mutation4; System.out.println ("Original string: \"" + phrase + "\""); System.out.println ("Length of string: " + phrase.length()); mutation1 = phrase.concat (", except from vending machines."); mutation2 = mutation1.toUpperCase(); mutation3 = mutation2.replace ('E', 'X'); mutation4 = mutation3.substring (3, 30); continued Copyright © 2012 Pearson Education, Inc.
197
// Print each mutated string
continued // Print each mutated string System.out.println ("Mutation #1: " + mutation1); System.out.println ("Mutation #2: " + mutation2); System.out.println ("Mutation #3: " + mutation3); System.out.println ("Mutation #4: " + mutation4); System.out.println ("Mutated length: " + mutation4.length()); } Copyright © 2012 Pearson Education, Inc.
198
Output Original string: "Change is inevitable" Length of string: 20
Mutation #1: Change is inevitable, except from vending machines. Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES. Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS. Mutation #4: NGX IS INXVITABLX, XXCXPT F Mutated length: 27 continued // Print each mutated string System.out.println ("Mutation #1: " + mutation1); System.out.println ("Mutation #2: " + mutation2); System.out.println ("Mutation #3: " + mutation3); System.out.println ("Mutation #4: " + mutation4); System.out.println ("Mutated length: " + mutation4.length()); } Copyright © 2012 Pearson Education, Inc.
199
Quick Check What output is produced by the following?
String str = "Space, the final frontier."; System.out.println (str.length()); System.out.println (str.substring(7)); System.out.println (str.toUpperCase()); Copyright © 2012 Pearson Education, Inc.
200
Quick Check What output is produced by the following?
String str = "Space, the final frontier."; System.out.println (str.length()); System.out.println (str.substring(7)); System.out.println (str.toUpperCase()); 26 the final frontier. SPACE, THE FINAL FRONTIER. Copyright © 2012 Pearson Education, Inc.
201
Outline Creating Objects The String Class The Random and Math Classes
Formatting Output Enumerated Types Wrapper Classes Components and Containers Images Copyright © 2012 Pearson Education, Inc.
202
Class Libraries A class library is a collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment Its classes are not part of the Java language per se, but we rely on them heavily Various classes we've already used (System , Scanner, String) are part of the Java standard class library Copyright © 2012 Pearson Education, Inc.
203
The Java API The Java class library is sometimes referred to as the Java API API stands for Application Programming Interface Clusters of related classes are sometimes referred to as specific APIs: The Swing API The Database API Copyright © 2012 Pearson Education, Inc.
204
The Java API Get comfortable navigating the online Java API documentation Copyright © 2012 Pearson Education, Inc.
205
Packages For purposes of accessing them, classes in the Java API are organized into packages These often overlap with specific APIs Examples: Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing Copyright © 2012 Pearson Education, Inc.
206
The import Declaration
When you want to use a class from a package, you could use its fully qualified name java.util.Scanner Or you can import the class, and then use just the class name import java.util.Scanner; To import all classes in a particular package, you can use the * wildcard character import java.util.*; Copyright © 2012 Pearson Education, Inc.
207
The import Declaration
All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line: import java.lang.*; That's why we didn't have to import the System or String classes explicitly in earlier programs The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported Copyright © 2012 Pearson Education, Inc.
208
The Random Class The Random class is part of the java.util package
It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values See RandomNumbers.java Copyright © 2012 Pearson Education, Inc.
209
//********************************************************************
// RandomNumbers.java Author: Lewis/Loftus // // Demonstrates the creation of pseudo-random numbers using the // Random class. import java.util.Random; public class RandomNumbers { // // Generates random numbers in various ranges. public static void main (String[] args) Random generator = new Random(); int num1; float num2; num1 = generator.nextInt(); System.out.println ("A random integer: " + num1); num1 = generator.nextInt(10); System.out.println ("From 0 to 9: " + num1); continued Copyright © 2012 Pearson Education, Inc.
210
num1 = generator.nextInt(10) + 1;
continued num1 = generator.nextInt(10) + 1; System.out.println ("From 1 to 10: " + num1); num1 = generator.nextInt(15) + 20; System.out.println ("From 20 to 34: " + num1); num1 = generator.nextInt(20) - 10; System.out.println ("From -10 to 9: " + num1); num2 = generator.nextFloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextFloat() * 6; // 0.0 to num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); } Copyright © 2012 Pearson Education, Inc.
211
Sample Run A random integer: 672981683 From 0 to 9: 0 From 1 to 10: 3
A random float (between 0-1): From 1 to 6: 3 continued num1 = generator.nextInt(10) + 1; System.out.println ("From 1 to 10: " + num1); num1 = generator.nextInt(15) + 20; System.out.println ("From 20 to 34: " + num1); num1 = generator.nextInt(20) - 10; System.out.println ("From -10 to 9: " + num1); num2 = generator.nextFloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextFloat() * 6; // 0.0 to num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); } Copyright © 2012 Pearson Education, Inc.
212
Quick Check Given a Random object named gen, what range of values are produced by the following expressions? gen.nextInt(25) gen.nextInt(6) + 1 gen.nextInt(100) + 10 gen.nextInt(50) + 100 gen.nextInt(10) – 5 gen.nextInt(22) + 12 Copyright © 2012 Pearson Education, Inc.
213
Quick Check Given a Random object named gen, what range of values are produced by the following expressions? Range 0 to 24 1 to 6 10 to 109 100 to 149 -5 to 4 12 to 33 gen.nextInt(25) gen.nextInt(6) + 1 gen.nextInt(100) + 10 gen.nextInt(50) + 100 gen.nextInt(10) – 5 gen.nextInt(22) + 12 Copyright © 2012 Pearson Education, Inc.
214
Quick Check Write an expression that produces a random integer in the following ranges: Range 0 to 12 1 to 20 15 to 20 -10 to 0 Copyright © 2012 Pearson Education, Inc.
215
Quick Check Write an expression that produces a random integer in the following ranges: Range 0 to 12 1 to 20 15 to 20 -10 to 0 gen.nextInt(13) gen.nextInt(20) + 1 gen.nextInt(6) + 15 gen.nextInt(11) – 10 Copyright © 2012 Pearson Education, Inc.
216
The Math Class The Math class is part of the java.lang package
The Math class contains methods that perform various mathematical functions These include: absolute value square root exponentiation trigonometric functions Copyright © 2012 Pearson Education, Inc.
217
value = Math.cos(90) + Math.sqrt(delta);
The Math Class The methods of the Math class are static methods (also called class methods) Static methods are invoked through the class name – no object of the Math class is needed value = Math.cos(90) + Math.sqrt(delta); We discuss static methods further in Chapter 7 See Quadratic.java Copyright © 2012 Pearson Education, Inc.
218
//********************************************************************
// Quadratic.java Author: Lewis/Loftus // // Demonstrates the use of the Math class to perform a calculation // based on user input. import java.util.Scanner; public class Quadratic { // // Determines the roots of a quadratic equation. public static void main (String[] args) int a, b, c; // ax^2 + bx + c double discriminant, root1, root2; Scanner scan = new Scanner (System.in); System.out.print ("Enter the coefficient of x squared: "); a = scan.nextInt(); continued Copyright © 2012 Pearson Education, Inc.
219
System.out.print ("Enter the coefficient of x: "); b = scan.nextInt();
continued System.out.print ("Enter the coefficient of x: "); b = scan.nextInt(); System.out.print ("Enter the constant: "); c = scan.nextInt(); // Use the quadratic formula to compute the roots. // Assumes a positive discriminant. discriminant = Math.pow(b, 2) - (4 * a * c); root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); System.out.println ("Root #1: " + root1); System.out.println ("Root #2: " + root2); } Copyright © 2012 Pearson Education, Inc.
220
Sample Run Enter the coefficient of x squared: 3
Enter the constant: 4 Root #1: Root #2: -2.0 continued System.out.print ("Enter the coefficient of x: "); b = scan.nextInt(); System.out.print ("Enter the constant: "); c = scan.nextInt(); // Use the quadratic formula to compute the roots. // Assumes a positive discriminant. discriminant = Math.pow(b, 2) - (4 * a * c); root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); System.out.println ("Root #1: " + root1); System.out.println ("Root #2: " + root2); } Copyright © 2012 Pearson Education, Inc.
221
Outline Creating Objects The String Class The Random and Math Classes
Formatting Output Enumerated Types Wrapper Classes Components and Containers Images Copyright © 2012 Pearson Education, Inc.
222
Formatting Output It is often necessary to format output values in certain ways so that they can be presented properly The Java standard class library contains classes that provide formatting capabilities The NumberFormat class allows you to format values as currency or percentages The DecimalFormat class allows you to format values based on a pattern Both are part of the java.text package Copyright © 2012 Pearson Education, Inc.
223
Formatting Output The NumberFormat class has static methods that return a formatter object getCurrencyInstance() getPercentInstance() Each formatter object has a method called format that returns a string with the specified information in the appropriate format See Purchase.java Copyright © 2012 Pearson Education, Inc.
224
//********************************************************************
// Purchase.java Author: Lewis/Loftus // // Demonstrates the use of the NumberFormat class to format output. import java.util.Scanner; import java.text.NumberFormat; public class Purchase { // // Calculates the final price of a purchased item using values // entered by the user. public static void main (String[] args) final double TAX_RATE = 0.06; // 6% sales tax int quantity; double subtotal, tax, totalCost, unitPrice; Scanner scan = new Scanner (System.in); continued Copyright © 2012 Pearson Education, Inc.
225
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
continued NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.getPercentInstance(); System.out.print ("Enter the quantity: "); quantity = scan.nextInt(); System.out.print ("Enter the unit price: "); unitPrice = scan.nextDouble(); subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // Print output with appropriate formatting System.out.println ("Subtotal: " + fmt1.format(subtotal)); System.out.println ("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE)); System.out.println ("Total: " + fmt1.format(totalCost)); } Copyright © 2012 Pearson Education, Inc.
226
Sample Run Enter the quantity: 5 Enter the unit price: 3.87
Subtotal: $19.35 Tax: $1.16 at 6% Total: $20.51 continued NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.getPercentInstance(); System.out.print ("Enter the quantity: "); quantity = scan.nextInt(); System.out.print ("Enter the unit price: "); unitPrice = scan.nextDouble(); subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // Print output with appropriate formatting System.out.println ("Subtotal: " + fmt1.format(subtotal)); System.out.println ("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE)); System.out.println ("Total: " + fmt1.format(totalCost)); } Copyright © 2012 Pearson Education, Inc.
227
Formatting Output The DecimalFormat class can be used to format a floating point value in various ways For example, you can specify that the number should be truncated to three decimal places The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number See CircleStats.java Copyright © 2012 Pearson Education, Inc.
228
//********************************************************************
// CircleStats.java Author: Lewis/Loftus // // Demonstrates the formatting of decimal values using the // DecimalFormat class. import java.util.Scanner; import java.text.DecimalFormat; public class CircleStats { // // Calculates the area and circumference of a circle given its // radius. public static void main (String[] args) int radius; double area, circumference; Scanner scan = new Scanner (System.in); continued Copyright © 2012 Pearson Education, Inc.
229
System.out.print ("Enter the circle's radius: ");
continued System.out.print ("Enter the circle's radius: "); radius = scan.nextInt(); area = Math.PI * Math.pow(radius, 2); circumference = 2 * Math.PI * radius; // Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The circle's area: " + fmt.format(area)); System.out.println ("The circle's circumference: " + fmt.format(circumference)); } Copyright © 2012 Pearson Education, Inc.
230
Sample Run Enter the circle's radius: 5 The circle's area: 78.54
The circle's circumference: continued System.out.print ("Enter the circle's radius: "); radius = scan.nextInt(); area = Math.PI * Math.pow(radius, 2); circumference = 2 * Math.PI * radius; // Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The circle's area: " + fmt.format(area)); System.out.println ("The circle's circumference: " + fmt.format(circumference)); } Copyright © 2012 Pearson Education, Inc.
231
Outline Creating Objects The String Class The Random and Math Classes
Formatting Output Enumerated Types Wrapper Classes Components and Containers Images Copyright © 2012 Pearson Education, Inc.
232
Enumerated Types Java allows you to define an enumerated type, which can then be used to declare variables An enumerated type declaration lists all possible values for a variable of that type The values are identifiers of your own choosing The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; Any number of values can be listed Copyright © 2012 Pearson Education, Inc.
233
Enumerated Types Once a type is defined, a variable of that type can be declared: Season time; And it can be assigned a value: time = Season.fall; The values are referenced through the name of the type Enumerated types are type-safe – you cannot assign any value other than those listed Copyright © 2012 Pearson Education, Inc.
234
Ordinal Values Internally, each value of an enumerated type is stored as an integer, called its ordinal value The first value in an enumerated type has an ordinal value of zero, the second one, and so on However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value Copyright © 2012 Pearson Education, Inc.
235
Enumerated Types The declaration of an enumerated type is a special type of class, and each variable of that type is an object The ordinal method returns the ordinal value of the object The name method returns the name of the identifier corresponding to the object's value See IceCream.java Copyright © 2012 Pearson Education, Inc.
236
//********************************************************************
// IceCream.java Author: Lewis/Loftus // // Demonstrates the use of enumerated types. public class IceCream { enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee, rockyRoad, mintChocolateChip, cookieDough} // // Creates and uses variables of the Flavor type. public static void main (String[] args) Flavor cone1, cone2, cone3; cone1 = Flavor.rockyRoad; cone2 = Flavor.chocolate; System.out.println ("cone1 value: " + cone1); System.out.println ("cone1 ordinal: " + cone1.ordinal()); System.out.println ("cone1 name: " + cone1.name()); continued Copyright © 2012 Pearson Education, Inc.
237
System.out.println ("cone2 value: " + cone2);
continued System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name()); cone3 = cone1; System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); } Copyright © 2012 Pearson Education, Inc.
238
Output cone1 value: rockyRoad cone1 ordinal: 5 cone1 name: rockyRoad
cone2 value: chocolate cone2 ordinal: 1 cone2 name: chocolate cone3 value: rockyRoad cone3 ordinal: 5 cone3 name: rockyRoad continued System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name()); cone3 = cone1; System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); } Copyright © 2012 Pearson Education, Inc.
239
Outline Creating Objects The String Class The Random and Math Classes
Formatting Output Enumerated Types Wrapper Classes Components and Containers Images Copyright © 2012 Pearson Education, Inc.
240
Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive Type Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean
241
Integer age = new Integer(40);
Wrapper Classes The following declaration creates an Integer object which represents the integer 40 as an object Integer age = new Integer(40); An object of a wrapper class can be used in any situation where a primitive value will not suffice For example, some objects serve as containers of other objects Primitive values could not be stored in such containers, but wrapper objects could be Copyright © 2012 Pearson Education, Inc.
242
num = Integer.parseInt(str);
Wrapper Classes Wrapper classes also contain static methods that help manage the associated type For example, the Integer class contains a method to convert an integer stored in a String to an int value: num = Integer.parseInt(str); They often contain useful constants as well For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values Copyright © 2012 Pearson Education, Inc.
243
Autoboxing Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: Integer obj; int num = 42; obj = num; The assignment creates the appropriate Integer object The reverse conversion (called unboxing) also occurs automatically as needed Copyright © 2012 Pearson Education, Inc.
244
Quick Check Are the following assignments valid? Explain.
Double value = 15.75; Character ch = new Character('T'); char myChar = ch; Copyright © 2012 Pearson Education, Inc.
245
Quick Check Are the following assignments valid? Explain.
Double value = 15.75; Character ch = new Character('T'); char myChar = ch; Yes. The double literal is autoboxed into a Double object. Yes, the char in the object is unboxed before the assignment. Copyright © 2012 Pearson Education, Inc.
246
Outline Creating Objects The String Class The Random and Math Classes
Formatting Output Enumerated Types Wrapper Classes Components and Containers Images Copyright © 2012 Pearson Education, Inc.
247
Graphical Applications
Except for the applets seen in Chapter 2, the example programs we've explored thus far have been text-based They are called command-line applications, which interact with the user using simple text prompts Let's examine some Java applications that have graphical components These components will serve as a foundation to programs that have true graphical user interfaces (GUIs) Copyright © 2012 Pearson Education, Inc.
248
GUI Components A GUI component is an object that represents a screen element such as a button or a text field GUI-related classes are defined primarily in the java.awt and the javax.swing packages The Abstract Windowing Toolkit (AWT) was the original Java GUI package The Swing package provides additional and more versatile components Both packages are needed to create a Java GUI- based program Copyright © 2012 Pearson Education, Inc.
249
GUI Containers A GUI container is a component that is used to hold and organize other components A frame is a container displayed as a separate window with a title bar It can be repositioned and resized on the screen as needed A panel is a container that cannot be displayed on its own but is used to organize other components A panel must be added to another container (like a frame or another panel) to be displayed Copyright © 2012 Pearson Education, Inc.
250
GUI Containers A GUI container can be classified as either heavyweight or lightweight A heavyweight container is one that is managed by the underlying operating system A lightweight container is managed by the Java program itself Occasionally this distinction is important A frame is a heavyweight container and a panel is a lightweight container Copyright © 2012 Pearson Education, Inc.
251
Labels A label is a GUI component that displays a line of text and/or an image Labels are usually used to display information or identify other components in the interface Let's look at a program that organizes two labels in a panel and displays that panel in a frame This program is not interactive, but the frame can be repositioned and resized See Authority.java Copyright © 2012 Pearson Education, Inc.
252
//********************************************************************
// Authority.java Author: Lewis/Loftus // // Demonstrates the use of frames, panels, and labels. import java.awt.*; import javax.swing.*; public class Authority { // // Displays some words of wisdom. public static void main (String[] args) JFrame frame = new JFrame ("Authority"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JPanel primary = new JPanel(); primary.setBackground (Color.yellow); primary.setPreferredSize (new Dimension(250, 75)); continued Copyright © 2012 Pearson Education, Inc.
253
JLabel label1 = new JLabel ("Question authority,");
continued JLabel label1 = new JLabel ("Question authority,"); JLabel label2 = new JLabel ("but raise your hand first."); primary.add (label1); primary.add (label2); frame.getContentPane().add(primary); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
254
JLabel label1 = new JLabel ("Question authority,");
continued JLabel label1 = new JLabel ("Question authority,"); JLabel label2 = new JLabel ("but raise your hand first."); primary.add (label1); primary.add (label2); frame.getContentPane().add(primary); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
255
Nested Panels Containers that contain other components make up the containment hierarchy of an interface This hierarchy can be as intricate as needed to create the visual effect desired The following example nests two panels inside a third panel – note the effect this has as the frame is resized See NestedPanels.java Copyright © 2012 Pearson Education, Inc.
256
//********************************************************************
// NestedPanels.java Author: Lewis/Loftus // // Demonstrates a basic componenet hierarchy. import java.awt.*; import javax.swing.*; public class NestedPanels { // // Presents two colored panels nested within a third. public static void main (String[] args) JFrame frame = new JFrame ("Nested Panels"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // Set up first subpanel JPanel subPanel1 = new JPanel(); subPanel1.setPreferredSize (new Dimension(150, 100)); subPanel1.setBackground (Color.green); JLabel label1 = new JLabel ("One"); subPanel1.add (label1); continued Copyright © 2012 Pearson Education, Inc.
257
// Set up second subpanel JPanel subPanel2 = new JPanel();
continued // Set up second subpanel JPanel subPanel2 = new JPanel(); subPanel2.setPreferredSize (new Dimension(150, 100)); subPanel2.setBackground (Color.red); JLabel label2 = new JLabel ("Two"); subPanel2.add (label2); // Set up primary panel JPanel primary = new JPanel(); primary.setBackground (Color.blue); primary.add (subPanel1); primary.add (subPanel2); frame.getContentPane().add(primary); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
258
// Set up second subpanel JPanel subPanel2 = new JPanel();
continued // Set up second subpanel JPanel subPanel2 = new JPanel(); subPanel2.setPreferredSize (new Dimension(150, 100)); subPanel2.setBackground (Color.red); JLabel label2 = new JLabel ("Two"); subPanel2.add (label2); // Set up primary panel JPanel primary = new JPanel(); primary.setBackground (Color.blue); primary.add (subPanel1); primary.add (subPanel2); frame.getContentPane().add(primary); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
259
Outline Creating Objects The String Class The Random and Math Classes
Formatting Output Enumerated Types Wrapper Classes Components and Containers Images Copyright © 2012 Pearson Education, Inc.
260
Images Images can be displayed in a Java program in various ways
As we've seen, a JLabel object can be used to display a line of text It can also be used to display an image That is, a label can be composed of text, an image, or both at the same time Copyright © 2012 Pearson Education, Inc.
261
Images The ImageIcon class is used to represent the image that is stored in a label If text is also included, the position of the text relative to the image can be set explicitly The alignment of the text and image within the label can be set as well See LabelDemo.java Copyright © 2012 Pearson Education, Inc.
262
//********************************************************************
// LabelDemo.java Author: Lewis/Loftus // // Demonstrates the use of image icons in labels. import java.awt.*; import javax.swing.*; public class LabelDemo { // // Creates and displays the primary application frame. public static void main (String[] args) JFrame frame = new JFrame ("Label Demo"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); ImageIcon icon = new ImageIcon ("devil.gif"); JLabel label1, label2, label3; label1 = new JLabel ("Devil Left", icon, SwingConstants.CENTER); continued Copyright © 2012 Pearson Education, Inc.
263
label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);
continued label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER); label2.setHorizontalTextPosition (SwingConstants.LEFT); label2.setVerticalTextPosition (SwingConstants.BOTTOM); label3 = new JLabel ("Devil Above", icon, SwingConstants.CENTER); label3.setHorizontalTextPosition (SwingConstants.CENTER); label3.setVerticalTextPosition (SwingConstants.BOTTOM); JPanel panel = new JPanel(); panel.setBackground (Color.cyan); panel.setPreferredSize (new Dimension (200, 250)); panel.add (label1); panel.add (label2); panel.add (label3); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
264
label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);
continued label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER); label2.setHorizontalTextPosition (SwingConstants.LEFT); label2.setVerticalTextPosition (SwingConstants.BOTTOM); label3 = new JLabel ("Devil Above", icon, SwingConstants.CENTER); label3.setHorizontalTextPosition (SwingConstants.CENTER); label3.setVerticalTextPosition (SwingConstants.BOTTOM); JPanel panel = new JPanel(); panel.setBackground (Color.cyan); panel.setPreferredSize (new Dimension (200, 250)); panel.add (label1); panel.add (label2); panel.add (label3); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
265
Summary Chapter 3 focused on: object creation and object references
the String class and its methods the Java standard class library the Random and Math classes formatting output enumerated types wrapper classes graphical components and containers labels and images Copyright © 2012 Pearson Education, Inc.
266
Chapter 4 Writing Classes
Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
267
Writing Classes We've been using predefined classes from the Java API. Now we will learn to write our own classes. Chapter 4 focuses on: class definitions instance data encapsulation and Java modifiers method declaration and parameter passing constructors graphical objects events and listeners buttons and text fields Copyright © 2012 Pearson Education, Inc.
268
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson Education, Inc.
269
Writing Classes The programs we’ve written in previous examples have used classes defined in the Java standard class library Now we will begin to design programs that rely on classes that we write ourselves The class that contains the main method is just the starting point of a program True object-oriented programming is based on defining classes that represent objects with well- defined characteristics and functionality Copyright © 2012 Pearson Education, Inc.
270
Examples of Classes Copyright © 2012 Pearson Education, Inc.
271
Classes and Objects Recall from our overview of objects in Chapter 1 that an object has state and behavior Consider a six-sided die (singular of dice) It’s state can be defined as which face is showing It’s primary behavior is that it can be rolled We represent a die by designing a class called Die that models this state and behavior The class serves as the blueprint for a die object We can then instantiate as many die objects as we need for any particular program Copyright © 2012 Pearson Education, Inc.
272
Classes A class can contain data declarations and method declarations
int size, weight; char category; Data declarations Method declarations Copyright © 2012 Pearson Education, Inc.
273
Classes The values of the data define the state of an object created from the class The functionality of the methods define the behaviors of the object For our Die class, we might declare an integer called faceValue that represents the current value showing on the face One of the methods would “roll” the die by setting faceValue to a random number between one and six Copyright © 2012 Pearson Education, Inc.
274
Classes We’ll want to design the Die class so that it is a versatile and reusable resource Any given program will probably not use all operations of a given class See RollingDice.java See Die.java Copyright © 2012 Pearson Education, Inc.
275
//********************************************************************
// RollingDice.java Author: Lewis/Loftus // // Demonstrates the creation and use of a user-defined class. public class RollingDice { // // Creates two Die objects and rolls them several times. public static void main (String[] args) Die die1, die2; int sum; die1 = new Die(); die2 = new Die(); die1.roll(); die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); continue Copyright © 2012 Pearson Education, Inc.
276
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
continue die1.roll(); die2.setFaceValue(4); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println ("Sum: " + sum); sum = die1.roll() + die2.roll(); System.out.println ("New sum: " + sum); } Copyright © 2012 Pearson Education, Inc.
277
Sample Run Die One: 5, Die Two: 2 Die One: 1, Die Two: 4 Sum: 5
New sum: 6 continue die1.roll(); die2.setFaceValue(4); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println ("Sum: " + sum); sum = die1.roll() + die2.roll(); System.out.println ("New sum: " + sum); } Copyright © 2012 Pearson Education, Inc.
278
//********************************************************************
// Die.java Author: Lewis/Loftus // // Represents one die (singular of dice) with faces showing values // between 1 and 6. public class Die { private final int MAX = 6; // maximum face value private int faceValue; // current value showing on the die // // Constructor: Sets the initial face value. public Die() faceValue = 1; } continue Copyright © 2012 Pearson Education, Inc.
279
//-----------------------------------------------------------------
continue // // Rolls the die and returns the result. public int roll() { faceValue = (int)(Math.random() * MAX) + 1; return faceValue; } // Face value mutator. public void setFaceValue (int value) faceValue = value; // Face value accessor. public int getFaceValue() Copyright © 2012 Pearson Education, Inc.
280
//-----------------------------------------------------------------
continue // // Returns a string representation of this die. public String toString() { String result = Integer.toString(faceValue); return result; } Copyright © 2012 Pearson Education, Inc.
281
The Die Class The Die class contains two data values
a constant MAX that represents the maximum face value an integer faceValue that represents the current face value The roll method uses the random method of the Math class to determine a new face value There are also methods to explicitly set and retrieve the current face value at any time Copyright © 2012 Pearson Education, Inc.
282
The toString Method It's good practice to define a toString method for a class The toString method returns a character string that represents the object in some way It is called automatically when an object is concatenated to a string or when it is passed to the println method It's also convenient for debugging problems Copyright © 2012 Pearson Education, Inc.
283
Constructors As mentioned previously, a constructor is used to set up an object when it is initially created A constructor has the same name as the class The Die constructor is used to set the initial face value of each new die object to one We examine constructors in more detail later in this chapter Copyright © 2012 Pearson Education, Inc.
284
Data Scope The scope of data is the area in a program in which that data can be referenced (used) Data declared at the class level can be referenced by all methods in that class Data declared within a method can be used only in that method Data declared within a method is called local data In the Die class, the variable result is declared inside the toString method -- it is local to that method and cannot be referenced anywhere else Copyright © 2012 Pearson Education, Inc.
285
Instance Data A variable declared at the class level (such as faceValue) is called instance data Each instance (object) has its own instance variable A class declares the type of the data, but it does not reserve memory space for it Each time a Die object is created, a new faceValue variable is created as well The objects of a class share the method definitions, but each object has its own data space That's the only way two objects can have different states Copyright © 2012 Pearson Education, Inc.
286
Instance Data We can depict the two Die objects from the RollingDice program as follows: die1 5 faceValue die2 2 Each object maintains its own faceValue variable, and thus its own state Copyright © 2012 Pearson Education, Inc.
287
UML Diagrams UML stands for the Unified Modeling Language
UML diagrams show relationships among classes and objects A UML class diagram consists of one or more classes, each with sections for the class name, attributes (data), and operations (methods) Lines between classes represent associations A dotted arrow shows that one class uses the other (calls its methods) Copyright © 2012 Pearson Education, Inc.
288
UML Class Diagrams A UML class diagram for the RollingDice program:
main (args : String[]) : void Die faceValue : int roll() : int setFaceValue (int value) : void getFaceValue() : int toString() : String
289
Quick Check What is the relationship between a class and an object?
Copyright © 2012 Pearson Education, Inc.
290
Quick Check What is the relationship between a class and an object?
A class is the definition/pattern/blueprint of an object. It defines the data that will be managed by an object but doesn't reserve memory space for it. Multiple objects can be created from a class, and each object has its own copy of the instance data. Copyright © 2012 Pearson Education, Inc.
291
Quick Check Where is instance data declared?
What is the scope of instance data? What is local data? Copyright © 2012 Pearson Education, Inc.
292
Quick Check Where is instance data declared?
What is the scope of instance data? What is local data? At the class level. It can be referenced in any method of the class. Local data is declared within a method, and is only accessible in that method. Copyright © 2012 Pearson Education, Inc.
293
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson Education, Inc.
294
Encapsulation We can take one of two views of an object:
internal - the details of the variables and methods of the class that defines it external - the services that an object provides and how the object interacts with the rest of the system From the external view, an object is an encapsulated entity, providing a set of specific services These services define the interface to the object Copyright © 2012 Pearson Education, Inc.
295
Encapsulation One object (called the client) may use another object for the services it provides The client of an object may request its services (call its methods), but it should not have to be aware of how those services are accomplished Any changes to the object's state (its variables) should be made by that object's methods We should make it difficult, if not impossible, for a client to access an object’s variables directly That is, an object should be self-governing Copyright © 2012 Pearson Education, Inc.
296
Encapsulation An encapsulated object can be thought of as a black box -- its inner workings are hidden from the client The client invokes the interface methods and they manage the instance data Methods Data Client Copyright © 2012 Pearson Education, Inc.
297
Visibility Modifiers In Java, we accomplish encapsulation through the appropriate use of visibility modifiers A modifier is a Java reserved word that specifies particular characteristics of a method or data We've used the final modifier to define constants Java has three visibility modifiers: public, protected, and private The protected modifier involves inheritance, which we will discuss later Copyright © 2012 Pearson Education, Inc.
298
Visibility Modifiers Members of a class that are declared with public visibility can be referenced anywhere Members of a class that are declared with private visibility can be referenced only within that class Members declared without a visibility modifier have default visibility and can be referenced by any class in the same package An overview of all Java modifiers is presented in Appendix E Copyright © 2012 Pearson Education, Inc.
299
Visibility Modifiers Public variables violate encapsulation because they allow the client to modify the values directly Therefore instance variables should not be declared with public visibility It is acceptable to give a constant public visibility, which allows it to be used outside of the class Public constants do not violate encapsulation because, although the client can access it, its value cannot be changed Copyright © 2012 Pearson Education, Inc.
300
Visibility Modifiers Methods that provide the object's services are declared with public visibility so that they can be invoked by clients Public methods are also called service methods A method created simply to assist a service method is called a support method Since a support method is not intended to be called by a client, it should not be declared with public visibility Copyright © 2012 Pearson Education, Inc.
301
Visibility Modifiers public private Violate encapsulation Enforce
Variables Methods Violate encapsulation Enforce encapsulation Support other methods in the class Provide services to clients Copyright © 2012 Pearson Education, Inc.
302
Accessors and Mutators
Because instance data is private, a class usually provides services to access and modify data values An accessor method returns the current value of a variable A mutator method changes the value of a variable The names of accessor and mutator methods take the form getX and setX, respectively, where X is the name of the value They are sometimes called “getters” and “setters” Copyright © 2012 Pearson Education, Inc.
303
Mutator Restrictions The use of mutators gives the class designer the ability to restrict a client’s options to modify an object’s state A mutator is often designed so that the values of variables can be set only within particular limits For example, the setFaceValue mutator of the Die class should restrict the value to the valid range (1 to MAX) We’ll see in Chapter 5 how such restrictions can be implemented Copyright © 2012 Pearson Education, Inc.
304
Quick Check Why was the faceValue variable declared as private in the Die class? Why is it ok to declare MAX as public in the Die class? Copyright © 2012 Pearson Education, Inc.
305
Quick Check Why was the faceValue variable declared as private in the Die class? Why is it ok to declare MAX as public in the Die class? By making it private, each Die object controls its own data and allows it to be modified only by the well-defined operations it provides. MAX is a constant. Its value cannot be changed. Therefore, there is no violation of encapsulation. Copyright © 2012 Pearson Education, Inc.
306
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson Education, Inc.
307
Method Declarations Let’s now examine methods in more detail
A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined Copyright © 2012 Pearson Education, Inc.
308
Method Control Flow If the called method is in the same class, only the method name is needed myMethod(); myMethod compute Copyright © 2012 Pearson Education, Inc.
309
Method Control Flow The called method is often part of another class or object obj.doIt(); main doIt helpMe helpMe(); Copyright © 2012 Pearson Education, Inc.
310
Method Header A method declaration begins with a method header
char calc (int num1, int num2, String message) method name parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter return type Copyright © 2012 Pearson Education, Inc.
311
Method Body The method header is followed by the method body
char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing The return expression must be consistent with the return type Copyright © 2012 Pearson Education, Inc.
312
The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type Copyright © 2012 Pearson Education, Inc.
313
Parameters When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header ch = obj.calc (25, count, "Hello"); char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } Copyright © 2012 Pearson Education, Inc.
314
Local Data As we’ve seen, local variables can be declared inside a method The formal parameters of a method create automatic local variables when the method is invoked When the method finishes, all local variables are destroyed (including the formal parameters) Keep in mind that instance variables, declared at the class level, exists as long as the object exists Copyright © 2012 Pearson Education, Inc.
315
Bank Account Example Let’s look at another example that demonstrates the implementation details of classes and methods We’ll represent a bank account by a class named Account It’s state can include the account number, the current balance, and the name of the owner An account’s behaviors (or services) include deposits and withdrawals, and adding interest Copyright © 2012 Pearson Education, Inc.
316
Driver Programs A driver program drives the use of other, more interesting parts of a program Driver programs are often used to test other parts of the software The Transactions class contains a main method that drives the use of the Account class, exercising its services See Transactions.java See Account.java Copyright © 2012 Pearson Education, Inc.
317
//********************************************************************
// Transactions.java Author: Lewis/Loftus // // Demonstrates the creation and use of multiple Account objects. public class Transactions { // // Creates some bank accounts and requests various services. public static void main (String[] args) Account acct1 = new Account ("Ted Murphy", 72354, ); Account acct2 = new Account ("Jane Smith", 69713, 40.00); Account acct3 = new Account ("Edward Demsey", 93757, ); acct1.deposit (25.85); double smithBalance = acct2.deposit (500.00); System.out.println ("Smith balance after deposit: " + smithBalance); continue Copyright © 2012 Pearson Education, Inc.
318
System.out.println ("Smith balance after withdrawal: " +
continue System.out.println ("Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50)); acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println (); System.out.println (acct1); System.out.println (acct2); System.out.println (acct3); } Copyright © 2012 Pearson Education, Inc.
319
Output Smith balance after deposit: 540.0
Smith balance after withdrawal: Ted Murphy $132.90 Jane Smith $111.52 Edward Demsey $785.90 continue System.out.println ("Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50)); acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println (); System.out.println (acct1); System.out.println (acct2); System.out.println (acct3); } Copyright © 2012 Pearson Education, Inc.
320
//********************************************************************
// Account.java Author: Lewis/Loftus // // Represents a bank account with basic services such as deposit // and withdraw. import java.text.NumberFormat; public class Account { private final double RATE = 0.035; // interest rate of 3.5% private long acctNumber; private double balance; private String name; // // Sets up the account by defining its owner, account number, // and initial balance. public Account (String owner, long account, double initial) name = owner; acctNumber = account; balance = initial; } continue Copyright © 2012 Pearson Education, Inc.
321
//-----------------------------------------------------------------
continue // // Deposits the specified amount into the account. Returns the // new balance. public double deposit (double amount) { balance = balance + amount; return balance; } // Withdraws the specified amount from the account and applies // the fee. Returns the new balance. public double withdraw (double amount, double fee) balance = balance - amount - fee; Copyright © 2012 Pearson Education, Inc.
322
//-----------------------------------------------------------------
continue // // Adds interest to the account and returns the new balance. public double addInterest () { balance += (balance * RATE); return balance; } // Returns the current balance of the account. public double getBalance () // Returns a one-line description of the account as a string. public String toString () NumberFormat fmt = NumberFormat.getCurrencyInstance(); return (acctNumber + "\t" + name + "\t" + fmt.format(balance)); Copyright © 2012 Pearson Education, Inc.
323
Bank Account Example acct1 acctNumber 72354 balance 102.56 name
"Ted Murphy" acct2 69713 acctNumber 40.00 balance name "Jane Smith" Copyright © 2012 Pearson Education, Inc.
324
Bank Account Example There are some improvements that can be made to the Account class Formal getters and setters could have been defined for all data The design of some methods could also be more robust, such as verifying that the amount parameter to the withdraw method is positive Copyright © 2012 Pearson Education, Inc.
325
Constructors Revisited
Note that a constructor has no return type specified in the method header, not even void A common error is to put a return type on a constructor, which makes it a “regular” method that happens to have the same name as the class The programmer does not have to define a constructor for a class Each class has a default constructor that accepts no parameters Copyright © 2012 Pearson Education, Inc.
326
Quick Check How do we express which Account object's balance is updated when a deposit is made? Copyright © 2012 Pearson Education, Inc.
327
Quick Check How do we express which Account object's balance is updated when a deposit is made? Each account is referenced by an object reference variable: Account myAcct = new Account(…); and when a method is called, you call it through a particular object: myAcct.deposit(50); Copyright © 2012 Pearson Education, Inc.
328
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson Education, Inc.
329
Graphical Objects Some objects contain information that determines how the object should be represented visually Most GUI components are graphical objects We can have some effect on how components get drawn We did this in Chapter 2 when we defined the paint method of an applet Let's look at some other examples of graphical objects Copyright © 2012 Pearson Education, Inc.
330
Smiling Face Example The SmilingFace program draws a face by defining the paintComponent method of a panel See SmilingFace.java See SmilingFacePanel.java The main method of the SmilingFace class instantiates a SmilingFacePanel and displays it The SmilingFacePanel class is derived from the JPanel class using inheritance Copyright © 2012 Pearson Education, Inc.
331
//********************************************************************
// SmilingFace.java Author: Lewis/Loftus // // Demonstrates the use of a separate panel class. import javax.swing.JFrame; public class SmilingFace { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Smiling Face"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); SmilingFacePanel panel = new SmilingFacePanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
332
//********************************************************************
// SmilingFace.java Author: Lewis/Loftus // // Demonstrates the use of a separate panel class. import javax.swing.JFrame; public class SmilingFace { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Smiling Face"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); SmilingFacePanel panel = new SmilingFacePanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
333
//********************************************************************
// SmilingFacePanel.java Author: Lewis/Loftus // // Demonstrates the use of a separate panel class. import javax.swing.JPanel; import java.awt.*; public class SmilingFacePanel extends JPanel { private final int BASEX = 120, BASEY = 60; // base point for head // // Constructor: Sets up the main characteristics of this panel. public SmilingFacePanel () setBackground (Color.blue); setPreferredSize (new Dimension(320, 200)); setFont (new Font("Arial", Font.BOLD, 16)); } continue Copyright © 2012 Pearson Education, Inc.
334
//-----------------------------------------------------------------
continue // // Draws a face. public void paintComponent (Graphics page) { super.paintComponent (page); page.setColor (Color.yellow); page.fillOval (BASEX, BASEY, 80, 80); // head page.fillOval (BASEX-5, BASEY+20, 90, 40); // ears page.setColor (Color.black); page.drawOval (BASEX+20, BASEY+30, 15, 7); // eyes page.drawOval (BASEX+45, BASEY+30, 15, 7); page.fillOval (BASEX+25, BASEY+31, 5, 5); // pupils page.fillOval (BASEX+50, BASEY+31, 5, 5); page.drawArc (BASEX+20, BASEY+25, 15, 7, 0, 180); // eyebrows page.drawArc (BASEX+45, BASEY+25, 15, 7, 0, 180); page.drawArc (BASEX+35, BASEY+40, 15, 10, 180, 180); // nose page.drawArc (BASEX+20, BASEY+50, 40, 15, 180, 180); // mouth Copyright © 2012 Pearson Education, Inc.
335
page.setColor (Color.white);
continue page.setColor (Color.white); page.drawString ("Always remember that you are unique!", BASEX-105, BASEY-15); page.drawString ("Just like everyone else.", BASEX-45, BASEY+105); } Copyright © 2012 Pearson Education, Inc.
336
Smiling Face Example Every Swing component has a paintComponent method
The paintComponent method accepts a Graphics object that represents the graphics context for the panel We define the paintComponent method to draw the face with appropriate calls to the Graphics methods Note the difference between drawing on a panel and adding other GUI components to a panel Copyright © 2012 Pearson Education, Inc.
337
Splat Example The Splat example is structured a bit differently
It draws a set of colored circles on a panel, but each circle is represented as a separate object that maintains its own graphical information The paintComponent method of the panel "asks" each circle to draw itself See Splat.java See SplatPanel.java See Circle.java Copyright © 2012 Pearson Education, Inc.
338
//********************************************************************
// Splat.java Author: Lewis/Loftus // // Demonstrates the use of graphical objects. import javax.swing.*; import java.awt.*; public class Splat { // // Presents a collection of circles. public static void main (String[] args) JFrame frame = new JFrame ("Splat"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new SplatPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
339
//********************************************************************
// Splat.java Author: Lewis/Loftus // // Demonstrates the use of graphical objects. import javax.swing.*; import java.awt.*; public class Splat { // // Presents a collection of circles. public static void main (String[] args) JFrame frame = new JFrame ("Splat"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new SplatPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
340
//********************************************************************
// SplatPanel.java Author: Lewis/Loftus // // Demonstrates the use of graphical objects. import javax.swing.*; import java.awt.*; public class SplatPanel extends JPanel { private Circle circle1, circle2, circle3, circle4, circle5; // // Constructor: Creates five Circle objects. public SplatPanel() circle1 = new Circle (30, Color.red, 70, 35); circle2 = new Circle (50, Color.green, 30, 20); circle3 = new Circle (100, Color.cyan, 60, 85); circle4 = new Circle (45, Color.yellow, 170, 30); circle5 = new Circle (60, Color.blue, 200, 60); setPreferredSize (new Dimension(300, 200)); setBackground (Color.black); } continue Copyright © 2012 Pearson Education, Inc.
341
//-----------------------------------------------------------------
continue // // Draws this panel by requesting that each circle draw itself. public void paintComponent (Graphics page) { super.paintComponent(page); circle1.draw(page); circle2.draw(page); circle3.draw(page); circle4.draw(page); circle5.draw(page); } Copyright © 2012 Pearson Education, Inc.
342
//********************************************************************
// Circle.java Author: Lewis/Loftus // // Represents a circle with a particular position, size, and color. import java.awt.*; public class Circle { private int diameter, x, y; private Color color; // // Constructor: Sets up this circle with the specified values. public Circle (int size, Color shade, int upperX, int upperY) diameter = size; color = shade; x = upperX; y = upperY; } continue Copyright © 2012 Pearson Education, Inc.
343
//-----------------------------------------------------------------
continue // // Draws this circle in the specified graphics context. public void draw (Graphics page) { page.setColor (color); page.fillOval (x, y, diameter, diameter); } // Diameter mutator. public void setDiameter (int size) diameter = size; // Color mutator. public void setColor (Color shade) color = shade; Copyright © 2012 Pearson Education, Inc.
344
//-----------------------------------------------------------------
continue // // X mutator. public void setX (int upperX) { x = upperX; } // Y mutator. public void setY (int upperY) y = upperY; // Diameter accessor. public int getDiameter () return diameter; Copyright © 2012 Pearson Education, Inc.
345
//-----------------------------------------------------------------
continue // // Color accessor. public Color getColor () { return color; } // X accessor. public int getX () return x; // Y accessor. public int getY () return y; Copyright © 2012 Pearson Education, Inc.
346
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson Education, Inc.
347
Graphical User Interfaces
A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: components, events, and listeners We've previously discussed components, which are objects that represent screen elements: labels, buttons, text fields, menus, etc. Some components are containers that hold and organize other components: frames, panels, applets, dialog boxes Copyright © 2012 Pearson Education, Inc.
348
Events An event is an object that represents some activity to which we may want to respond For example, we may want our program to perform some action when the following occurs: the mouse is moved the mouse is dragged a mouse button is clicked a graphical button is pressed a keyboard key is pressed a timer expires Copyright © 2012 Pearson Education, Inc.
349
Events and Listeners The Java API contains several classes that represent typical events Components, such as a graphical button, generate (or fire) an event when it occurs We set up a listener object to respond to an event when it occurs We can design listener objects to take whatever actions are appropriate when an event occurs Copyright © 2012 Pearson Education, Inc.
350
A corresponding listener
Events and Listeners Event Component A component object generates an event Listener A corresponding listener object is designed to respond to the event When the event occurs, the component calls the appropriate method of the listener, passing an object that describes the event Copyright © 2012 Pearson Education, Inc.
351
GUI Development To create a Java program that uses a GUI we must:
instantiate and set up the necessary components implement listener classes for any events we care about establish the relationship between listeners and the components that generate the corresponding events Let's now explore some new components and see how this all comes together Copyright © 2012 Pearson Education, Inc.
352
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson Education, Inc.
353
Buttons A push button is defined by the JButton class
It generates an action event The PushCounter example displays a push button that increments a counter each time it is pushed See PushCounter.java See PushCounterPanel.java Copyright © 2012 Pearson Education, Inc.
354
//********************************************************************
// PushCounter.java Authors: Lewis/Loftus // // Demonstrates a graphical user interface and an event listener. import javax.swing.JFrame; public class PushCounter { // // Creates the main program frame. public static void main (String[] args) JFrame frame = new JFrame ("Push Counter"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new PushCounterPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
355
//********************************************************************
// PushCounter.java Authors: Lewis/Loftus // // Demonstrates a graphical user interface and an event listener. import javax.swing.JFrame; public class PushCounter { // // Creates the main program frame. public static void main (String[] args) JFrame frame = new JFrame ("Push Counter"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new PushCounterPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
356
//********************************************************************
// PushCounterPanel.java Authors: Lewis/Loftus // // Demonstrates a graphical user interface and an event listener. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PushCounterPanel extends JPanel { private int count; private JButton push; private JLabel label; // // Constructor: Sets up the GUI. public PushCounterPanel () count = 0; push = new JButton ("Push Me!"); push.addActionListener (new ButtonListener()); continue Copyright © 2012 Pearson Education, Inc.
357
label = new JLabel ("Pushes: " + count); add (push); add (label);
continue label = new JLabel ("Pushes: " + count); add (push); add (label); setPreferredSize (new Dimension(300, 40)); setBackground (Color.cyan); } //***************************************************************** // Represents a listener for button push (action) events. private class ButtonListener implements ActionListener { // // Updates the counter and label when the button is pushed. public void actionPerformed (ActionEvent event) count++; label.setText("Pushes: " + count); Copyright © 2012 Pearson Education, Inc.
358
Push Counter Example The components of the GUI are the button, a label to display the counter, a panel to organize the components, and the main frame The PushCounterPanel class represents the panel used to display the button and label The PushCounterPanel class is derived from JPanel using inheritance The constructor of PushCounterPanel sets up the elements of the GUI and initializes the counter to zero Copyright © 2012 Pearson Education, Inc.
359
Push Counter Example The ButtonListener class is the listener for the action event generated by the button It is implemented as an inner class, which means it is defined within the body of another class That facilitates the communication between the listener and the GUI components Inner classes should only be used in situations where there is an intimate relationship between the two classes and the inner class is not needed in any other context Copyright © 2012 Pearson Education, Inc.
360
Push Counter Example Listener classes are written by implementing a listener interface The ButtonListener class implements the ActionListener interface An interface is a list of methods that the implementing class must define The only method in the ActionListener interface is the actionPerformed method The Java API contains interfaces for many types of events We discuss interfaces in more detail in Chapter 6 Copyright © 2012 Pearson Education, Inc.
361
Push Counter Example The PushCounterPanel constructor:
instantiates the ButtonListener object establishes the relationship between the button and the listener by the call to addActionListener When the user presses the button, the button component creates an ActionEvent object and calls the actionPerformed method of the listener The actionPerformed method increments the counter and resets the text of the label Copyright © 2012 Pearson Education, Inc.
362
Quick Check Which object in the Push Counter example generated the event? What did it do then? Copyright © 2012 Pearson Education, Inc.
363
Quick Check Which object in the Push Counter example generated the event? What did it do then? The button component generated the event. It called the actionPerformed method of the listener object that had been registered with it. Copyright © 2012 Pearson Education, Inc.
364
Text Fields Let's look at another GUI example that uses another type of component A text field allows the user to enter one line of input If the cursor is in the text field, the text field object generates an action event when the enter key is pressed See Fahrenheit.java See FahrenheitPanel.java Copyright © 2012 Pearson Education, Inc.
365
//********************************************************************
// Fahrenheit.java Author: Lewis/Loftus // // Demonstrates the use of text fields. import javax.swing.JFrame; public class Fahrenheit { // // Creates and displays the temperature converter GUI. public static void main (String[] args) JFrame frame = new JFrame ("Fahrenheit"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); FahrenheitPanel panel = new FahrenheitPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
366
//********************************************************************
// Fahrenheit.java Author: Lewis/Loftus // // Demonstrates the use of text fields. import javax.swing.JFrame; public class Fahrenheit { // // Creates and displays the temperature converter GUI. public static void main (String[] args) JFrame frame = new JFrame ("Fahrenheit"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); FahrenheitPanel panel = new FahrenheitPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
367
//********************************************************************
// FahrenheitPanel.java Author: Lewis/Loftus // // Demonstrates the use of text fields. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FahrenheitPanel extends JPanel { private JLabel inputLabel, outputLabel, resultLabel; private JTextField fahrenheit; // // Constructor: Sets up the main GUI components. public FahrenheitPanel() inputLabel = new JLabel ("Enter Fahrenheit temperature:"); outputLabel = new JLabel ("Temperature in Celsius: "); resultLabel = new JLabel ("---"); fahrenheit = new JTextField (5); fahrenheit.addActionListener (new TempListener()); continue Copyright © 2012 Pearson Education, Inc.
368
setPreferredSize (new Dimension(300, 75));
continue add (inputLabel); add (fahrenheit); add (outputLabel); add (resultLabel); setPreferredSize (new Dimension(300, 75)); setBackground (Color.yellow); } //***************************************************************** // Represents an action listener for the temperature input field. private class TempListener implements ActionListener { // // Performs the conversion when the enter key is pressed in // the text field. public void actionPerformed (ActionEvent event) int fahrenheitTemp, celsiusTemp; String text = fahrenheit.getText(); Copyright © 2012 Pearson Education, Inc.
369
fahrenheitTemp = Integer.parseInt (text);
continue fahrenheitTemp = Integer.parseInt (text); celsiusTemp = (fahrenheitTemp-32) * 5/9; resultLabel.setText (Integer.toString (celsiusTemp)); } Copyright © 2012 Pearson Education, Inc.
370
Fahrenheit Example Like the PushCounter example, the GUI is set up in a separate panel class The TempListener inner class defines the listener for the action event generated by the text field The FahrenheitPanel constructor instantiates the listener and adds it to the text field When the user types a temperature and presses enter, the text field generates the action event and calls the actionPerformed method of the listener Copyright © 2012 Pearson Education, Inc.
371
Summary Chapter 4 focused on: class definitions instance data
encapsulation and Java modifiers method declaration and parameter passing constructors graphical objects events and listeners buttons and text fields Copyright © 2012 Pearson Education, Inc.
372
Chapter 5 Conditionals and Loops
Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
373
Conditionals and Loops
Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions the if and if-else statements comparing data while loops iterators more drawing techniques more GUI components Copyright © 2012 Pearson Education, Inc.
374
Outline Boolean Expressions The if Statement Comparing Data
The while Statement Iterators The ArrayList Class Determining Event Sources Check Boxes and Radio Buttons Copyright © 2012 Pearson Education, Inc.
375
Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one after another Some programming statements allow us to make decisions and perform repetitions These decisions are based on boolean expressions (also called conditions) that evaluate to true or false The order of statement execution is called the flow of control Copyright © 2012 Pearson Education, Inc.
376
Conditional Statements
A conditional statement lets us choose which statement will be executed next They are sometimes called selection statements Conditional statements give us the power to make basic decisions The Java conditional statements are the: if and if-else statement switch statement We'll explore the switch statement in Chapter 6 Copyright © 2012 Pearson Education, Inc.
377
Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=) Copyright © 2012 Pearson Education, Inc.
378
Boolean Expressions An if statement with its boolean condition:
if (sum > MAX) delta = sum – MAX; First, the condition is evaluated: the value of sum is either greater than the value of MAX, or it is not If the condition is true, the assignment statement is executed; if it isn't, it is skipped See Age.java Copyright © 2012 Pearson Education, Inc.
379
//********************************************************************
// Age.java Author: Lewis/Loftus // // Demonstrates the use of an if statement. import java.util.Scanner; public class Age { // // Reads the user's age and prints comments accordingly. public static void main (String[] args) final int MINOR = 21; Scanner scan = new Scanner (System.in); System.out.print ("Enter your age: "); int age = scan.nextInt(); continue Copyright © 2012 Pearson Education, Inc.
380
System.out.println ("You entered: " + age); if (age < MINOR)
continue System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy."); System.out.println ("Age is a state of mind."); } Copyright © 2012 Pearson Education, Inc.
381
Sample Run Another Sample Run Enter your age: 47 You entered: 47
Age is a state of mind. continue System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy."); System.out.println ("Age is a state of mind."); } Another Sample Run Enter your age: 12 You entered: 12 Youth is a wonderful thing. Enjoy. Age is a state of mind. Copyright © 2012 Pearson Education, Inc.
382
Logical Operators Boolean expressions can also use the following logical operators: ! Logical NOT && Logical AND || Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) Copyright © 2012 Pearson Education, Inc.
383
Logical NOT The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table: a !a true false Copyright © 2012 Pearson Education, Inc.
384
Logical AND and Logical OR
The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a || b is true if a or b or both are true, and false otherwise Copyright © 2012 Pearson Education, Inc.
385
Logical AND and Logical OR
A truth table shows all possible true-false combinations of the terms Since && and || each have two operands, there are four possible combinations of conditions a and b a b a && b a || b true false Copyright © 2012 Pearson Education, Inc.
386
Logical Operators Expressions that use logical operators can form complex conditions if (total < MAX+5 && !found) System.out.println ("Processing…"); All logical operators have lower precedence than the relational operators The ! operator has higher precedence than && and || Copyright © 2012 Pearson Education, Inc.
387
Boolean Expressions Specific expressions can be evaluated using truth tables total < MAX found !found total < MAX && !found false true Copyright © 2012 Pearson Education, Inc.
388
Short-Circuited Operators
The processing of && and || is “short-circuited” If the left operand is sufficient to determine the result, the right operand is not evaluated if (count != 0 && total/count > MAX) System.out.println ("Testing."); This type of processing should be used carefully Copyright © 2012 Pearson Education, Inc.
389
Outline Boolean Expressions The if Statement Comparing Data
The while Statement Iterators The ArrayList Class Determining Event Sources Check Boxes and Radio Buttons Copyright © 2012 Pearson Education, Inc.
390
The if Statement Let's now look at the if statement in more detail
The if statement has the following syntax: The condition must be a boolean expression. It must evaluate to either true or false. if is a Java reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped. Copyright © 2012 Pearson Education, Inc.
391
Logic of an if statement
condition evaluated false statement true Copyright © 2012 Pearson Education, Inc.
392
Indentation The statement controlled by the if statement is indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand The compiler ignores indentation, which can lead to errors if the indentation is not correct "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding Copyright © 2012 Pearson Education, Inc.
393
Quick Check What do the following statements do?
if (total != stock + warehouse) inventoryError = true; if (found || !done) System.out.println("Ok"); Copyright © 2012 Pearson Education, Inc.
394
Quick Check What do the following statements do?
if (total != stock + warehouse) inventoryError = true; Sets the boolean variable to true if the value of total is not equal to the sum of stock and warehouse if (found || !done) System.out.println("Ok"); Prints "Ok" if found is true or done is false Copyright © 2012 Pearson Education, Inc.
395
The if-else Statement An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both See Wages.java Copyright © 2012 Pearson Education, Inc.
396
//********************************************************************
// Wages.java Author: Lewis/Loftus // // Demonstrates the use of an if-else statement. import java.text.NumberFormat; import java.util.Scanner; public class Wages { // // Reads the number of hours worked and calculates wages. public static void main (String[] args) final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours in a work week Scanner scan = new Scanner (System.in); double pay = 0.0; continue Copyright © 2012 Pearson Education, Inc.
397
System.out.print ("Enter the number of hours worked: ");
continue System.out.print ("Enter the number of hours worked: "); int hours = scan.nextInt(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println ("Gross earnings: " + fmt.format(pay)); } Copyright © 2012 Pearson Education, Inc.
398
Sample Run Enter the number of hours worked: 46
Gross earnings: $404.25 continue System.out.print ("Enter the number of hours worked: "); int hours = scan.nextInt(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println ("Gross earnings: " + fmt.format(pay)); } Copyright © 2012 Pearson Education, Inc.
399
Logic of an if-else statement
condition evaluated false statement2 statement1 true Copyright © 2012 Pearson Education, Inc.
400
The Coin Class Let's look at an example that uses a class that represents a coin that can be flipped Instance data is used to indicate which face (heads or tails) is currently showing See CoinFlip.java See Coin.java Copyright © 2012 Pearson Education, Inc.
401
//********************************************************************
// CoinFlip.java Author: Lewis/Loftus // // Demonstrates the use of an if-else statement. public class CoinFlip { // // Creates a Coin object, flips it, and prints the results. public static void main (String[] args) Coin myCoin = new Coin(); myCoin.flip(); System.out.println (myCoin); if (myCoin.isHeads()) System.out.println ("You win."); else System.out.println ("Better luck next time."); } Copyright © 2012 Pearson Education, Inc.
402
Sample Run Tails Better luck next time.
//******************************************************************** // CoinFlip.java Author: Lewis/Loftus // // Demonstrates the use of an if-else statement. public class CoinFlip { // // Creates a Coin object, flips it, and prints the results. public static void main (String[] args) Coin myCoin = new Coin(); myCoin.flip(); System.out.println (myCoin); if (myCoin.isHeads()) System.out.println ("You win."); else System.out.println ("Better luck next time."); } Copyright © 2012 Pearson Education, Inc.
403
//********************************************************************
// Coin.java Author: Lewis/Loftus // // Represents a coin with two sides that can be flipped. public class Coin { private final int HEADS = 0; private final int TAILS = 1; private int face; // // Sets up the coin by flipping it initially. public Coin () flip(); } continue Copyright © 2012 Pearson Education, Inc.
404
//-----------------------------------------------------------------
continue // // Flips the coin by randomly choosing a face value. public void flip () { face = (int) (Math.random() * 2); } // Returns true if the current face of the coin is heads. public boolean isHeads () return (face == HEADS); Copyright © 2012 Pearson Education, Inc.
405
//-----------------------------------------------------------------
continue // // Returns the current face of the coin as a string. public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; } Copyright © 2012 Pearson Education, Inc.
406
Indentation Revisited
Remember that indentation is for the human reader, and is ignored by the compiler if (depth >= UPPER_LIMIT) delta = 100; else System.out.println("Reseting Delta"); delta = 0; Despite what the indentation implies, delta will be set to 0 no matter what Copyright © 2012 Pearson Education, Inc.
407
Block Statements Several statements can be grouped together into a block statement delimited by braces A block statement can be used wherever a statement is called for in the Java syntax rules if (total > MAX) { System.out.println ("Error!!"); errorCount++; } Copyright © 2012 Pearson Education, Inc.
408
Block Statements The if clause, or the else clause, or both, could govern block statements See Guessing.java if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else System.out.println ("Total: " + total); current = total*2; Copyright © 2012 Pearson Education, Inc.
409
//********************************************************************
// Guessing.java Author: Lewis/Loftus // // Demonstrates the use of a block statement in an if-else. import java.util.*; public class Guessing { // // Plays a simple guessing game with the user. public static void main (String[] args) final int MAX = 10; int answer, guess; Scanner scan = new Scanner (System.in); Random generator = new Random(); answer = generator.nextInt(MAX) + 1; continue Copyright © 2012 Pearson Education, Inc.
410
System.out.print ("I'm thinking of a number between 1 and "
continue System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: "); guess = scan.nextInt(); if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); } Copyright © 2012 Pearson Education, Inc.
411
Sample Run I'm thinking of a number between 1 and 10. Guess what it is: 6 That is not correct, sorry. The number was 9 continue System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: "); guess = scan.nextInt(); if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); } Copyright © 2012 Pearson Education, Inc.
412
Nested if Statements The statement executed as a result of an if or else clause could be another if statement These are called nested if statements An else clause is matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs See MinOfThree.java Copyright © 2012 Pearson Education, Inc.
413
//********************************************************************
// MinOfThree.java Author: Lewis/Loftus // // Demonstrates the use of nested if statements. import java.util.Scanner; public class MinOfThree { // // Reads three integers from the user and determines the smallest // value. public static void main (String[] args) int num1, num2, num3, min = 0; Scanner scan = new Scanner (System.in); System.out.println ("Enter three integers: "); num1 = scan.nextInt(); num2 = scan.nextInt(); num3 = scan.nextInt(); continue Copyright © 2012 Pearson Education, Inc.
414
System.out.println ("Minimum value: " + min); }
continue if (num1 < num2) if (num1 < num3) min = num1; else min = num3; if (num2 < num3) min = num2; System.out.println ("Minimum value: " + min); } Copyright © 2012 Pearson Education, Inc.
415
Sample Run Enter three integers: 84 69 90 Minimum value: 69 continue
Minimum value: 69 continue if (num1 < num2) if (num1 < num3) min = num1; else min = num3; if (num2 < num3) min = num2; System.out.println ("Minimum value: " + min); } Copyright © 2012 Pearson Education, Inc.
416
Outline Boolean Expressions The if Statement Comparing Data
The while Statement Iterators The ArrayList Class Determining Event Sources Check Boxes and Radio Buttons Copyright © 2012 Pearson Education, Inc.
417
Comparing Data When comparing data using boolean expressions, it's important to understand the nuances of certain data types Let's examine some key situations: Comparing floating point values for equality Comparing characters Comparing strings (alphabetical order) Comparing object vs. comparing object references Copyright © 2012 Pearson Education, Inc.
418
Comparing Float Values
You should rarely use the equality operator (==) when comparing two floating point values (float or double) Two floating point values are equal only if their underlying binary representations match exactly Computations often result in slight differences that may be irrelevant In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal Copyright © 2012 Pearson Education, Inc.
419
Comparing Float Values
To determine the equality of two floats, use the following technique: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance could be set to any appropriate level, such as Copyright © 2012 Pearson Education, Inc.
420
Comparing Characters As we've discussed, Java character data is based on the Unicode character set Unicode establishes a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on this ordering For example, the character '+' is less than the character 'J' because it comes before it in the Unicode character set Appendix C provides an overview of Unicode Copyright © 2012 Pearson Education, Inc.
421
Comparing Characters In Unicode, the digit characters (0-9) are contiguous and in order Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order Characters Unicode Values 0 – 9 48 through 57 A – Z 65 through 90 a – z 97 through 122 Copyright © 2012 Pearson Education, Inc.
422
Comparing Strings Remember that in Java a character string is an object The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name"); Copyright © 2012 Pearson Education, Inc.
423
Comparing Strings We cannot use the relational operators to compare strings The String class contains the compareTo method for determining if one string comes before another A call to name1.compareTo(name2) returns zero if name1 and name2 are equal (contain the same characters) returns a negative value if name1 is less than name2 returns a positive value if name1 is greater than name2 Copyright © 2012 Pearson Education, Inc.
424
Comparing Strings Because comparing characters and strings is based on a character set, it is called a lexicographic ordering int result = name1.comareTo(name2); if (result < 0) System.out.println (name1 + "comes first"); else if (result == 0) System.out.println ("Same name"); System.out.println (name2 + "comes first"); Copyright © 2012 Pearson Education, Inc.
425
Lexicographic Ordering
Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically) Therefore "book" comes before "bookcase" Copyright © 2012 Pearson Education, Inc.
426
Comparing Objects The == operator can be applied to objects – it returns true if the two references are aliases of each other The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator It has been redefined in the String class to compare the characters in the two strings When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate Copyright © 2012 Pearson Education, Inc.
427
Outline Boolean Expressions The if Statement Comparing Data
The while Statement Iterators The ArrayList Class Determining Event Sources Check Boxes and Radio Buttons Copyright © 2012 Pearson Education, Inc.
428
Repetition Statements
Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: while, do, and for loops The do and for loops are discussed in Chapter 6 Copyright © 2012 Pearson Education, Inc.
429
The while Statement A while statement has the following syntax:
while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false Copyright © 2012 Pearson Education, Inc.
430
Logic of a while Loop condition evaluated false true statement
Copyright © 2012 Pearson Education, Inc.
431
The while Statement An example of a while statement:
If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times int count = 1; while (count <= 5) { System.out.println (count); count++; } Copyright © 2012 Pearson Education, Inc.
432
Sentinel Values Let's look at some examples of loop processing
A loop can be used to maintain a running sum A sentinel value is a special input value that represents the end of input See Average.java Copyright © 2012 Pearson Education, Inc.
433
//********************************************************************
// Average.java Author: Lewis/Loftus // // Demonstrates the use of a while loop, a sentinel value, and a // running sum. import java.text.DecimalFormat; import java.util.Scanner; public class Average { // // Computes the average of a set of values entered by the user. // The running sum is printed as the numbers are entered. public static void main (String[] args) int sum = 0, value, count = 0; double average; Scanner scan = new Scanner (System.in); System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); continue Copyright © 2012 Pearson Education, Inc.
434
while (value != 0) // sentinel value of 0 to terminate loop { count++;
continue while (value != 0) // sentinel value of 0 to terminate loop { count++; sum += value; System.out.println ("The sum so far is " + sum); System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); } Copyright © 2012 Pearson Education, Inc.
435
System.out.println ("No values were entered."); else {
continue System.out.println (); if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count; DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); } Copyright © 2012 Pearson Education, Inc.
436
Sample Run Enter an integer (0 to quit): 25 The sum so far is 25
The average is continue System.out.println (); if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count; DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); } Copyright © 2012 Pearson Education, Inc.
437
Input Validation A loop can also be used for input validation, making a program more robust It's generally a good idea to verify that input is valid (in whatever sense) when possible See WinPercentage.java Copyright © 2012 Pearson Education, Inc.
438
//********************************************************************
// WinPercentage.java Author: Lewis/Loftus // // Demonstrates the use of a while loop for input validation. import java.text.NumberFormat; import java.util.Scanner; public class WinPercentage { // // Computes the percentage of games won by a team. public static void main (String[] args) final int NUM_GAMES = 12; int won; double ratio; Scanner scan = new Scanner (System.in); System.out.print ("Enter the number of games won (0 to " + NUM_GAMES + "): "); won = scan.nextInt(); continue Copyright © 2012 Pearson Education, Inc.
439
while (won < 0 || won > NUM_GAMES) {
continue while (won < 0 || won > NUM_GAMES) { System.out.print ("Invalid input. Please reenter: "); won = scan.nextInt(); } ratio = (double)won / NUM_GAMES; NumberFormat fmt = NumberFormat.getPercentInstance(); System.out.println (); System.out.println ("Winning percentage: " + fmt.format(ratio)); Copyright © 2012 Pearson Education, Inc.
440
Sample Run Enter the number of games won (0 to 12): -5
Invalid input. Please reenter: 13 Invalid input. Please reenter: 7 Winning percentage: 58% continue while (won < 0 || won > NUM_GAMES) { System.out.print ("Invalid input. Please reenter: "); won = scan.nextInt(); } ratio = (double)won / NUM_GAMES; NumberFormat fmt = NumberFormat.getPercentInstance(); System.out.println (); System.out.println ("Winning percentage: " + fmt.format(ratio)); Copyright © 2012 Pearson Education, Inc.
441
Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally Copyright © 2012 Pearson Education, Inc.
442
Infinite Loops An example of an infinite loop:
This loop will continue executing until interrupted (Control-C) or until an underflow error occurs int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } Copyright © 2012 Pearson Education, Inc.
443
Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely See PalindromeTester.java Copyright © 2012 Pearson Education, Inc.
444
//********************************************************************
// PalindromeTester.java Author: Lewis/Loftus // // Demonstrates the use of nested while loops. import java.util.Scanner; public class PalindromeTester { // // Tests strings to see if they are palindromes. public static void main (String[] args) String str, another = "y"; int left, right; Scanner scan = new Scanner (System.in); while (another.equalsIgnoreCase("y")) // allows y or Y System.out.println ("Enter a potential palindrome:"); str = scan.nextLine(); left = 0; right = str.length() - 1; continue Copyright © 2012 Pearson Education, Inc.
445
while (str.charAt(left) == str.charAt(right) && left < right) {
continue while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.print ("Test another palindrome (y/n)? "); another = scan.nextLine(); Copyright © 2012 Pearson Education, Inc.
446
Sample Run Enter a potential palindrome: radar
That string IS a palindrome. Test another palindrome (y/n)? y able was I ere I saw elba abracadabra That string is NOT a palindrome. Test another palindrome (y/n)? n continue while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.print ("Test another palindrome (y/n)? "); another = scan.nextLine(); Copyright © 2012 Pearson Education, Inc.
447
Quick Check How many times will the string "Here" be printed?
count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 < 20) System.out.println ("Here"); count2++; } count1++; Copyright © 2012 Pearson Education, Inc.
448
Quick Check How many times will the string "Here" be printed?
count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 < 20) System.out.println ("Here"); count2++; } count1++; 10 * 19 = 190 Copyright © 2012 Pearson Education, Inc.
449
Outline Boolean Expressions The if Statement Comparing Data
The while Statement Iterators The ArrayList Class Determining Event Sources Check Boxes and Radio Buttons Copyright © 2012 Pearson Education, Inc.
450
Iterators An iterator is an object that allows you to process a collection of items one at a time It lets you step through each item in turn and process it as needed An iterator has a hasNext method that returns true if there is at least one more item to process The next method returns the next item Iterator objects are defined using the Iterator interface, which is discussed further in Chapter 7 Copyright © 2012 Pearson Education, Inc.
451
Iterators Several classes in the Java standard class library are iterators The Scanner class is an iterator the hasNext method returns true if there is more data to be scanned the next method returns the next scanned token as a string The Scanner class also has variations on the hasNext method for specific data types (such as hasNextInt) Copyright © 2012 Pearson Education, Inc.
452
Iterators The fact that a Scanner is an iterator is particularly helpful when reading input from a file Suppose we wanted to read and process a list of URLs stored in a file One scanner can be set up to read each line of the input until the end of the file is encountered Another scanner can be set up for each URL to process each part of the path See URLDissector.java Copyright © 2012 Pearson Education, Inc.
453
//********************************************************************
// URLDissector.java Author: Lewis/Loftus // // Demonstrates the use of Scanner to read file input and parse it // using alternative delimiters. import java.util.Scanner; import java.io.*; public class URLDissector { // // Reads urls from a file and prints their path components. public static void main (String[] args) throws IOException String url; Scanner fileScan, urlScan; fileScan = new Scanner (new File("urls.inp")); continue Copyright © 2012 Pearson Education, Inc.
454
// Read and process each line of the file while (fileScan.hasNext()) {
continue // Read and process each line of the file while (fileScan.hasNext()) { url = fileScan.nextLine(); System.out.println ("URL: " + url); urlScan = new Scanner (url); urlScan.useDelimiter("/"); // Print each part of the url while (urlScan.hasNext()) System.out.println (" " + urlScan.next()); System.out.println(); } Copyright © 2012 Pearson Education, Inc.
455
Sample Run URL: www.google.com www.google.com
URL: info gnu.html URL: thelyric.com/calendar/ thelyric.com calendar URL: undergraduate about URL: youtube.com/watch?v=EHCRimwRGLs youtube.com watch?v=EHCRimwRGLs continue // Read and process each line of the file while (fileScan.hasNext()) { url = fileScan.nextLine(); System.out.println ("URL: " + url); urlScan = new Scanner (url); urlScan.useDelimiter("/"); // Print each part of the url while (urlScan.hasNext()) System.out.println (" " + urlScan.next()); System.out.println(); } Copyright © 2012 Pearson Education, Inc.
456
Outline Boolean Expressions The if Statement Comparing Data
The while Statement Iterators The ArrayList Class Determining Event Sources Check Boxes and Radio Buttons Copyright © 2012 Pearson Education, Inc.
457
The ArrayList Class An ArrayList object stores a list of objects, and is often processed using a loop The ArrayList class is part of the java.util package You can reference each object in the list using a numeric index An ArrayList object grows and shrinks as needed, adjusting its capacity as necessary Copyright © 2012 Pearson Education, Inc.
458
The ArrayList Class Index values of an ArrayList begin at 0 (not 1):
0 "Bashful" 1 "Sleepy" 2 "Happy" 3 "Dopey" 4 "Doc" Elements can be inserted and removed The indexes of the elements adjust accordingly Copyright © 2012 Pearson Education, Inc.
459
ArrayList Methods Some ArrayList methods: boolean add (E obj)
void add (int index, E obj) Object remove (int index) Object get (int index) boolean isEmpty() int size() Copyright © 2012 Pearson Education, Inc.
460
The ArrayList Class The type of object stored in the list is established when the ArrayList object is created: ArrayList<String> names = new ArrayList<String>(); ArrayList<Book> list = new ArrayList<Book>(); This makes use of Java generics, which provide additional type checking at compile time An ArrayList object cannot store primitive types, but that's what wrapper classes are for See Beatles.java Copyright © 2012 Pearson Education, Inc.
461
//********************************************************************
// Beatles.java Author: Lewis/Loftus // // Demonstrates the use of a ArrayList object. import java.util.ArrayList; public class Beatles { // // Stores and modifies a list of band members. public static void main (String[] args) ArrayList<String> band = new ArrayList<String>(); band.add ("Paul"); band.add ("Pete"); band.add ("John"); band.add ("George"); continue Copyright © 2012 Pearson Education, Inc.
462
System.out.println (band); int location = band.indexOf ("Pete");
continue System.out.println (band); int location = band.indexOf ("Pete"); band.remove (location); System.out.println ("At index 1: " + band.get(1)); band.add (2, "Ringo"); System.out.println ("Size of the band: " + band.size()); int index = 0; while (index < band.size()) { System.out.println (band.get(index)); index++; } Copyright © 2012 Pearson Education, Inc.
463
Output [Paul, Pete, John, George] [Paul, John, George]
At index 1: John Size of the band: 4 Paul John Ringo George continue System.out.println (band); int location = band.indexOf ("Pete"); band.remove (location); System.out.println ("At index 1: " + band.get(1)); band.add (2, "Ringo"); System.out.println ("Size of the band: " + band.size()); int index = 0; while (index < band.size()) { System.out.println (band.get(index)); index++; } Copyright © 2012 Pearson Education, Inc.
464
Outline Boolean Expressions The if Statement Comparing Data
The while Statement Iterators The ArrayList Class Determining Event Sources Check Boxes and Radio Buttons Copyright © 2012 Pearson Education, Inc.
465
Determining Event Sources
Recall that interactive GUIs require establishing a relationship between components and the listeners that respond to component events One listener object can be used to listen to two different components The source of the event can be determined by using the getSource method of the event passed to the listener See LeftRight.java See LeftRightPanel.java Copyright © 2012 Pearson Education, Inc.
466
//********************************************************************
// LeftRight.java Authors: Lewis/Loftus // // Demonstrates the use of one listener for multiple buttons. import javax.swing.JFrame; public class LeftRight { // // Creates the main program frame. public static void main (String[] args) JFrame frame = new JFrame ("Left Right"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new LeftRightPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
467
//********************************************************************
// LeftRight.java Authors: Lewis/Loftus // // Demonstrates the use of one listener for multiple buttons. import javax.swing.JFrame; public class LeftRight { // // Creates the main program frame. public static void main (String[] args) JFrame frame = new JFrame ("Left Right"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new LeftRightPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
468
//********************************************************************
// LeftRightPanel.java Authors: Lewis/Loftus // // Demonstrates the use of one listener for multiple buttons. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LeftRightPanel extends JPanel { private JButton left, right; private JLabel label; private JPanel buttonPanel; continue Copyright © 2012 Pearson Education, Inc.
469
//-----------------------------------------------------------------
continue // // Constructor: Sets up the GUI. public LeftRightPanel () { left = new JButton ("Left"); right = new JButton ("Right"); ButtonListener listener = new ButtonListener(); left.addActionListener (listener); right.addActionListener (listener); label = new JLabel ("Push a button"); buttonPanel = new JPanel(); buttonPanel.setPreferredSize (new Dimension(200, 40)); buttonPanel.setBackground (Color.blue); buttonPanel.add (left); buttonPanel.add (right); setPreferredSize (new Dimension(200, 80)); setBackground (Color.cyan); add (label); add (buttonPanel); } Copyright © 2012 Pearson Education, Inc.
470
//*****************************************************************
continue //***************************************************************** // Represents a listener for both buttons. private class ButtonListener implements ActionListener { // // Determines which button was pressed and sets the label // text accordingly. public void actionPerformed (ActionEvent event) if (event.getSource() == left) label.setText("Left"); else label.setText("Right"); } Copyright © 2012 Pearson Education, Inc.
471
Outline Boolean Expressions The if Statement Comparing Data
The while Statement Iterators The ArrayList Class Determining Event Sources Check Boxes and Radio Buttons Copyright © 2012 Pearson Education, Inc.
472
Check Boxes A check box is a button that can be toggled on or off
It is represented by the JCheckBox class Unlike a push button, which generates an action event, a check box generates an item event whenever it changes state The ItemListener interface is used to define item event listeners A check box calls the itemStateChanged method of the listener when it is toggled Copyright © 2012 Pearson Education, Inc.
473
Check Boxes Let's examine a program that uses check boxes to determine the style of a label's text string It uses the Font class, which embodies a character font's: family name (such as Times or Courier) style (bold, italic, or both) font size See StyleOptions.java See StyleOptionsPanel.java Copyright © 2012 Pearson Education, Inc.
474
//********************************************************************
// StyleOptions.java Author: Lewis/Loftus // // Demonstrates the use of check boxes. import javax.swing.JFrame; public class StyleOptions { // // Creates and presents the program frame. public static void main (String[] args) JFrame frame = new JFrame ("Style Options"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); StyleOptionsPanel panel = new StyleOptionsPanel(); frame.getContentPane().add (panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
475
//********************************************************************
// StyleOptions.java Author: Lewis/Loftus // // Demonstrates the use of check boxes. import javax.swing.JFrame; public class StyleOptions { // // Creates and presents the program frame. public static void main (String[] args) JFrame frame = new JFrame ("Style Options"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); StyleOptionsPanel panel = new StyleOptionsPanel(); frame.getContentPane().add (panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
476
//********************************************************************
// StyleOptionsPanel.java Author: Lewis/Loftus // // Demonstrates the use of check boxes. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class StyleOptionsPanel extends JPanel { private JLabel saying; private JCheckBox bold, italic; continue Copyright © 2012 Pearson Education, Inc.
477
//-----------------------------------------------------------------
continue // // Sets up a panel with a label and some check boxes that // control the style of the label's font. public StyleOptionsPanel() { saying = new JLabel ("Say it with style!"); saying.setFont (new Font ("Helvetica", Font.PLAIN, 36)); bold = new JCheckBox ("Bold"); bold.setBackground (Color.cyan); italic = new JCheckBox ("Italic"); italic.setBackground (Color.cyan); StyleListener listener = new StyleListener(); bold.addItemListener (listener); italic.addItemListener (listener); add (saying); add (bold); add (italic); setBackground (Color.cyan); setPreferredSize (new Dimension(300, 100)); } Copyright © 2012 Pearson Education, Inc.
478
//*****************************************************************
continue //***************************************************************** // Represents the listener for both check boxes. private class StyleListener implements ItemListener { // // Updates the style of the label font style. public void itemStateChanged (ItemEvent event) int style = Font.PLAIN; if (bold.isSelected()) style = Font.BOLD; if (italic.isSelected()) style += Font.ITALIC; saying.setFont (new Font ("Helvetica", style, 36)); } Copyright © 2012 Pearson Education, Inc.
479
Radio Buttons A group of radio buttons represents a set of mutually exclusive options – only one can be selected at any given time When a radio button from a group is selected, the button that is currently "on" in the group is automatically toggled off To define the group of radio buttons that will work together, each radio button is added to a ButtonGroup object A radio button generates an action event Copyright © 2012 Pearson Education, Inc.
480
Radio Buttons Let's look at a program that uses radio buttons to determine which line of text to display See QuoteOptions.java See QuoteOptionsPanel.java Copyright © 2012 Pearson Education, Inc.
481
//********************************************************************
// QuoteOptions.java Author: Lewis/Loftus // // Demonstrates the use of radio buttons. import javax.swing.JFrame; public class QuoteOptions { // // Creates and presents the program frame. public static void main (String[] args) JFrame frame = new JFrame ("Quote Options"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); QuoteOptionsPanel panel = new QuoteOptionsPanel(); frame.getContentPane().add (panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
482
//********************************************************************
// QuoteOptions.java Author: Lewis/Loftus // // Demonstrates the use of radio buttons. import javax.swing.JFrame; public class QuoteOptions { // // Creates and presents the program frame. public static void main (String[] args) JFrame frame = new JFrame ("Quote Options"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); QuoteOptionsPanel panel = new QuoteOptionsPanel(); frame.getContentPane().add (panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
483
//********************************************************************
// QuoteOptionsPanel.java Author: Lewis/Loftus // // Demonstrates the use of radio buttons. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class QuoteOptionsPanel extends JPanel { private JLabel quote; private JRadioButton comedy, philosophy, carpentry; private String comedyQuote, philosophyQuote, carpentryQuote; // // Sets up a panel with a label and a set of radio buttons // that control its text. public QuoteOptionsPanel() comedyQuote = "Take my wife, please."; philosophyQuote = "I think, therefore I am."; carpentryQuote = "Measure twice. Cut once."; quote = new JLabel (comedyQuote); quote.setFont (new Font ("Helvetica", Font.BOLD, 24)); continue Copyright © 2012 Pearson Education, Inc.
484
comedy = new JRadioButton ("Comedy", true);
continue comedy = new JRadioButton ("Comedy", true); comedy.setBackground (Color.green); philosophy = new JRadioButton ("Philosophy"); philosophy.setBackground (Color.green); carpentry = new JRadioButton ("Carpentry"); carpentry.setBackground (Color.green); ButtonGroup group = new ButtonGroup(); group.add (comedy); group.add (philosophy); group.add (carpentry); QuoteListener listener = new QuoteListener(); comedy.addActionListener (listener); philosophy.addActionListener (listener); carpentry.addActionListener (listener); add (quote); add (comedy); add (philosophy); add (carpentry); setBackground (Color.green); setPreferredSize (new Dimension(300, 100)); } Copyright © 2012 Pearson Education, Inc.
485
//*****************************************************************
continue //***************************************************************** // Represents the listener for all radio buttons private class QuoteListener implements ActionListener { // // Sets the text of the label depending on which radio // button was pressed. public void actionPerformed (ActionEvent event) Object source = event.getSource(); if (source == comedy) quote.setText (comedyQuote); else if (source == philosophy) quote.setText (philosophyQuote); quote.setText (carpentryQuote); } Copyright © 2012 Pearson Education, Inc.
486
Summary Chapter 5 focused on: boolean expressions
the if and if-else statements comparing data while loops iterators more drawing techniques more GUI components Copyright © 2012 Pearson Education, Inc.
487
Chapter 6 More Conditionals and Loops
Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
488
More Conditionals and Loops
Now we can fill in some additional details regarding Java conditional and repetition statements Chapter 6 focuses on: the switch statement the conditional operator the do loop the for loop drawing with the aid of conditionals and loops dialog boxes Copyright © 2012 Pearson Education, Inc.
489
Outline The switch Statement The Conditional Operator The do Statement
The for Statement Drawing with Loops and Conditionals Dialog Boxes Copyright © 2012 Pearson Education, Inc.
490
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches Copyright © 2012 Pearson Education, Inc.
491
The switch Statement The general syntax of a switch statement is:
and case are reserved words switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } If expression matches value2, control jumps to here Copyright © 2012 Pearson Education, Inc.
492
The switch Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case Copyright © 2012 Pearson Education, Inc.
493
The switch Statement An example of a switch statement: switch (option)
{ case 'A': aCount++; break; case 'B': bCount++; case 'C': cCount++; } Copyright © 2012 Pearson Education, Inc.
494
The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch Copyright © 2012 Pearson Education, Inc.
495
The switch Statement The type of a switch expression must be integers, characters, or enumerated types As of Java 7, a switch can also be used with strings You cannot use a switch with floating point values The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement See GradeReport.java Copyright © 2012 Pearson Education, Inc.
496
//********************************************************************
// GradeReport.java Author: Lewis/Loftus // // Demonstrates the use of a switch statement. import java.util.Scanner; public class GradeReport { // // Reads a grade from the user and prints comments accordingly. public static void main (String[] args) int grade, category; Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); category = grade / 10; System.out.print ("That grade is "); continue Copyright © 2012 Pearson Education, Inc.
497
System.out.println ("a perfect score. Well done."); break; case 9:
continue switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); case 8: System.out.println ("above average. Nice job."); case 7: System.out.println ("average."); case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); default: System.out.println ("not passing."); } Copyright © 2012 Pearson Education, Inc.
498
Sample Run Enter a numeric grade (0 to 100): 91
That grade is well above average. Excellent. continue switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); case 8: System.out.println ("above average. Nice job."); case 7: System.out.println ("average."); case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); default: System.out.println ("not passing."); } Copyright © 2012 Pearson Education, Inc.
499
Outline The switch Statement The Conditional Operator The do Statement
The for Statement Drawing with Loops and Conditionals Dialog Boxes Copyright © 2012 Pearson Education, Inc.
500
The Conditional Operator
The conditional operator evaluates to one of two expressions based on a boolean condition Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression Copyright © 2012 Pearson Education, Inc.
501
The Conditional Operator
The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands Copyright © 2012 Pearson Education, Inc.
502
The Conditional Operator
Another example: If count equals 1, the "Dime" is printed If count is anything other than 1, then "Dimes" is printed System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); Copyright © 2012 Pearson Education, Inc.
503
Quick Check Express the following logic in a succinct manner using the conditional operator. if (val <= 10) System.out.println("It is not greater than 10."); else System.out.println("It is greater than 10."); Copyright © 2012 Pearson Education, Inc.
504
Quick Check Express the following logic in a succinct manner using the conditional operator. if (val <= 10) System.out.println("It is not greater than 10."); else System.out.println("It is greater than 10."); System.out.println("It is" + ((val <= 10) ? " not" : "") + " greater than 10."); Copyright © 2012 Pearson Education, Inc.
505
Outline The switch Statement The Conditional Operator The do Statement
The for Statement Drawing with Loops and Conditionals Dialog Boxes Copyright © 2012 Pearson Education, Inc.
506
The do Statement A do statement has the following syntax:
{ statement-list; } while (condition); The statement-list is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false Copyright © 2012 Pearson Education, Inc.
507
Logic of a do Loop statement true condition evaluated false
Copyright © 2012 Pearson Education, Inc.
508
The do Statement An example of a do loop:
The body of a do loop executes at least once See ReverseNumber.java int count = 0; do { count++; System.out.println (count); } while (count < 5); Copyright © 2012 Pearson Education, Inc.
509
//********************************************************************
// ReverseNumber.java Author: Lewis/Loftus // // Demonstrates the use of a do loop. import java.util.Scanner; public class ReverseNumber { // // Reverses the digits of an integer mathematically. public static void main (String[] args) int number, lastDigit, reverse = 0; Scanner scan = new Scanner (System.in); continue Copyright © 2012 Pearson Education, Inc.
510
System.out.print ("Enter a positive integer: ");
continue System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); Copyright © 2012 Pearson Education, Inc.
511
Sample Run Enter a positive integer: 2896 That number reversed is 6982
continue System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); Copyright © 2012 Pearson Education, Inc.
512
Comparing while and do The while Loop The do Loop statement condition
true false condition evaluated The while Loop true condition evaluated statement false The do Loop Copyright © 2012 Pearson Education, Inc.
513
Outline The switch Statement The Conditional Operator The do Statement
The for Statement Drawing with Loops and Conditionals Dialog Boxes Copyright © 2012 Pearson Education, Inc.
514
The for Statement A for statement has the following syntax:
The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration Copyright © 2012 Pearson Education, Inc.
515
Logic of a for loop initialization condition evaluated false statement
true increment Copyright © 2012 Pearson Education, Inc.
516
The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; } Copyright © 2012 Pearson Education, Inc.
517
The for Statement An example of a for loop:
for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times Copyright © 2012 Pearson Education, Inc.
518
The for Statement The increment section can perform any calculation:
for (int num=100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance See Multiples.java See Stars.java Copyright © 2012 Pearson Education, Inc.
519
//********************************************************************
// Multiples.java Author: Lewis/Loftus // // Demonstrates the use of a for loop. import java.util.Scanner; public class Multiples { // // Prints multiples of a user-specified number up to a user- // specified limit. public static void main (String[] args) final int PER_LINE = 5; int value, limit, mult, count = 0; Scanner scan = new Scanner (System.in); System.out.print ("Enter a positive value: "); value = scan.nextInt(); continue Copyright © 2012 Pearson Education, Inc.
520
System.out.print ("Enter an upper limit: "); limit = scan.nextInt();
continue System.out.print ("Enter an upper limit: "); limit = scan.nextInt(); System.out.println (); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:"); for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t"); // Print a specific number of values per line of output count++; if (count % PER_LINE == 0) System.out.println(); } Copyright © 2012 Pearson Education, Inc.
521
Sample Run Enter a positive value: 7 Enter an upper limit: 400
The multiples of 7 between 7 and 400 (inclusive) are: continue System.out.print ("Enter an upper limit: "); limit = scan.nextInt(); System.out.println (); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:"); for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t"); // Print a specific number of values per line of output count++; if (count % PER_LINE == 0) System.out.println(); } Copyright © 2012 Pearson Education, Inc.
522
//********************************************************************
// Stars.java Author: Lewis/Loftus // // Demonstrates the use of nested for loops. public class Stars { // // Prints a triangle shape using asterisk (star) characters. public static void main (String[] args) final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) for (int star = 1; star <= row; star++) System.out.print ("*"); System.out.println(); } Copyright © 2012 Pearson Education, Inc.
523
Output * ** *** **** ***** ****** ******* ******** *********
********** //******************************************************************** // Stars.java Author: Lewis/Loftus // // Demonstrates the use of nested for loops. public class Stars { // // Prints a triangle shape using asterisk (star) characters. public static void main (String[] args) final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) for (int star = 1; star <= row; star++) System.out.print ("*"); System.out.println(); } Copyright © 2012 Pearson Education, Inc.
524
Quick Check Write a code fragment that rolls a die 100 times and counts the number of times a 3 comes up. Copyright © 2012 Pearson Education, Inc.
525
Quick Check Write a code fragment that rolls a die 100 times and counts the number of times a 3 comes up. Die die = new Die(); int count = 0; for (int num=1; num <= 100; num++) if (die.roll() == 3) count++; Sytem.out.println (count); Copyright © 2012 Pearson Education, Inc.
526
The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed Copyright © 2012 Pearson Education, Inc.
527
For-each Loops A variant of the for loop simplifies the repetitive processing of items in an iterator For example, suppose bookList is an ArrayList<Book> object The following loop will print each book: for (Book myBook : bookList) System.out.println (myBook); This version of a for loop is often called a for-each loop Copyright © 2012 Pearson Education, Inc.
528
For-each Loops A for-each loop can be used on any object that implements the Iterable interface It eliminates the need to retrieve an iterator and call the hasNext and next methods explicitly It also will be helpful when processing arrays, which are discussed in Chapter 8 Copyright © 2012 Pearson Education, Inc.
529
Quick Check Write a for-each loop that prints all of the Student objects in an ArrayList<Student> object called roster. Copyright © 2012 Pearson Education, Inc.
530
Quick Check Write a for-each loop that prints all of the Student objects in an ArrayList<Student> object called roster. for (Student student : roster) System.out.println (student); Copyright © 2012 Pearson Education, Inc.
531
Outline The switch Statement The Conditional Operator The do Statement
The for Statement Drawing with Loops and Conditionals Dialog Boxes Copyright © 2012 Pearson Education, Inc.
532
Drawing Techniques Conditionals and loops enhance our ability to generate interesting graphics See Bullseye.java See BullseyePanel.java See Boxes.java See BoxesPanel.java Copyright © 2012 Pearson Education, Inc.
533
//********************************************************************
// Bullseye.java Author: Lewis/Loftus // // Demonstrates the use of loops to draw. import javax.swing.JFrame; public class Bullseye { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Bullseye"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); BullseyePanel panel = new BullseyePanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
534
//********************************************************************
// Bullseye.java Author: Lewis/Loftus // // Demonstrates the use of loops to draw. import javax.swing.JFrame; public class Bullseye { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Bullseye"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); BullseyePanel panel = new BullseyePanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
535
//********************************************************************
// BullseyePanel.java Author: Lewis/Loftus // // Demonstrates the use of conditionals and loops to guide drawing. import javax.swing.JPanel; import java.awt.*; public class BullseyePanel extends JPanel { private final int MAX_WIDTH = 300, NUM_RINGS = 5, RING_WIDTH = 25; // // Sets up the bullseye panel. public BullseyePanel () setBackground (Color.cyan); setPreferredSize (new Dimension(300,300)); } continue Copyright © 2012 Pearson Education, Inc.
536
//-----------------------------------------------------------------
continue // // Paints a bullseye target. public void paintComponent (Graphics page) { super.paintComponent (page); int x = 0, y = 0, diameter = MAX_WIDTH; page.setColor (Color.white); for (int count = 0; count < NUM_RINGS; count++) if (page.getColor() == Color.black) // alternate colors else page.setColor (Color.black); page.fillOval (x, y, diameter, diameter); diameter -= (2 * RING_WIDTH); x += RING_WIDTH; y += RING_WIDTH; } // Draw the red bullseye in the center page.setColor (Color.red); Copyright © 2012 Pearson Education, Inc.
537
//********************************************************************
// Boxes.java Author: Lewis/Loftus // // Demonstrates the use of loops to draw. import javax.swing.JFrame; public class Boxes { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Boxes"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); BoxesPanel panel = new BoxesPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
538
//********************************************************************
// Boxes.java Author: Lewis/Loftus // // Demonstrates the use of loops to draw. import javax.swing.JFrame; public class Boxes { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Boxes"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); BoxesPanel panel = new BoxesPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
539
//********************************************************************
// BoxesPanel.java Author: Lewis/Loftus // // Demonstrates the use of conditionals and loops to guide drawing. import javax.swing.JPanel; import java.awt.*; import java.util.Random; public class BoxesPanel extends JPanel { private final int NUM_BOXES = 50, THICKNESS = 5, MAX_SIDE = 50; private final int MAX_X = 350, MAX_Y = 250; private Random generator; // // Sets up the drawing panel. public BoxesPanel () generator = new Random(); setBackground (Color.black); setPreferredSize (new Dimension(400, 300)); } continue Copyright © 2012 Pearson Education, Inc.
540
//-----------------------------------------------------------------
continue // // Paints boxes of random width and height in a random location. // Narrow or short boxes are highlighted with a fill color. public void paintComponent(Graphics page) { super.paintComponent (page); int x, y, width, height; for (int count = 0; count < NUM_BOXES; count++) x = generator.nextInt(MAX_X) + 1; y = generator.nextInt(MAX_Y) + 1; width = generator.nextInt(MAX_SIDE) + 1; height = generator.nextInt(MAX_SIDE) + 1; Copyright © 2012 Pearson Education, Inc.
541
if (width <= THICKNESS) // check for narrow box {
continue if (width <= THICKNESS) // check for narrow box { page.setColor (Color.yellow); page.fillRect (x, y, width, height); } else if (height <= THICKNESS) // check for short box page.setColor (Color.green); page.setColor (Color.white); page.drawRect (x, y, width, height); Copyright © 2012 Pearson Education, Inc.
542
Outline The switch Statement The Conditional Operator The do Statement
The for Statement Drawing with Loops and Conditionals Dialog Boxes Copyright © 2012 Pearson Education, Inc.
543
Dialog Boxes A dialog box is a window that appears on top of any currently active window It may be used to: convey information confirm an action allow the user to enter data pick a color choose a file A dialog box usually has a specific, solitary purpose, and the user interaction with it is brief Copyright © 2012 Pearson Education, Inc.
544
Dialog Boxes The JOptionPane class provides methods that simplify the creation of some types of dialog boxes See EvenOdd.java Specialized dialog boxes for choosing colors and files are covered in Chapter 9 Copyright © 2012 Pearson Education, Inc.
545
/********************************************************************
// EvenOdd.java Author: Lewis/Loftus // // Demonstrates the use of the JOptionPane class. //******************************************************************** import javax.swing.JOptionPane; public class EvenOdd { // // Determines if the value input by the user is even or odd. // Uses multiple dialog boxes for user interaction. public static void main (String[] args) String numStr, result; int num, again; continue Copyright © 2012 Pearson Education, Inc.
546
numStr = JOptionPane.showInputDialog ("Enter an integer: ");
continue do { numStr = JOptionPane.showInputDialog ("Enter an integer: "); num = Integer.parseInt(numStr); result = "That number is " + ((num%2 == 0) ? "even" : "odd"); JOptionPane.showMessageDialog (null, result); again = JOptionPane.showConfirmDialog (null, "Do Another?"); } while (again == JOptionPane.YES_OPTION); Copyright © 2012 Pearson Education, Inc.
547
numStr = JOptionPane.showInputDialog ("Enter an integer: ");
continue do { numStr = JOptionPane.showInputDialog ("Enter an integer: "); num = Integer.parseInt(numStr); result = "That number is " + ((num%2 == 0) ? "even" : "odd"); JOptionPane.showMessageDialog (null, result); again = JOptionPane.showConfirmDialog (null, "Do Another?"); } while (again == JOptionPane.YES_OPTION); Copyright © 2012 Pearson Education, Inc.
548
Summary Chapter 6 focused on: the switch statement
the conditional operator the do loop the for loop drawing with the aid of conditionals and loops dialog boxes Copyright © 2012 Pearson Education, Inc.
549
Chapter 7 Object-Oriented Design
Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
550
Object-Oriented Design
Now we can extend our discussion of the design of classes and objects Chapter 7 focuses on: software development activities determining the classes and objects that are needed for a program the relationships that can exist among classes the static modifier writing interfaces the design of enumerated type classes method design and method overloading GUI design and layout managers Copyright © 2012 Pearson Education, Inc.
551
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
552
Program Development The creation of software involves four basic activities: establishing the requirements creating a design implementing the code testing the implementation These activities are not strictly linear – they overlap and interact Copyright © 2012 Pearson Education, Inc.
553
Requirements Software requirements specify the tasks that a program must accomplish what to do, not how to do it Often an initial set of requirements is provided, but they should be critiqued and expanded It is difficult to establish detailed, unambiguous, and complete requirements Careful attention to the requirements can save significant time and expense in the overall project Copyright © 2012 Pearson Education, Inc.
554
Design A software design specifies how a program will accomplish its requirements A software design specifies how the solution can be broken down into manageable pieces and what each piece will do An object-oriented design determines which classes and objects are needed, and specifies how they will interact Low level design details include how individual methods will accomplish their tasks Copyright © 2012 Pearson Education, Inc.
555
Implementation Implementation is the process of translating a design into source code Novice programmers often think that writing code is the heart of software development, but actually it should be the least creative step Almost all important decisions are made during requirements and design stages Implementation should focus on coding details, including style guidelines and documentation Copyright © 2012 Pearson Education, Inc.
556
Testing Testing attempts to ensure that the program will solve the intended problem under all the constraints specified in the requirements A program should be thoroughly tested with the goal of finding errors Debugging is the process of determining the cause of a problem and fixing it We revisit the details of the testing process later in this chapter Copyright © 2012 Pearson Education, Inc.
557
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
558
Identifying Classes and Objects
The core activity of object-oriented design is determining the classes and objects that will make up the solution The classes may be part of a class library, reused from a previous project, or newly written One way to identify potential classes is to identify the objects discussed in the requirements Objects are generally nouns, and the services that an object provides are generally verbs Copyright © 2012 Pearson Education, Inc.
559
Identifying Classes and Objects
A partial requirements document: Of course, not all nouns will correspond to a class or object in the final solution The user must be allowed to specify each product by its primary characteristics, including its name and product number. If the bar code does not match the product, then an error should be generated to the message window and entered into the error log. The summary report of all transactions must be structured as specified in section 7.A. Copyright © 2012 Pearson Education, Inc.
560
Identifying Classes and Objects
Remember that a class represents a group (classification) of objects with the same behaviors Generally, classes that represent objects should be given names that are singular nouns Examples: Coin, Student, Message A class represents the concept of one such object We are free to instantiate as many of each object as needed Copyright © 2012 Pearson Education, Inc.
561
Identifying Classes and Objects
Sometimes it is challenging to decide whether something should be represented as a class For example, should an employee's address be represented as a set of instance variables or as an Address object The more you examine the problem and its details the more clear these issues become When a class becomes too complex, it often should be decomposed into multiple smaller classes to distribute the responsibilities Copyright © 2012 Pearson Education, Inc.
562
Identifying Classes and Objects
We want to define classes with the proper amount of detail For example, it may be unnecessary to create separate classes for each type of appliance in a house It may be sufficient to define a more general Appliance class with appropriate instance data It all depends on the details of the problem being solved Copyright © 2012 Pearson Education, Inc.
563
Identifying Classes and Objects
Part of identifying the classes we need is the process of assigning responsibilities to each class Every activity that a program must accomplish must be represented by one or more methods in one or more classes We generally use verbs for the names of methods In early stages it is not necessary to determine every method of every class – begin with primary responsibilities and evolve the design Copyright © 2012 Pearson Education, Inc.
564
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
565
Static Class Members Recall that a static method is one that can be invoked through its class name For example, the methods of the Math class are static: result = Math.sqrt(25) Variables can be static as well Determining if a method or variable should be static is an important design decision Copyright © 2012 Pearson Education, Inc.
566
The static Modifier We declare static methods and variables using the static modifier It associates the method or variable with the class rather than with an object of that class Static methods are sometimes called class methods and static variables are sometimes called class variables Let's carefully consider the implications of each Copyright © 2012 Pearson Education, Inc.
567
Static Variables Normally, each object has its own data space, but if a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created when the class is first referenced All objects instantiated from the class share its static variables Changing the value of a static variable in one object changes it for all others Copyright © 2012 Pearson Education, Inc.
568
Static Methods public class Helper { public static int cube (int num) return num * num * num; } Because it is declared as static, the cube method can be invoked through the class name: value = Helper.cube(4); Copyright © 2012 Pearson Education, Inc.
569
Static Class Members The order of the modifiers can be interchanged, but by convention visibility modifiers come first Recall that the main method is static – it is invoked by the Java interpreter without creating an object Static methods cannot reference instance variables because instance variables don't exist until an object exists However, a static method can reference static variables or local variables Copyright © 2012 Pearson Education, Inc.
570
Static Class Members Static methods and static variables often work together The following example keeps track of how many Slogan objects have been created using a static variable, and makes that information available using a static method See SloganCounter.java See Slogan.java Copyright © 2012 Pearson Education, Inc.
571
//********************************************************************
// SloganCounter.java Author: Lewis/Loftus // // Demonstrates the use of the static modifier. public class SloganCounter { // // Creates several Slogan objects and prints the number of // objects that were created. public static void main (String[] args) Slogan obj; obj = new Slogan ("Remember the Alamo."); System.out.println (obj); obj = new Slogan ("Don't Worry. Be Happy."); continue Copyright © 2012 Pearson Education, Inc.
572
obj = new Slogan ("Live Free or Die."); System.out.println (obj);
continue obj = new Slogan ("Live Free or Die."); System.out.println (obj); obj = new Slogan ("Talk is Cheap."); obj = new Slogan ("Write Once, Run Anywhere."); System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); } Copyright © 2012 Pearson Education, Inc.
573
Output Remember the Alamo. Don't Worry. Be Happy. Live Free or Die.
Talk is Cheap. Write Once, Run Anywhere. Slogans created: 5 continue obj = new Slogan ("Live Free or Die."); System.out.println (obj); obj = new Slogan ("Talk is Cheap."); obj = new Slogan ("Write Once, Run Anywhere."); System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); } Copyright © 2012 Pearson Education, Inc.
574
//********************************************************************
// Slogan.java Author: Lewis/Loftus // // Represents a single slogan string. public class Slogan { private String phrase; private static int count = 0; // // Constructor: Sets up the slogan and counts the number of // instances created. public Slogan (String str) phrase = str; count++; } continue Copyright © 2012 Pearson Education, Inc.
575
//-----------------------------------------------------------------
continue // // Returns this slogan as a string. public String toString() { return phrase; } // Returns the number of instances of this class that have been // created. public static int getCount () return count; Copyright © 2012 Pearson Education, Inc.
576
Quick Check Why can't a static method reference an instance variable?
Copyright © 2012 Pearson Education, Inc.
577
Quick Check Why can't a static method reference an instance variable?
Because instance data is created only when an object is created. You don't need an object to execute a static method. And even if you had an object, which object's instance data would be referenced? (remember, the method is invoked through the class name) Copyright © 2012 Pearson Education, Inc.
578
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
579
Class Relationships Classes in a software system can have various types of relationships to each other Three of the most common relationships: Dependency: A uses B Aggregation: A has-a B Inheritance: A is-a B Let's discuss dependency and aggregation further Inheritance is discussed in detail in Chapter 9 Copyright © 2012 Pearson Education, Inc.
580
Dependency A dependency exists when one class relies on another in some way, usually by invoking the methods of the other We've seen dependencies in many previous examples We don't want numerous or complex dependencies among classes Nor do we want complex classes that don't depend on others A good design strikes the right balance Copyright © 2012 Pearson Education, Inc.
581
Dependency Some dependencies occur between objects of the same class
A method of the class may accept an object of the same class as a parameter For example, the concat method of the String class takes as a parameter another String object str3 = str1.concat(str2); Copyright © 2012 Pearson Education, Inc.
582
Dependency The following example defines a class called RationalNumber
A rational number is a value that can be represented as the ratio of two integers Several methods of the RationalNumber class accept another RationalNumber object as a parameter See RationalTester.java See RationalNumber.java Copyright © 2012 Pearson Education, Inc.
583
//********************************************************************
// RationalTester.java Author: Lewis/Loftus // // Driver to exercise the use of multiple Rational objects. public class RationalTester { // // Creates some rational number objects and performs various // operations on them. public static void main (String[] args) RationalNumber r1 = new RationalNumber (6, 8); RationalNumber r2 = new RationalNumber (1, 3); RationalNumber r3, r4, r5, r6, r7; System.out.println ("First rational number: " + r1); System.out.println ("Second rational number: " + r2); continue Copyright © 2012 Pearson Education, Inc.
584
System.out.println ("r1 and r2 are equal."); else
continue if (r1.isLike(r2)) System.out.println ("r1 and r2 are equal."); else System.out.println ("r1 and r2 are NOT equal."); r3 = r1.reciprocal(); System.out.println ("The reciprocal of r1 is: " + r3); r4 = r1.add(r2); r5 = r1.subtract(r2); r6 = r1.multiply(r2); r7 = r1.divide(r2); System.out.println ("r1 + r2: " + r4); System.out.println ("r1 - r2: " + r5); System.out.println ("r1 * r2: " + r6); System.out.println ("r1 / r2: " + r7); } Copyright © 2012 Pearson Education, Inc.
585
Output First rational number: 3/4 Second rational number: 1/3
r1 and r2 are NOT equal. The reciprocal of r1 is: 4/3 r1 + r2: 13/12 r1 - r2: 5/12 r1 * r2: 1/4 r1 / r2: 9/4 continue if (r1.isLike(r2)) System.out.println ("r1 and r2 are equal."); else System.out.println ("r1 and r2 are NOT equal."); r3 = r1.reciprocal(); System.out.println ("The reciprocal of r1 is: " + r3); r4 = r1.add(r2); r5 = r1.subtract(r2); r6 = r1.multiply(r2); r7 = r1.divide(r2); System.out.println ("r1 + r2: " + r4); System.out.println ("r1 - r2: " + r5); System.out.println ("r1 * r2: " + r6); System.out.println ("r1 / r2: " + r7); } Copyright © 2012 Pearson Education, Inc.
586
//********************************************************************
// RationalNumber.java Author: Lewis/Loftus // // Represents one rational number with a numerator and denominator. public class RationalNumber { private int numerator, denominator; // // Constructor: Sets up the rational number by ensuring a nonzero // denominator and making only the numerator signed. public RationalNumber (int numer, int denom) if (denom == 0) denom = 1; // Make the numerator "store" the sign if (denom < 0) numer = numer * -1; denom = denom * -1; } continue Copyright © 2012 Pearson Education, Inc.
587
//-----------------------------------------------------------------
continue numerator = numer; denominator = denom; reduce(); } // // Returns the numerator of this rational number. public int getNumerator () { return numerator; // Returns the denominator of this rational number. public int getDenominator () return denominator; Copyright © 2012 Pearson Education, Inc.
588
//-----------------------------------------------------------------
continue // // Returns the reciprocal of this rational number. public RationalNumber reciprocal () { return new RationalNumber (denominator, numerator); } // Adds this rational number to the one passed as a parameter. // A common denominator is found by multiplying the individual // denominators. public RationalNumber add (RationalNumber op2) int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int sum = numerator1 + numerator2; return new RationalNumber (sum, commonDenominator); Copyright © 2012 Pearson Education, Inc.
589
//-----------------------------------------------------------------
continue // // Subtracts the rational number passed as a parameter from this // rational number. public RationalNumber subtract (RationalNumber op2) { int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int difference = numerator1 - numerator2; return new RationalNumber (difference, commonDenominator); } // Multiplies this rational number by the one passed as a // parameter. public RationalNumber multiply (RationalNumber op2) int numer = numerator * op2.getNumerator(); int denom = denominator * op2.getDenominator(); return new RationalNumber (numer, denom); Copyright © 2012 Pearson Education, Inc.
590
//-----------------------------------------------------------------
continue // // Divides this rational number by the one passed as a parameter // by multiplying by the reciprocal of the second rational. public RationalNumber divide (RationalNumber op2) { return multiply (op2.reciprocal()); } // Determines if this rational number is equal to the one passed // as a parameter. Assumes they are both reduced. public boolean isLike (RationalNumber op2) return ( numerator == op2.getNumerator() && denominator == op2.getDenominator() ); Copyright © 2012 Pearson Education, Inc.
591
//-----------------------------------------------------------------
continue // // Returns this rational number as a string. public String toString () { String result; if (numerator == 0) result = "0"; else if (denominator == 1) result = numerator + ""; result = numerator + "/" + denominator; return result; } Copyright © 2012 Pearson Education, Inc.
592
//-----------------------------------------------------------------
continue // // Reduces this rational number by dividing both the numerator // and the denominator by their greatest common divisor. private void reduce () { if (numerator != 0) int common = gcd (Math.abs(numerator), denominator); numerator = numerator / common; denominator = denominator / common; } Copyright © 2012 Pearson Education, Inc.
593
//-----------------------------------------------------------------
continue // // Computes and returns the greatest common divisor of the two // positive parameters. Uses Euclid's algorithm. private int gcd (int num1, int num2) { while (num1 != num2) if (num1 > num2) num1 = num1 - num2; else num2 = num2 - num1; return num1; } Copyright © 2012 Pearson Education, Inc.
594
Aggregation An aggregate is an object that is made up of other objects
Therefore aggregation is a has-a relationship A car has a chassis An aggregate object contains references to other objects as instance data This is a special kind of dependency; the aggregate relies on the objects that compose it Copyright © 2012 Pearson Education, Inc.
595
Aggregation In the following example, a Student object is composed, in part, of Address objects A student has an address (in fact each student has two addresses) See StudentBody.java See Student.java See Address.java Copyright © 2012 Pearson Education, Inc.
596
//********************************************************************
// StudentBody.java Author: Lewis/Loftus // // Demonstrates the use of an aggregate class. public class StudentBody { // // Creates some Address and Student objects and prints them. public static void main (String[] args) Address school = new Address ("800 Lancaster Ave.", "Villanova", "PA", 19085); Address jHome = new Address ("21 Jump Street", "Lynchburg", "VA", 24551); Student john = new Student ("John", "Smith", jHome, school); Address mHome = new Address ("123 Main Street", "Euclid", "OH", 44132); Student marsha = new Student ("Marsha", "Jones", mHome, school); System.out.println (john); System.out.println (); System.out.println (marsha); } Copyright © 2012 Pearson Education, Inc.
597
Output John Smith Home Address: 21 Jump Street Lynchburg, VA 24551
School Address: 800 Lancaster Ave. Villanova, PA Marsha Jones 123 Main Street Euclid, OH //******************************************************************** // StudentBody.java Author: Lewis/Loftus // // Demonstrates the use of an aggregate class. public class StudentBody { // // Creates some Address and Student objects and prints them. public static void main (String[] args) Address school = new Address ("800 Lancaster Ave.", "Villanova", "PA", 19085); Address jHome = new Address ("21 Jump Street", "Lynchburg", "VA", 24551); Student john = new Student ("John", "Smith", jHome, school); Address mHome = new Address ("123 Main Street", "Euclid", "OH", 44132); Student marsha = new Student ("Marsha", "Jones", mHome, school); System.out.println (john); System.out.println (); System.out.println (marsha); } Copyright © 2012 Pearson Education, Inc.
598
//********************************************************************
// Student.java Author: Lewis/Loftus // // Represents a college student. public class Student { private String firstName, lastName; private Address homeAddress, schoolAddress; // // Constructor: Sets up this student with the specified values. public Student (String first, String last, Address home, Address school) firstName = first; lastName = last; homeAddress = home; schoolAddress = school; } continue Copyright © 2012 Pearson Education, Inc.
599
//-----------------------------------------------------------------
continue // // Returns a string description of this Student object. public String toString() { String result; result = firstName + " " + lastName + "\n"; result += "Home Address:\n" + homeAddress + "\n"; result += "School Address:\n" + schoolAddress; return result; } Copyright © 2012 Pearson Education, Inc.
600
//********************************************************************
// Address.java Author: Lewis/Loftus // // Represents a street address. public class Address { private String streetAddress, city, state; private long zipCode; // // Constructor: Sets up this address with the specified data. public Address (String street, String town, String st, long zip) streetAddress = street; city = town; state = st; zipCode = zip; } continue Copyright © 2012 Pearson Education, Inc.
601
//-----------------------------------------------------------------
continue // // Returns a description of this Address object. public String toString() { String result; result = streetAddress + "\n"; result += city + ", " + state + " " + zipCode; return result; } Copyright © 2012 Pearson Education, Inc.
602
Aggregation in UML StudentBody Student Address - firstName : String
+ main (args : String[]) : void + toString() : String Student - firstName : String - lastName : String - homeAddress : Address - schoolAddress : Address - streetAddress : String - city : String - state : String - zipCode : long Address Copyright © 2012 Pearson Education, Inc.
603
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through which the method is being executed Suppose the this reference is used inside a method called tryMe, which is invoked as follows: obj1.tryMe(); obj2.tryMe(); In the first invocation, the this reference refers to obj1; in the second it refers to obj2 Copyright © 2012 Pearson Education, Inc.
604
The this reference The this reference can be used to distinguish the instance variables of a class from corresponding method parameters with the same names The constructor of the Account class from Chapter 4 could have been written as follows: public Account (String name, long acctNumber, double balance) { this.name = name; this.acctNumber = acctNumber; this.balance = balance; } Copyright © 2012 Pearson Education, Inc.
605
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
606
Interfaces A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, usually it is left off An interface is used to establish a set of methods that a class will implement Copyright © 2012 Pearson Education, Inc.
607
Interfaces None of the methods in an interface are given
a definition (body) interface is a reserved word public interface Doable { public void doThis(); public int doThat(); public void doThis2 (double value, char ch); public boolean doTheOther (int num); } A semicolon immediately follows each method header Copyright © 2012 Pearson Education, Inc.
608
Interfaces An interface cannot be instantiated
Methods in an interface have public visibility by default A class formally implements an interface by: stating so in the class header providing implementations for every abstract method in the interface If a class declares that it implements an interface, it must define all methods in the interface Copyright © 2012 Pearson Education, Inc.
609
Interfaces implements is a reserved word
public class CanDo implements Doable { public void doThis () // whatever } public void doThat () // etc. Each method listed in Doable is given a definition Copyright © 2012 Pearson Education, Inc.
610
Interfaces In addition to (or instead of) abstract methods, an interface can contain constants When a class implements an interface, it gains access to all its constants A class that implements an interface can implement other methods as well See Complexity.java See Question.java See MiniQuiz.java Copyright © 2012 Pearson Education, Inc.
611
//********************************************************************
// Complexity.java Author: Lewis/Loftus // // Represents the interface for an object that can be assigned an // explicit complexity. public interface Complexity { public void setComplexity (int complexity); public int getComplexity(); } Copyright © 2012 Pearson Education, Inc.
612
//********************************************************************
// Question.java Author: Lewis/Loftus // // Represents a question (and its answer). public class Question implements Complexity { private String question, answer; private int complexityLevel; // // Constructor: Sets up the question with a default complexity. public Question (String query, String result) question = query; answer = result; complexityLevel = 1; } continue Copyright © 2012 Pearson Education, Inc.
613
//-----------------------------------------------------------------
continue // // Sets the complexity level for this question. public void setComplexity (int level) { complexityLevel = level; } // Returns the complexity level for this question. public int getComplexity() return complexityLevel; // Returns the question. public String getQuestion() return question; Copyright © 2012 Pearson Education, Inc.
614
//-----------------------------------------------------------------
continue // // Returns the answer to this question. public String getAnswer() { return answer; } // Returns true if the candidate answer matches the answer. public boolean answerCorrect (String candidateAnswer) return answer.equals(candidateAnswer); // Returns this question (and its answer) as a string. public String toString() return question + "\n" + answer; Copyright © 2012 Pearson Education, Inc.
615
//********************************************************************
// MiniQuiz.java Author: Lewis/Loftus // // Demonstrates the use of a class that implements an interface. import java.util.Scanner; public class MiniQuiz { // // Presents a short quiz. public static void main (String[] args) Question q1, q2; String possible; Scanner scan = new Scanner (System.in); q1 = new Question ("What is the capital of Jamaica?", "Kingston"); q1.setComplexity (4); q2 = new Question ("Which is worse, ignorance or apathy?", "I don't know and I don't care"); q2.setComplexity (10); continue Copyright © 2012 Pearson Education, Inc.
616
System.out.print (q1.getQuestion());
continue System.out.print (q1.getQuestion()); System.out.println (" (Level: " + q1.getComplexity() + ")"); possible = scan.nextLine(); if (q1.answerCorrect(possible)) System.out.println ("Correct"); else System.out.println ("No, the answer is " + q1.getAnswer()); System.out.println(); System.out.print (q2.getQuestion()); System.out.println (" (Level: " + q2.getComplexity() + ")"); if (q2.answerCorrect(possible)) System.out.println ("No, the answer is " + q2.getAnswer()); } Copyright © 2012 Pearson Education, Inc.
617
Sample Run What is the capital of Jamaica? (Level: 4) Kingston Correct
Which is worse, ignorance or apathy? (Level: 10) apathy No, the answer is I don't know and I don't care continue System.out.print (q1.getQuestion()); System.out.println (" (Level: " + q1.getComplexity() + ")"); possible = scan.nextLine(); if (q1.answerCorrect(possible)) System.out.println ("Correct"); else System.out.println ("No, the answer is " + q1.getAnswer()); System.out.println(); System.out.print (q2.getQuestion()); System.out.println (" (Level: " + q2.getComplexity() + ")"); if (q2.answerCorrect(possible)) System.out.println ("No, the answer is " + q2.getAnswer()); } Copyright © 2012 Pearson Education, Inc.
618
Interfaces A class can implement multiple interfaces
The interfaces are listed in the implements clause The class must implement all methods in all interfaces listed in the header class ManyThings implements interface1, interface2 { // all methods of both interfaces } Copyright © 2012 Pearson Education, Inc.
619
Interfaces The Java API contains many helpful interfaces
The Comparable interface contains one abstract method called compareTo, which is used to compare two objects We discussed the compareTo method of the String class in Chapter 5 The String class implements Comparable, giving us the ability to put strings in lexicographic order Copyright © 2012 Pearson Education, Inc.
620
The Comparable Interface
Any class can implement Comparable to provide a mechanism for comparing objects of that type if (obj1.compareTo(obj2) < 0) System.out.println ("obj1 is less than obj2"); The value returned from compareTo should be negative is obj1 is less that obj2, 0 if they are equal, and positive if obj1 is greater than obj2 It's up to the programmer to determine what makes one object less than another Copyright © 2012 Pearson Education, Inc.
621
The Iterator Interface
As we discussed in Chapter 5, an iterator is an object that provides a means of processing a collection of objects one at a time An iterator is created formally by implementing the Iterator interface, which contains three methods The hasNext method returns a boolean result – true if there are items left to process The next method returns the next object in the iteration The remove method removes the object most recently returned by the next method Copyright © 2012 Pearson Education, Inc.
622
The Iterable Interface
Another interface, Iterable, establishes that an object provides an iterator The Iterable interface has one method, iterator, that returns an Iterator object Any Iterable object can be processed using the for-each version of the for loop Note the difference: an Iterator has methods that perform an iteration; an Iterable object provides an iterator on request Copyright © 2012 Pearson Education, Inc.
623
Interfaces You could write a class that implements certain methods (such as compareTo) without formally implementing the interface (Comparable) However, formally establishing the relationship between a class and an interface allows Java to deal with an object in certain ways Interfaces are a key aspect of object-oriented design in Java We discuss this idea further in Chapter 10 Copyright © 2012 Pearson Education, Inc.
624
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
625
enum Season {winter, spring, summer, fall}
Enumerated Types In Chapter 3 we introduced enumerated types, which define a new data type and list all possible values of that type: enum Season {winter, spring, summer, fall} Once established, the new type can be used to declare variables Season time; The only values this variable can be assigned are the ones established in the enum definition Copyright © 2012 Pearson Education, Inc.
626
Enumerated Types An enumerated type definition is a special kind of class The values of the enumerated type are objects of that type For example, fall is an object of type Season That's why the following assignment is valid: time = Season.fall; Copyright © 2012 Pearson Education, Inc.
627
Enumerated Types An enumerated type definition can be more interesting than a simple list of values Because they are like classes, we can add additional instance data and methods We can define an enum constructor as well Each value listed for the enumerated type calls the constructor See Season.java See SeasonTester.java Copyright © 2012 Pearson Education, Inc.
628
//********************************************************************
// Season.java Author: Lewis/Loftus // // Enumerates the values for Season. public enum Season { winter ("December through February"), spring ("March through May"), summer ("June through August"), fall ("September through November"); private String span; continue Copyright © 2012 Pearson Education, Inc.
629
//-----------------------------------------------------------------
continue // // Constructor: Sets up each value with an associated string. Season (String months) { span = months; } // Returns the span message for this value. public String getSpan() return span; Copyright © 2012 Pearson Education, Inc.
630
//********************************************************************
// SeasonTester.java Author: Lewis/Loftus // // Demonstrates the use of a full enumerated type. public class SeasonTester { // // Iterates through the values of the Season enumerated type. public static void main (String[] args) for (Season time : Season.values()) System.out.println (time + "\t" + time.getSpan()); } Copyright © 2012 Pearson Education, Inc.
631
Output winter December through February spring March through May
summer June through August fall September through November //******************************************************************** // SeasonTester.java Author: Lewis/Loftus // // Demonstrates the use of a full enumerated type. public class SeasonTester { // // Iterates through the values of the Season enumerated type. public static void main (String[] args) for (Season time : Season.values()) System.out.println (time + "\t" + time.getSpan()); } Copyright © 2012 Pearson Education, Inc.
632
Enumerated Types Every enumerated type contains a static method called values that returns a list of all possible values for that type The list returned from values can be processed using a for-each loop An enumerated type cannot be instantiated outside of its own definition A carefully designed enumerated type provides a versatile and type-safe mechanism for managing data Copyright © 2012 Pearson Education, Inc.
633
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
634
Method Design As we've discussed, high-level design issues include:
identifying primary classes and objects assigning primary responsibilities After establishing high-level design issues, its important to address low-level issues such as the design of key methods For some methods, careful planning is needed to make sure they contribute to an efficient and elegant system design Copyright © 2012 Pearson Education, Inc.
635
Method Decomposition A method should be relatively small, so that it can be understood as a single entity A potentially large method should be decomposed into several smaller methods as needed for clarity A public service method of an object may call one or more private support methods to help it accomplish its goal Support methods might call other support methods if appropriate Copyright © 2012 Pearson Education, Inc.
636
Method Decomposition Let's look at an example that requires method decomposition – translating English into Pig Latin Pig Latin is a language in which each word is modified by moving the initial sound of the word to the end and adding "ay" Words that begin with vowels have the "yay" sound added on the end book ookbay table abletay item itemyay chair airchay Copyright © 2012 Pearson Education, Inc.
637
Method Decomposition The primary objective (translating a sentence) is too complicated for one method to accomplish Therefore we look for natural ways to decompose the solution into pieces Translating a sentence can be decomposed into the process of translating each word The process of translating a word can be separated into translating words that: begin with vowels begin with consonant blends (sh, cr, th, etc.) begin with single consonants Copyright © 2012 Pearson Education, Inc.
638
Method Decomposition In a UML class diagram, the visibility of a variable or method can be shown using special characters Public members are preceded by a plus sign Private members are preceded by a minus sign See PigLatin.java See PigLatinTranslator.java Copyright © 2012 Pearson Education, Inc.
639
//********************************************************************
// PigLatin.java Author: Lewis/Loftus // // Demonstrates the concept of method decomposition. import java.util.Scanner; public class PigLatin { // // Reads sentences and translates them into Pig Latin. public static void main (String[] args) String sentence, result, another; Scanner scan = new Scanner (System.in); continue Copyright © 2012 Pearson Education, Inc.
640
System.out.println ("Enter a sentence (no punctuation):");
continue do { System.out.println (); System.out.println ("Enter a sentence (no punctuation):"); sentence = scan.nextLine(); result = PigLatinTranslator.translate (sentence); System.out.println ("That sentence in Pig Latin is:"); System.out.println (result); System.out.print ("Translate another sentence (y/n)? "); another = scan.nextLine(); } while (another.equalsIgnoreCase("y")); Copyright © 2012 Pearson Education, Inc.
641
Sample Run Enter a sentence (no punctuation): Do you speak Pig Latin
That sentence in Pig Latin is: oday ouyay eakspay igpay atinlay Translate another sentence (y/n)? y Play it again Sam ayplay ityay againyay amsay Translate another sentence (y/n)? n continue do { System.out.println (); System.out.println ("Enter a sentence (no punctuation):"); sentence = scan.nextLine(); result = PigLatinTranslator.translate (sentence); System.out.println ("That sentence in Pig Latin is:"); System.out.println (result); System.out.print ("Translate another sentence (y/n)? "); another = scan.nextLine(); } while (another.equalsIgnoreCase("y")); Copyright © 2012 Pearson Education, Inc.
642
//********************************************************************
// PigLatinTranslator.java Author: Lewis/Loftus // // Represents a translator from English to Pig Latin. Demonstrates // method decomposition. import java.util.Scanner; public class PigLatinTranslator { // // Translates a sentence of words into Pig Latin. public static String translate (String sentence) String result = ""; sentence = sentence.toLowerCase(); Scanner scan = new Scanner (sentence); while (scan.hasNext()) result += translateWord (scan.next()); result += " "; } continue Copyright © 2012 Pearson Education, Inc.
643
//-----------------------------------------------------------------
continue return result; } // // Translates one word into Pig Latin. If the word begins with a // vowel, the suffix "yay" is appended to the word. Otherwise, // the first letter or two are moved to the end of the word, // and "ay" is appended. private static String translateWord (String word) { String result = ""; if (beginsWithVowel(word)) result = word + "yay"; else if (beginsWithBlend(word)) result = word.substring(2) + word.substring(0,2) + "ay"; result = word.substring(1) + word.charAt(0) + "ay"; Copyright © 2012 Pearson Education, Inc.
644
//-----------------------------------------------------------------
continue // // Determines if the specified word begins with a vowel. private static boolean beginsWithVowel (String word) { String vowels = "aeiou"; char letter = word.charAt(0); return (vowels.indexOf(letter) != -1); } Copyright © 2012 Pearson Education, Inc.
645
//-----------------------------------------------------------------
continue // // Determines if the specified word begins with a particular // two-character consonant blend. private static boolean beginsWithBlend (String word) { return ( word.startsWith ("bl") || word.startsWith ("sc") || word.startsWith ("br") || word.startsWith ("sh") || word.startsWith ("ch") || word.startsWith ("sk") || word.startsWith ("cl") || word.startsWith ("sl") || word.startsWith ("cr") || word.startsWith ("sn") || word.startsWith ("dr") || word.startsWith ("sm") || word.startsWith ("dw") || word.startsWith ("sp") || word.startsWith ("fl") || word.startsWith ("sq") || word.startsWith ("fr") || word.startsWith ("st") || word.startsWith ("gl") || word.startsWith ("sw") || word.startsWith ("gr") || word.startsWith ("th") || word.startsWith ("kl") || word.startsWith ("tr") || word.startsWith ("ph") || word.startsWith ("tw") || word.startsWith ("pl") || word.startsWith ("wh") || word.startsWith ("pr") || word.startsWith ("wr") ); } Copyright © 2012 Pearson Education, Inc.
646
Class Diagram for Pig Latin
+ main (args : String[]) : void + translate (sentence : String) : String - translateWord (word : String) : String - beginsWithVowel (word : String) : boolean - beginsWithBlend (word : String) : boolean PigLatinTranslator Copyright © 2012 Pearson Education, Inc.
647
Objects as Parameters Another important issue related to method design involves parameter passing Parameters in a Java method are passed by value A copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other Copyright © 2012 Pearson Education, Inc.
648
Passing Objects to Methods
What a method does with a parameter may or may not have a permanent effect (outside the method) Note the difference between changing the internal state of an object versus changing which object a reference points to See ParameterTester.java See ParameterModifier.java See Num.java Copyright © 2012 Pearson Education, Inc.
649
//********************************************************************
// ParameterTester.java Author: Lewis/Loftus // // Demonstrates the effects of passing various types of parameters. public class ParameterTester { // // Sets up three variables (one primitive and two objects) to // serve as actual parameters to the changeValues method. Prints // their values before and after calling the method. public static void main (String[] args) ParameterModifier modifier = new ParameterModifier(); int a1 = 111; Num a2 = new Num (222); Num a3 = new Num (333); continue Copyright © 2012 Pearson Education, Inc.
650
System.out.println ("Before calling changeValues:");
continue System.out.println ("Before calling changeValues:"); System.out.println ("a1\ta2\ta3"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); modifier.changeValues (a1, a2, a3); System.out.println ("After calling changeValues:"); } Copyright © 2012 Pearson Education, Inc.
651
Output Before calling changeValues: a1 a2 a3 111 222 333
Before changing the values: f1 f2 f3 After changing the values: After calling changeValues: continue System.out.println ("Before calling changeValues:"); System.out.println ("a1\ta2\ta3"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); modifier.changeValues (a1, a2, a3); System.out.println ("After calling changeValues:"); } Copyright © 2012 Pearson Education, Inc.
652
//********************************************************************
// ParameterModifier.java Author: Lewis/Loftus // // Demonstrates the effects of changing parameter values. public class ParameterModifier { // // Modifies the parameters, printing their values before and // after making the changes. public void changeValues (int f1, Num f2, Num f3) System.out.println ("Before changing the values:"); System.out.println ("f1\tf2\tf3"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); f1 = 999; f2.setValue(888); f3 = new Num (777); System.out.println ("After changing the values:"); } Copyright © 2012 Pearson Education, Inc.
653
//********************************************************************
// Num.java Author: Lewis/Loftus // // Represents a single integer as an object. public class Num { private int value; // // Sets up the new Num object, storing an initial value. public Num (int update) value = update; } continue Copyright © 2012 Pearson Education, Inc.
654
//-----------------------------------------------------------------
continue // // Sets the stored value to the newly specified value. public void setValue (int update) { value = update; } // Returns the stored integer value as a string. public String toString () return value + ""; Copyright © 2012 Pearson Education, Inc.
655
Copyright © 2012 Pearson Education, Inc.
656
Method Overloading Let's look at one more important method design issue: method overloading Method overloading is the process of giving a single method name multiple definitions in a class If a method is overloaded, the method name is not sufficient to determine which method is being called The signature of each overloaded method must be unique The signature includes the number, type, and order of the parameters Copyright © 2012 Pearson Education, Inc.
657
Method Overloading The compiler determines which method is being invoked by analyzing the parameters float tryMe(int x) { return x ; } result = tryMe(25, 4.32) Invocation float tryMe(int x, float y) { return x*y; } Copyright © 2012 Pearson Education, Inc.
658
Method Overloading The println method is overloaded:
println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total); Copyright © 2012 Pearson Education, Inc.
659
Overloading Methods The return type of the method is not part of the signature That is, overloaded methods cannot differ only by their return type Constructors can be overloaded Overloaded constructors provide multiple ways to initialize a new object Copyright © 2012 Pearson Education, Inc.
660
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
661
Testing Testing can mean many different things
It certainly includes running a completed program with various inputs It also includes any evaluation performed by human or computer to assess quality Some evaluations should occur before coding even begins The earlier we find an problem, the easier and cheaper it is to fix Copyright © 2012 Pearson Education, Inc.
662
Testing The goal of testing is to find errors
As we find and fix errors, we raise our confidence that a program will perform as intended We can never really be sure that all errors have been eliminated So when do we stop testing? Conceptual answer: Never Cynical answer: When we run out of time Better answer: When we are willing to risk that an undiscovered error still exists Copyright © 2012 Pearson Education, Inc.
663
Reviews A review is a meeting in which several people examine a design document or section of code It is a common and effective form of human-based testing Presenting a design or code to others: makes us think more carefully about it provides an outside perspective Reviews are sometimes called inspections or walkthroughs Copyright © 2012 Pearson Education, Inc.
664
Test Cases A test case is a set of input and user actions, coupled with the expected results Often test cases are organized formally into test suites which are stored and reused as needed For medium and large systems, testing must be a carefully managed process Many organizations have a separate Quality Assurance (QA) department to lead testing efforts Copyright © 2012 Pearson Education, Inc.
665
Defect and Regression Testing
Defect testing is the execution of test cases to uncover errors The act of fixing an error may introduce new errors After fixing a set of errors we should perform regression testing – running previous test suites to ensure new errors haven't been introduced It is not possible to create test cases for all possible input and user actions Therefore we should design tests to maximize their ability to find problems Copyright © 2012 Pearson Education, Inc.
666
Black-Box Testing In black-box testing, test cases are developed without considering the internal logic They are based on the input and expected output Input can be organized into equivalence categories Two input values in the same equivalence category would produce similar results Therefore a good test suite will cover all equivalence categories and focus on the boundaries between categories Copyright © 2012 Pearson Education, Inc.
667
White-Box Testing White-box testing focuses on the internal structure of the code The goal is to ensure that every path through the code is tested Paths through the code are governed by any conditional or looping statements in a program A good testing effort will include both black-box and white-box tests Copyright © 2012 Pearson Education, Inc.
668
Outline Software Development Activities
Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited Method Design Testing GUI Design and Layout Copyright © 2012 Pearson Education, Inc.
669
GUI Design We must remember that the goal of software is to help the user solve the problem To that end, the GUI designer should: Know the user Prevent user errors Optimize user abilities Be consistent Let's discuss each of these in more detail Copyright © 2012 Pearson Education, Inc.
670
Know the User Knowing the user implies an understanding of:
the user's true needs the user's common activities the user's level of expertise in the problem domain and in computer processing We should also realize these issues may differ for different users Remember, to the user, the interface is the program Copyright © 2012 Pearson Education, Inc.
671
Prevent User Errors Whenever possible, we should design user interfaces that minimize possible user mistakes We should choose the best GUI components for each task For example, in a situation where there are only a few valid options, using a menu or radio buttons would be better than an open text field Error messages should guide the user appropriately Copyright © 2012 Pearson Education, Inc.
672
Optimize User Abilities
Not all users are alike – some may be more familiar with the system than others Knowledgeable users are sometimes called power users We should provide multiple ways to accomplish a task whenever reasonable "wizards" to walk a user through a process short cuts for power users Help facilities should be available but not intrusive Copyright © 2012 Pearson Education, Inc.
673
Be Consistent Consistency is important – users get used to things appearing and working in certain ways Colors should be used consistently to indicate similar types of information or processing Screen layout should be consistent from one part of a system to another For example, error messages should appear in consistent locations Copyright © 2012 Pearson Education, Inc.
674
Layout Managers A layout manager is an object that determines the way that components are arranged in a container There are several predefined layout managers defined in the Java API: Flow Layout Border Layout Card Layout Grid Layout GridBag Layout Defined in the AWT Box Layout Overlay Layout Defined in Swing Copyright © 2012 Pearson Education, Inc.
675
Layout Managers Every container has a default layout manager, but we can explicitly set the layout manager as well Each layout manager has its own particular rules governing how the components will be arranged Some layout managers pay attention to a component's preferred size or alignment, while others do not A layout manager adjusts the layout as components are added and as containers are resized Copyright © 2012 Pearson Education, Inc.
676
Layout Managers We can use the setLayout method of a container to change its layout manager: JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); The following example uses a tabbed pane, a container which permits one of several panes to be selected See LayoutDemo.java See IntroPanel.java Copyright © 2012 Pearson Education, Inc.
677
//********************************************************************
// LayoutDemo.java Authors: Lewis/Loftus // // Demonstrates the use of flow, border, grid, and box layouts. import javax.swing.*; public class LayoutDemo { // // Sets up a frame containing a tabbed pane. The panel on each // tab demonstrates a different layout manager. public static void main (String[] args) JFrame frame = new JFrame ("Layout Manager Demo"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); continue Copyright © 2012 Pearson Education, Inc.
678
JTabbedPane tp = new JTabbedPane();
continue JTabbedPane tp = new JTabbedPane(); tp.addTab ("Intro", new IntroPanel()); tp.addTab ("Flow", new FlowPanel()); tp.addTab ("Border", new BorderPanel()); tp.addTab ("Grid", new GridPanel()); tp.addTab ("Box", new BoxPanel()); frame.getContentPane().add(tp); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
679
//********************************************************************
// IntroPanel.java Authors: Lewis/Loftus // // Represents the introduction panel for the LayoutDemo program. import java.awt.*; import javax.swing.*; public class IntroPanel extends JPanel { // // Sets up this panel with two labels. public IntroPanel() setBackground (Color.green); JLabel l1 = new JLabel ("Layout Manager Demonstration"); JLabel l2 = new JLabel ("Choose a tab to see an example of " + "a layout manager."); add (l1); add (l2); } Copyright © 2012 Pearson Education, Inc.
680
//********************************************************************
// IntroPanel.java Authors: Lewis/Loftus // // Represents the introduction panel for the LayoutDemo program. import java.awt.*; import javax.swing.*; public class IntroPanel extends JPanel { // // Sets up this panel with two labels. public IntroPanel() setBackground (Color.green); JLabel l1 = new JLabel ("Layout Manager Demonstration"); JLabel l2 = new JLabel ("Choose a tab to see an example of " + "a layout manager."); add (l1); add (l2); } Copyright © 2012 Pearson Education, Inc.
681
Flow Layout Flow layout puts as many components as possible on a row, then moves to the next row Components are displayed in the order they are added to the container Each row of components is centered horizontally by default, but could also be aligned left or right The horizontal and vertical gaps between the components can be explicitly set See FlowPanel.java Copyright © 2012 Pearson Education, Inc.
682
//********************************************************************
// FlowPanel.java Authors: Lewis/Loftus // // Represents the panel in the LayoutDemo program that demonstrates // the flow layout manager. import java.awt.*; import javax.swing.*; public class FlowPanel extends JPanel { // // Sets up this panel with some buttons to show how flow layout // affects their position. public FlowPanel () setLayout (new FlowLayout()); setBackground (Color.green); continue Copyright © 2012 Pearson Education, Inc.
683
JButton b1 = new JButton ("BUTTON 1");
continue JButton b1 = new JButton ("BUTTON 1"); JButton b2 = new JButton ("BUTTON 2"); JButton b3 = new JButton ("BUTTON 3"); JButton b4 = new JButton ("BUTTON 4"); JButton b5 = new JButton ("BUTTON 5"); add (b1); add (b2); add (b3); add (b4); add (b5); } Copyright © 2012 Pearson Education, Inc.
684
JButton b1 = new JButton ("BUTTON 1");
continue JButton b1 = new JButton ("BUTTON 1"); JButton b2 = new JButton ("BUTTON 2"); JButton b3 = new JButton ("BUTTON 3"); JButton b4 = new JButton ("BUTTON 4"); JButton b5 = new JButton ("BUTTON 5"); add (b1); add (b2); add (b3); add (b4); add (b5); } Copyright © 2012 Pearson Education, Inc.
685
Border Layout A border layout defines five areas into which components can be added North South Center East West Copyright © 2012 Pearson Education, Inc.
686
Border Layout Each area displays one component (which could be a container such as a JPanel) Each of the four outer areas enlarges as needed to accommodate the component added to it If nothing is added to the outer areas, they take up no space and other areas expand to fill the void The center area expands to fill space as needed See BorderPanel.java Copyright © 2012 Pearson Education, Inc.
687
//********************************************************************
// BorderPanel.java Authors: Lewis/Loftus // // Represents the panel in the LayoutDemo program that demonstrates // the border layout manager. import java.awt.*; import javax.swing.*; public class BorderPanel extends JPanel { // // Sets up this panel with a button in each area of a border // layout to show how it affects their position, shape, and size. public BorderPanel() setLayout (new BorderLayout()); setBackground (Color.green); continue Copyright © 2012 Pearson Education, Inc.
688
JButton b1 = new JButton ("BUTTON 1");
continue JButton b1 = new JButton ("BUTTON 1"); JButton b2 = new JButton ("BUTTON 2"); JButton b3 = new JButton ("BUTTON 3"); JButton b4 = new JButton ("BUTTON 4"); JButton b5 = new JButton ("BUTTON 5"); add (b1, BorderLayout.CENTER); add (b2, BorderLayout.NORTH); add (b3, BorderLayout.SOUTH); add (b4, BorderLayout.EAST); add (b5, BorderLayout.WEST); } Copyright © 2012 Pearson Education, Inc.
689
JButton b1 = new JButton ("BUTTON 1");
continue JButton b1 = new JButton ("BUTTON 1"); JButton b2 = new JButton ("BUTTON 2"); JButton b3 = new JButton ("BUTTON 3"); JButton b4 = new JButton ("BUTTON 4"); JButton b5 = new JButton ("BUTTON 5"); add (b1, BorderLayout.CENTER); add (b2, BorderLayout.NORTH); add (b3, BorderLayout.SOUTH); add (b4, BorderLayout.EAST); add (b5, BorderLayout.WEST); } Copyright © 2012 Pearson Education, Inc.
690
Grid Layout A grid layout presents a container’s components in a rectangular grid of rows and columns One component is placed in each cell of the grid, and all cells have the same size Components fill the grid from left-to-right and top- to-bottom (by default) The size of each cell is determined by the overall size of the container See GridPanel.java Copyright © 2012 Pearson Education, Inc.
691
//********************************************************************
// GridPanel.java Authors: Lewis/Loftus // // Represents the panel in the LayoutDemo program that demonstrates // the grid layout manager. import java.awt.*; import javax.swing.*; public class GridPanel extends JPanel { // // Sets up this panel with some buttons to show how grid // layout affects their position, shape, and size. public GridPanel() setLayout (new GridLayout (2, 3)); setBackground (Color.green); continue Copyright © 2012 Pearson Education, Inc.
692
JButton b1 = new JButton ("BUTTON 1");
continue JButton b1 = new JButton ("BUTTON 1"); JButton b2 = new JButton ("BUTTON 2"); JButton b3 = new JButton ("BUTTON 3"); JButton b4 = new JButton ("BUTTON 4"); JButton b5 = new JButton ("BUTTON 5"); add (b1); add (b2); add (b3); add (b4); add (b5); } Copyright © 2012 Pearson Education, Inc.
693
JButton b1 = new JButton ("BUTTON 1");
continue JButton b1 = new JButton ("BUTTON 1"); JButton b2 = new JButton ("BUTTON 2"); JButton b3 = new JButton ("BUTTON 3"); JButton b4 = new JButton ("BUTTON 4"); JButton b5 = new JButton ("BUTTON 5"); add (b1); add (b2); add (b3); add (b4); add (b5); } Copyright © 2012 Pearson Education, Inc.
694
Box Layout A box layout organizes components horizontally (in one row) or vertically (in one column) Components are placed top-to-bottom or left-to-right in the order in which they are added to the container By combining multiple containers using box layout, many different configurations can be created Multiple containers with box layouts are often preferred to one container that uses the more complicated gridbag layout manager Copyright © 2012 Pearson Education, Inc.
695
Box Layout Invisible components can be added to a box layout container to take up space between components Rigid areas have a fixed size Glue specifies where excess space should go Invisible components are created using these methods of the Box class: createRigidArea(Dimension d) createHorizontalGlue() createVerticalGlue() See BoxPanel.java Copyright © 2012 Pearson Education, Inc.
696
//********************************************************************
// BoxPanel.java Authors: Lewis/Loftus // // Represents the panel in the LayoutDemo program that demonstrates // the box layout manager. import java.awt.*; import javax.swing.*; public class BoxPanel extends JPanel { // // Sets up this panel with some buttons to show how a vertical // box layout (and invisible components) affects their position. public BoxPanel() setLayout (new BoxLayout (this, BoxLayout.Y_AXIS)); setBackground (Color.green); continue Copyright © 2012 Pearson Education, Inc.
697
JButton b1 = new JButton ("BUTTON 1");
continue JButton b1 = new JButton ("BUTTON 1"); JButton b2 = new JButton ("BUTTON 2"); JButton b3 = new JButton ("BUTTON 3"); JButton b4 = new JButton ("BUTTON 4"); JButton b5 = new JButton ("BUTTON 5"); add (b1); add (Box.createRigidArea (new Dimension (0, 10))); add (b2); add (Box.createVerticalGlue()); add (b3); add (b4); add (Box.createRigidArea (new Dimension (0, 20))); add (b5); } Copyright © 2012 Pearson Education, Inc.
698
JButton b1 = new JButton ("BUTTON 1");
continue JButton b1 = new JButton ("BUTTON 1"); JButton b2 = new JButton ("BUTTON 2"); JButton b3 = new JButton ("BUTTON 3"); JButton b4 = new JButton ("BUTTON 4"); JButton b5 = new JButton ("BUTTON 5"); add (b1); add (Box.createRigidArea (new Dimension (0, 10))); add (b2); add (Box.createVerticalGlue()); add (b3); add (b4); add (Box.createRigidArea (new Dimension (0, 20))); add (b5); } Copyright © 2012 Pearson Education, Inc.
699
Borders A border can be put around any Swing component to define how the edges of the component should be drawn Borders can be used effectively to group components visually The BorderFactory class contains several static methods for creating border objects A border is applied to a component using the setBorder method Copyright © 2012 Pearson Education, Inc.
700
Borders An empty border A line border An etched border
buffers the space around the edge of a component otherwise has no visual effect A line border surrounds the component with a simple line the line's color and thickness can be specified An etched border creates the effect of an etched groove around a component uses colors for the highlight and shadow Copyright © 2012 Pearson Education, Inc.
701
Borders A bevel border A titled border A matte border
can be raised or lowered uses colors for the outer and inner highlights and shadows A titled border places a title on or around the border the title can be oriented in many ways A matte border specifies the sizes of the top, left, bottom, and right edges of the border separately uses either a solid color or an image Copyright © 2012 Pearson Education, Inc.
702
Borders A compound border See BorderDemo.java
is a combination of two borders one or both of the borders can be a compound border See BorderDemo.java Copyright © 2012 Pearson Education, Inc.
703
//********************************************************************
// BorderDemo.java Authors: Lewis/Loftus // // Demonstrates the use of various types of borders. import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class BorderDemo { // // Creates several bordered panels and displays them. public static void main (String[] args) JFrame frame = new JFrame ("Border Demo"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout (new GridLayout (0, 2, 5, 10)); panel.setBorder (BorderFactory.createEmptyBorder (8, 8, 8, 8)); JPanel p1 = new JPanel(); p1.setBorder (BorderFactory.createLineBorder (Color.red, 3)); p1.add (new JLabel ("Line Border")); panel.add (p1); continue Copyright © 2012 Pearson Education, Inc.
704
JPanel p2 = new JPanel();
continue JPanel p2 = new JPanel(); p2.setBorder (BorderFactory.createEtchedBorder ()); p2.add (new JLabel ("Etched Border")); panel.add (p2); JPanel p3 = new JPanel(); p3.setBorder (BorderFactory.createRaisedBevelBorder ()); p3.add (new JLabel ("Raised Bevel Border")); panel.add (p3); JPanel p4 = new JPanel(); p4.setBorder (BorderFactory.createLoweredBevelBorder ()); p4.add (new JLabel ("Lowered Bevel Border")); panel.add (p4); JPanel p5 = new JPanel(); p5.setBorder (BorderFactory.createTitledBorder ("Title")); p5.add (new JLabel ("Titled Border")); panel.add (p5); JPanel p6 = new JPanel(); TitledBorder tb = BorderFactory.createTitledBorder ("Title"); tb.setTitleJustification (TitledBorder.RIGHT); p6.setBorder (tb); p6.add (new JLabel ("Titled Border (right)")); panel.add (p6); Copyright © 2012 Pearson Education, Inc.
705
JPanel p7 = new JPanel();
continue JPanel p7 = new JPanel(); Border b1 = BorderFactory.createLineBorder (Color.blue, 2); Border b2 = BorderFactory.createEtchedBorder (); p7.setBorder (BorderFactory.createCompoundBorder (b1, b2)); p7.add (new JLabel ("Compound Border")); panel.add (p7); JPanel p8 = new JPanel(); Border mb = BorderFactory.createMatteBorder (1, 5, 1, 1, Color.red); p8.setBorder (mb); p8.add (new JLabel ("Matte Border")); panel.add (p8); frame.getContentPane().add (panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
706
JPanel p7 = new JPanel();
continue JPanel p7 = new JPanel(); Border b1 = BorderFactory.createLineBorder (Color.blue, 2); Border b2 = BorderFactory.createEtchedBorder (); p7.setBorder (BorderFactory.createCompoundBorder (b1, b2)); p7.add (new JLabel ("Compound Border")); panel.add (p7); JPanel p8 = new JPanel(); Border mb = BorderFactory.createMatteBorder (1, 5, 1, 1, Color.red); p8.setBorder (mb); p8.add (new JLabel ("Matte Border")); panel.add (p8); frame.getContentPane().add (panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
707
Summary Chapter 7 has focused on: software development activities
determining the classes and objects that are needed for a program the relationships that can exist among classes the static modifier writing interfaces the design of enumerated type classes method design and method overloading GUI design and layout managers Copyright © 2012 Pearson Education, Inc.
708
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 8 Arrays Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
709
Arrays Arrays are objects that help us organize large amounts of information Chapter 8 focuses on: array declaration and use bounds checking and capacity arrays that store object references variable length parameter lists multidimensional arrays polygons and polylines mouse events and keyboard events Copyright © 2012 Pearson Education, Inc.
710
Outline Declaring and Using Arrays Arrays of Objects
Variable Length Parameter Lists Two-Dimensional Arrays Polygons and Polylines Mouse Events and Key Events Copyright © 2012 Pearson Education, Inc.
711
Arrays The ArrayList class, introduced in Chapter 5, is used to organize a list of objects It is a class in the Java API An array is a programming language construct used to organize a list of objects It has special syntax to access elements As its name implies, the ArrayList class uses an array internally to manage the list of objects Copyright © 2012 Pearson Education, Inc.
712
Each value has a numeric index
Arrays An array is an ordered list of values: scores The entire array has a single name Each value has a numeric index An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9 Copyright © 2012 Pearson Education, Inc.
713
Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) That expression represents a place to store a single integer and can be used wherever an integer variable can be used Copyright © 2012 Pearson Education, Inc.
714
Arrays For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); pick = scores[rand.nextInt(11)]; Copyright © 2012 Pearson Education, Inc.
715
Arrays The values held in an array are called array elements
An array stores multiple values of the same type – the element type The element type can be a primitive type or an object reference Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. Copyright © 2012 Pearson Education, Inc.
716
Arrays In Java, the array itself is an object that must be instantiated Another way to depict the scores array: scores 79 87 94 82 67 98 81 74 91 The name of the array is an object reference variable Copyright © 2012 Pearson Education, Inc.
717
int[] scores = new int[10];
Declaring Arrays The scores array could be declared as follows: int[] scores = new int[10]; The type of the variable scores is int[] (an array of integers) Note that the array type does not specify its size, but each object of that type has a specific size The reference variable scores is set to a new array object that can hold 10 integers Copyright © 2012 Pearson Education, Inc.
718
Declaring Arrays Some other examples of array declarations:
int[] weights = new int[2000]; double[] prices = new double[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; Copyright © 2012 Pearson Education, Inc.
719
Using Arrays The for-each version of the for loop can be used when processing array elements: for (int score : scores) System.out.println (score); This is only appropriate when processing all array elements starting at index 0 It can't be used to set the array values See BasicArray.java Copyright © 2012 Pearson Education, Inc.
720
//********************************************************************
// BasicArray.java Author: Lewis/Loftus // // Demonstrates basic array declaration and use. public class BasicArray { // // Creates an array, fills it with various integer values, // modifies one value, then prints them out. public static void main (String[] args) final int LIMIT = 15, MULTIPLE = 10; int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value // Print the array values for (int value : list) System.out.print (value + " "); } Copyright © 2012 Pearson Education, Inc.
721
Output //******************************************************************** // BasicArray.java Author: Lewis/Loftus // // Demonstrates basic array declaration and use. public class BasicArray { // // Creates an array, fills it with various integer values, // modifies one value, then prints them out. public static void main (String[] args) final int LIMIT = 15, MULTIPLE = 10; int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value // Print the array values for (int value : list) System.out.print (value + " "); } Copyright © 2012 Pearson Education, Inc.
722
Basic Array Example Copyright © 2012 Pearson Education, Inc.
723
Quick Check Write an array declaration to represent the ages of 100 children. Write code that prints each value in an array of integers named values. Copyright © 2012 Pearson Education, Inc.
724
Quick Check Write an array declaration to represent the ages of 100 children. Write code that prints each value in an array of integers named values. int[] ages = new int[100]; for (int value : values) System.out.println(value); Copyright © 2012 Pearson Education, Inc.
725
Bounds Checking Once an array is created, it has a fixed size
An index used in an array reference must specify a valid element That is, the index value must be in range 0 to N-1 The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds This is called automatic bounds checking Copyright © 2012 Pearson Education, Inc.
726
Bounds Checking For example, if the array codes can hold 100 values, it can be indexed from 0 to 99 If the value of count is 100, then the following reference will cause an exception to be thrown: System.out.println(codes[count]); It’s common to introduce off-by-one errors when using arrays: problem for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; Copyright © 2012 Pearson Education, Inc.
727
Bounds Checking Each array object has a public constant called length that stores the size of the array It is referenced using the array name: scores.length Note that length holds the number of elements, not the largest index See ReverseOrder.java See LetterCount.java Copyright © 2012 Pearson Education, Inc.
728
//********************************************************************
// ReverseOrder.java Author: Lewis/Loftus // // Demonstrates array index processing. import java.util.Scanner; public class ReverseOrder { // // Reads a list of numbers from the user, storing them in an // array, then prints them in the opposite order. public static void main (String[] args) Scanner scan = new Scanner (System.in); double[] numbers = new double[10]; System.out.println ("The size of the array: " + numbers.length); continue Copyright © 2012 Pearson Education, Inc.
729
for (int index = 0; index < numbers.length; index++) {
continue for (int index = 0; index < numbers.length; index++) { System.out.print ("Enter number " + (index+1) + ": "); numbers[index] = scan.nextDouble(); } System.out.println ("The numbers in reverse order:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " "); Copyright © 2012 Pearson Education, Inc.
730
Sample Run The size of the array: 10 Enter number 1: 18.36
The numbers in reverse order: continue for (int index = 0; index < numbers.length; index++) { System.out.print ("Enter number " + (index+1) + ": "); numbers[index] = scan.nextDouble(); } System.out.println ("The numbers in reverse order:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " "); Copyright © 2012 Pearson Education, Inc.
731
//********************************************************************
// LetterCount.java Author: Lewis/Loftus // // Demonstrates the relationship between arrays and strings. import java.util.Scanner; public class LetterCount { // // Reads a sentence from the user and counts the number of // uppercase and lowercase letters contained in it. public static void main (String[] args) final int NUMCHARS = 26; Scanner scan = new Scanner (System.in); int[] upper = new int[NUMCHARS]; int[] lower = new int[NUMCHARS]; char current; // the current character being processed int other = 0; // counter for non-alphabetics continue Copyright © 2012 Pearson Education, Inc.
732
System.out.println ("Enter a sentence:");
continue System.out.println ("Enter a sentence:"); String line = scan.nextLine(); // Count the number of each letter occurence for (int ch = 0; ch < line.length(); ch++) { current = line.charAt(ch); if (current >= 'A' && current <= 'Z') upper[current-'A']++; else if (current >= 'a' && current <= 'z') lower[current-'a']++; other++; } Copyright © 2012 Pearson Education, Inc.
733
for (int letter=0; letter < upper.length; letter++) {
continue // Print the results System.out.println (); for (int letter=0; letter < upper.length; letter++) { System.out.print ( (char) (letter + 'A') ); System.out.print (": " + upper[letter]); System.out.print ("\t\t" + (char) (letter + 'a') ); System.out.println (": " + lower[letter]); } System.out.println ("Non-alphabetic characters: " + other); Copyright © 2012 Pearson Education, Inc.
734
Sample Run (continued)
Enter a sentence: In Casablanca, Humphrey Bogart never says "Play it again, Sam." A: 0 a: 10 B: 1 b: 1 C: 1 c: 1 D: 0 d: 0 E: 0 e: 3 F: 0 f: 0 G: 0 g: 2 H: 1 h: 1 I: 1 i: 2 J: 0 j: 0 K: 0 k: 0 L: 0 l: 2 M: 0 m: 2 N: 0 n: 4 O: 0 o: 1 P: 1 p: 1 Q: 0 q: 0 continue continue // Print the results System.out.println (); for (int letter=0; letter < upper.length; letter++) { System.out.print ( (char) (letter + 'A') ); System.out.print (": " + upper[letter]); System.out.print ("\t\t" + (char) (letter + 'a') ); System.out.println (": " + lower[letter]); } System.out.println ("Non-alphabetic characters: " + other); Sample Run (continued) R: 0 r: 3 S: 1 s: 3 T: 0 t: 2 U: 0 u: 1 V: 0 v: 1 W: 0 w: 0 X: 0 x: 0 Y: 0 y: 3 Z: 0 z: 0 Non-alphabetic characters: 14 Copyright © 2012 Pearson Education, Inc.
735
Alternate Array Syntax
The brackets of the array type can be associated with the element type or with the name of the array Therefore the following two declarations are equivalent: double[] prices; double prices[]; The first format generally is more readable and should be used Copyright © 2012 Pearson Education, Inc.
736
Initializer Lists An initializer list can be used to instantiate and fill an array in one step The values are delimited by braces and separated by commas Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] grades = {'A', 'B', 'C', 'D', ’F'}; Copyright © 2012 Pearson Education, Inc.
737
Initializer Lists Note that when an initializer list is used:
the new operator is not used no size value is specified The size of the array is determined by the number of items in the list An initializer list can be used only in the array declaration See Primes.java Copyright © 2012 Pearson Education, Inc.
738
//********************************************************************
// Primes.java Author: Lewis/Loftus // // Demonstrates the use of an initializer list for an array. public class Primes { // // Stores some prime numbers in an array and prints them. public static void main (String[] args) int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " + primeNums.length); System.out.println ("The first few prime numbers are:"); for (int prime : primeNums) System.out.print (prime + " "); } Copyright © 2012 Pearson Education, Inc.
739
Output Array length: 8 The first few prime numbers are:
//******************************************************************** // Primes.java Author: Lewis/Loftus // // Demonstrates the use of an initializer list for an array. public class Primes { // // Stores some prime numbers in an array and prints them. public static void main (String[] args) int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " + primeNums.length); System.out.println ("The first few prime numbers are:"); for (int prime : primeNums) System.out.print (prime + " "); } Copyright © 2012 Pearson Education, Inc.
740
Arrays as Parameters An entire array can be passed as a parameter to a method Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other Therefore, changing an array element within the method changes the original An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type Copyright © 2012 Pearson Education, Inc.
741
Outline Declaring and Using Arrays Arrays of Objects
Variable Length Parameter Lists Two-Dimensional Arrays Polygons and Polylines Mouse Events and Key Events Copyright © 2012 Pearson Education, Inc.
742
String[] words = new String[5];
Arrays of Objects The elements of an array can be object references The following declaration reserves space to store 5 references to String objects String[] words = new String[5]; It does NOT create the String objects themselves Initially an array of objects holds null references Each object stored in an array must be instantiated separately Copyright © 2012 Pearson Education, Inc.
743
System.out.println(words[0]);
Arrays of Objects The words array when initially declared: At this point, the following line of code would throw a NullPointerException: System.out.println(words[0]); words - Copyright © 2012 Pearson Education, Inc.
744
Arrays of Objects After some String objects are created and stored in the array: "friendship" words - "loyalty" "honor" Copyright © 2012 Pearson Education, Inc.
745
Arrays of Objects Keep in mind that String objects can be created using literals The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep", "run"}; Copyright © 2012 Pearson Education, Inc.
746
Arrays of Objects The following example creates an array of Grade objects, each with a string representation and a numeric lower bound The letter grades include plus and minus designations, so must be stored as strings instead of char See GradeRange.java See Grade.java Copyright © 2012 Pearson Education, Inc.
747
//********************************************************************
// GradeRange.java Author: Lewis/Loftus // // Demonstrates the use of an array of objects. public class GradeRange { // // Creates an array of Grade objects and prints them. public static void main (String[] args) Grade[] grades = new Grade("A", 95), new Grade("A-", 90), new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80), new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70), new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60), new Grade("F", 0) }; for (Grade letterGrade : grades) System.out.println (letterGrade); } Copyright © 2012 Pearson Education, Inc.
748
Output A 95 A- 90 B+ 87 B 85 B- 80 C+ 77 C 75 C- 70 D+ 67 D 65 D- 60
F 0 //******************************************************************** // GradeRange.java Author: Lewis/Loftus // // Demonstrates the use of an array of objects. public class GradeRange { // // Creates an array of Grade objects and prints them. public static void main (String[] args) Grade[] grades = new Grade("A", 95), new Grade("A-", 90), new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80), new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70), new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60), new Grade("F", 0) }; for (Grade letterGrade : grades) System.out.println (letterGrade); } Copyright © 2012 Pearson Education, Inc.
749
//********************************************************************
// Grade.java Author: Lewis/Loftus // // Represents a school grade. public class Grade { private String name; private int lowerBound; // // Constructor: Sets up this Grade object with the specified // grade name and numeric lower bound. public Grade (String grade, int cutoff) name = grade; lowerBound = cutoff; } // Returns a string representation of this grade. public String toString() return name + "\t" + lowerBound; continue Copyright © 2012 Pearson Education, Inc.
750
//-----------------------------------------------------------------
continue // // Name mutator. public void setName (String grade) { name = grade; } // Lower bound mutator. public void setLowerBound (int cutoff) lowerBound = cutoff; Copyright © 2012 Pearson Education, Inc.
751
//-----------------------------------------------------------------
continue // // Name accessor. public String getName() { return name; } // Lower bound accessor. public int getLowerBound() return lowerBound; Copyright © 2012 Pearson Education, Inc.
752
Arrays of Objects Now let's look at an example that manages a collection of DVD objects An initial capacity of 100 is created for the collection If more room is needed, a private method is used to create a larger array and transfer the current DVDs See Movies.java See DVDCollection.java See DVD.java Copyright © 2012 Pearson Education, Inc.
753
//********************************************************************
// Movies.java Author: Lewis/Loftus // // Demonstrates the use of an array of objects. public class Movies { // // Creates a DVDCollection object and adds some DVDs to it. Prints // reports on the status of the collection. public static void main (String[] args) DVDCollection movies = new DVDCollection(); movies.addDVD ("The Godfather", "Francis Ford Coppala", 1972, 24.95, true); movies.addDVD ("District 9", "Neill Blomkamp", 2009, 19.95, false); movies.addDVD ("Iron Man", "Jon Favreau", 2008, 15.95, false); movies.addDVD ("All About Eve", "Joseph Mankiewicz", 1950, 17.50, false); movies.addDVD ("The Matrix", "Andy & Lana Wachowski", 1999, 19.95, true); System.out.println (movies); movies.addDVD ("Iron Man 2", "Jon Favreau", 2010, 22.99, false); movies.addDVD ("Casablanca", "Michael Curtiz", 1942, 19.95, false); } Copyright © 2012 Pearson Education, Inc.
754
Output ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ My DVD Collection
//******************************************************************** // Movies.java Author: Lewis/Loftus // // Demonstrates the use of an array of objects. public class Movies { // // Creates a DVDCollection object and adds some DVDs to it. Prints // reports on the status of the collection. public static void main (String[] args) DVDCollection movies = new DVDCollection(); movies.addDVD ("The Godfather", "Francis Ford Coppala", 1972, 24.95, true); movies.addDVD ("District 9", "Neill Blomkamp", 2009, 19.95, false); movies.addDVD ("Iron Man", "Jon Favreau", 2008, 15.95, false); movies.addDVD ("All About Eve", "Joseph Mankiewicz", 1950, 17.50, false); movies.addDVD ("The Matrix", "Andy & Lana Wachowski", 1999, 19.95, true); System.out.println (movies); movies.addDVD ("Iron Man 2", "Jon Favreau", 2010, 22.99, false); movies.addDVD ("Casablanca", "Michael Curtiz", 1942, 19.95, false); } Output ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ My DVD Collection Number of DVDs: 5 Total cost: $98.30 Average cost: $19.66 DVD List: $ The Godfather Francis Ford Coppala Blu-Ray $ District 9 Neill Blomkamp $ Iron Man Jon Favreau $ All About Eve Joseph Mankiewicz $ The Matrix Andy & Lana Wachowski Blu-Ray continue Copyright © 2012 Pearson Education, Inc.
755
Output Output (continued) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//******************************************************************** // Movies.java Author: Lewis/Loftus // // Demonstrates the use of an array of objects. public class Movies { // // Creates a DVDCollection object and adds some DVDs to it. Prints // reports on the status of the collection. public static void main (String[] args) DVDCollection movies = new DVDCollection(); movies.addDVD ("The Godfather", "Francis Ford Coppala", 1972, 24.95, true); movies.addDVD ("District 9", "Neill Blomkamp", 2009, 19.95, false); movies.addDVD ("Iron Man", "Jon Favreau", 2008, 15.95, false); movies.addDVD ("All About Eve", "Joseph Mankiewicz", 1950, 17.50, false); movies.addDVD ("The Matrix", "Andy & Lana Wachowski", 1999, 19.95, true); System.out.println (movies); movies.addDVD ("Iron Man 2", "Jon Favreau", 2010, 22.99, false); movies.addDVD ("Casablanca", "Michael Curtiz", 1942, 19.95, false); } Output ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ My DVD Collection Number of DVDs: 5 Total cost: $98.30 Average cost: $19.66 DVD List: $ The Godfather Francis Ford Coppala Blu-Ray $ District 9 Neill Blomkamp $ Iron Man Jon Favreau $ All About Eve Joseph Mankiewicz $ The Matrix Andy & Lana Wachowski Blu-Ray continue Output (continued) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ My DVD Collection Number of DVDs: 7 Total cost: $141.24 Average cost: $20.18 DVD List: $ The Godfather Francis Ford Coppala Blu-Ray $ District 9 Neill Blomkamp $ Iron Man Jon Favreau $ All About Eve Joseph Mankiewicz $ The Matrix Andy & Lana Wachowski Blu-Ray $ Iron Man 2 Jon Favreau $ Casablanca Michael Curtiz Copyright © 2012 Pearson Education, Inc.
756
//********************************************************************
// DVDCollection.java Author: Lewis/Loftus // // Represents a collection of DVD movies. import java.text.NumberFormat; public class DVDCollection { private DVD[] collection; private int count; private double totalCost; // // Constructor: Creates an initially empty collection. public DVDCollection () collection = new DVD[100]; count = 0; totalCost = 0.0; } continue Copyright © 2012 Pearson Education, Inc.
757
//-----------------------------------------------------------------
continue // // Adds a DVD to the collection, increasing the size of the // collection array if necessary. public void addDVD (String title, String director, int year, double cost, boolean bluRay) { if (count == collection.length) increaseSize(); collection[count] = new DVD (title, director, year, cost, bluRay); totalCost += cost; count++; } Copyright © 2012 Pearson Education, Inc.
758
//-----------------------------------------------------------------
continue // // Returns a report describing the DVD collection. public String toString() { NumberFormat fmt = NumberFormat.getCurrencyInstance(); String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; report += "My DVD Collection\n\n"; report += "Number of DVDs: " + count + "\n"; report += "Total cost: " + fmt.format(totalCost) + "\n"; report += "Average cost: " + fmt.format(totalCost/count); report += "\n\nDVD List:\n\n"; for (int dvd = 0; dvd < count; dvd++) report += collection[dvd].toString() + "\n"; return report; } Copyright © 2012 Pearson Education, Inc.
759
//-----------------------------------------------------------------
continue // // Increases the capacity of the collection by creating a // larger array and copying the existing collection into it. private void increaseSize () { DVD[] temp = new DVD[collection.length * 2]; for (int dvd = 0; dvd < collection.length; dvd++) temp[dvd] = collection[dvd]; collection = temp; } Copyright © 2012 Pearson Education, Inc.
760
//********************************************************************
// DVD.java Author: Lewis/Loftus // // Represents a DVD video disc. import java.text.NumberFormat; public class DVD { private String title, director; private int year; private double cost; private boolean bluRay; // // Creates a new DVD with the specified information. public DVD (String title, String director, int year, double cost, boolean bluRay) this.title = title; this.director = director; this.year = year; this.cost = cost; this.bluRay = bluRay; } continue Copyright © 2012 Pearson Education, Inc.
761
//-----------------------------------------------------------------
continue // // Returns a string description of this DVD. public String toString() { NumberFormat fmt = NumberFormat.getCurrencyInstance(); String description; description = fmt.format(cost) + "\t" + year + "\t"; description += title + "\t" + director; if (bluRay) description += "\t" + "Blu-Ray"; return description; } Copyright © 2012 Pearson Education, Inc.
762
Arrays of Objects A UML diagram for the Movies program:
Copyright © 2012 Pearson Education, Inc.
763
Command-Line Arguments
The signature of the main method indicates that it takes an array of String objects as a parameter These values come from command-line arguments that are provided when the interpreter is invoked For example, the following invocation of the interpreter passes three String objects into the main method of the StateEval program: java StateEval pennsylvania texas arizona See NameTag.java Copyright © 2012 Pearson Education, Inc.
764
//********************************************************************
// NameTag.java Author: Lewis/Loftus // // Demonstrates the use of command line arguments. public class NameTag { // // Prints a simple name tag using a greeting and a name that is // specified by the user. public static void main (String[] args) System.out.println (); System.out.println (" " + args[0]); System.out.println ("My name is " + args[1]); } Copyright © 2012 Pearson Education, Inc.
765
Command-Line Execution
> java NameTag Howdy John Howdy My name is John > java NameTag Hello Bill Hello My name is Bill //******************************************************************** // NameTag.java Author: Lewis/Loftus // // Demonstrates the use of command line arguments. public class NameTag { // // Prints a simple name tag using a greeting and a name that is // specified by the user. public static void main (String[] args) System.out.println (); System.out.println (" " + args[0]); System.out.println ("My name is " + args[1]); } Copyright © 2012 Pearson Education, Inc.
766
Outline Declaring and Using Arrays Arrays of Objects
Variable Length Parameter Lists Two-Dimensional Arrays Polygons and Polylines Mouse Events and Key Events Copyright © 2012 Pearson Education, Inc.
767
Variable Length Parameter Lists
Suppose we wanted to create a method that processed a different amount of data from one invocation to the next For example, let's define a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75); Copyright © 2012 Pearson Education, Inc.
768
Variable Length Parameter Lists
We could define overloaded versions of the average method Downside: we'd need a separate version of the method for each additional parameter We could define the method to accept an array of integers Downside: we'd have to create the array and store the integers prior to calling the method each time Instead, Java provides a convenient way to create variable length parameter lists Copyright © 2012 Pearson Education, Inc.
769
Variable Length Parameter Lists
Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type For each call, the parameters are automatically put into an array for easy processing in the method Indicates a variable length parameter list public double average (int ... list) { // whatever } element type array name Copyright © 2012 Pearson Education, Inc.
770
Variable Length Parameter Lists
public double average (int ... list) { double result = 0.0; if (list.length != 0) int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result; Copyright © 2012 Pearson Education, Inc.
771
Variable Length Parameter Lists
The type of the parameter can be any primitive or object type: public void printGrades (Grade ... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); } Copyright © 2012 Pearson Education, Inc.
772
Quick Check Write method called distance that accepts a variable number of integers (which each represent the distance of one leg of a trip) and returns the total distance of the trip. Copyright © 2012 Pearson Education, Inc.
773
Quick Check Write method called distance that accepts a variable number of integers (which each represent the distance of one leg of a trip) and returns the total distance of the trip. public int distance (int ... list) { int sum = 0; for (int num : list) sum = sum + num; return sum; } Copyright © 2012 Pearson Education, Inc.
774
Variable Length Parameter Lists
A method that accepts a variable number of parameters can also accept other parameters The following method accepts an int, a String object, and a variable number of double values into an array called nums public void test (int count, String name, double ... nums) { // whatever } Copyright © 2012 Pearson Education, Inc.
775
Variable Length Parameter Lists
The varying number of parameters must come last in the formal arguments A method cannot accept two sets of varying parameters Constructors can also be set up to accept a variable number of parameters See VariableParameters.java See Family.java Copyright © 2012 Pearson Education, Inc.
776
//********************************************************************
// VariableParameters.java Author: Lewis/Loftus // // Demonstrates the use of a variable length parameter list. public class VariableParameters { // // Creates two Family objects using a constructor that accepts // a variable number of String objects as parameters. public static void main (String[] args) Family lewis = new Family ("John", "Sharon", "Justin", "Kayla", "Nathan", "Samantha"); Family camden = new Family ("Stephen", "Annie", "Matt", "Mary", "Simon", "Lucy", "Ruthie", "Sam", "David"); System.out.println(lewis); System.out.println(); System.out.println(camden); } Copyright © 2012 Pearson Education, Inc.
777
Output John Sharon Justin Kayla Nathan Samantha Stephen Annie Matt
Mary Simon Lucy Ruthie Sam David //******************************************************************** // VariableParameters.java Author: Lewis/Loftus // // Demonstrates the use of a variable length parameter list. public class VariableParameters { // // Creates two Family objects using a constructor that accepts // a variable number of String objects as parameters. public static void main (String[] args) Family lewis = new Family ("John", "Sharon", "Justin", "Kayla", "Nathan", "Samantha"); Family camden = new Family ("Stephen", "Annie", "Matt", "Mary", "Simon", "Lucy", "Ruthie", "Sam", "David"); System.out.println(lewis); System.out.println(); System.out.println(camden); } Copyright © 2012 Pearson Education, Inc.
778
//********************************************************************
// Family.java Author: Lewis/Loftus // // Demonstrates the use of variable length parameter lists. public class Family { private String[] members; // // Constructor: Sets up this family by storing the (possibly // multiple) names that are passed in as parameters. public Family (String ... names) members = names; } continue Copyright © 2012 Pearson Education, Inc.
779
//-----------------------------------------------------------------
continue // // Returns a string representation of this family. public String toString() { String result = ""; for (String name : members) result += name + "\n"; return result; } Copyright © 2012 Pearson Education, Inc.
780
Outline Declaring and Using Arrays Arrays of Objects
Variable Length Parameter Lists Two-Dimensional Arrays Polygons and Polylines Mouse Events and Key Events Copyright © 2012 Pearson Education, Inc.
781
Two-Dimensional Arrays
A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions Copyright © 2012 Pearson Education, Inc.
782
Two-Dimensional Arrays
To be precise, in Java a two-dimensional array is an array of arrays A two-dimensional array is declared by specifying the size of each dimension separately: int[][] table = new int[12][50]; A array element is referenced using two index values: value = table[3][6] The array stored in one row can be specified using one index Copyright © 2012 Pearson Education, Inc.
783
Two-Dimensional Arrays
Expression Type Description table int[][] 2D array of integers, or array of integer arrays table[5] int[] array of integers table[5][12] int integer See TwoDArray.java See SodaSurvey.java Copyright © 2012 Pearson Education, Inc.
784
//********************************************************************
// TwoDArray.java Author: Lewis/Loftus // // Demonstrates the use of a two-dimensional array. public class TwoDArray { // // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. public static void main (String[] args) int[][] table = new int[5][10]; // Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table System.out.print (table[row][col] + "\t"); System.out.println(); } Copyright © 2012 Pearson Education, Inc.
785
//********************************************************************
// TwoDArray.java Author: Lewis/Loftus // // Demonstrates the use of a two-dimensional array. public class TwoDArray { // // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. public static void main (String[] args) int[][] table = new int[5][10]; // Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table System.out.print (table[row][col] + "\t"); System.out.println(); } Output Copyright © 2012 Pearson Education, Inc.
786
//********************************************************************
// SodaSurvey.java Author: Lewis/Loftus // // Demonstrates the use of a two-dimensional array. import java.text.DecimalFormat; public class SodaSurvey { // // Determines and prints the average of each row (soda) and each // column (respondent) of the survey scores. public static void main (String[] args) int[][] scores = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4}, {2, 4, 3, 4, 3, 3, 2, 1, 2, 2}, {3, 5, 4, 5, 5, 3, 2, 5, 5, 5}, {1, 1, 1, 3, 1, 2, 1, 3, 2, 4} }; final int SODAS = scores.length; final int PEOPLE = scores[0].length; int[] sodaSum = new int[SODAS]; int[] personSum = new int[PEOPLE]; continue Copyright © 2012 Pearson Education, Inc.
787
for (int soda=0; soda < SODAS; soda++)
continue for (int soda=0; soda < SODAS; soda++) for (int person=0; person < PEOPLE; person++) { sodaSum[soda] += scores[soda][person]; personSum[person] += scores[soda][person]; } DecimalFormat fmt = new DecimalFormat ("0.#"); System.out.println ("Averages:\n"); System.out.println ("Soda #" + (soda+1) + ": " + fmt.format ((float)sodaSum[soda]/PEOPLE)); System.out.println (); System.out.println ("Person #" + (person+1) + ": " + fmt.format ((float)personSum[person]/SODAS)); Copyright © 2012 Pearson Education, Inc.
788
Output Averages: Soda #1: 3.2 Soda #2: 2.6 Soda #3: 4.2 Soda #4: 1.9
Person #1: 2.2 Person #2: 3.5 Person #3: 3.2 Person #4: 3.5 Person #5: 2.5 Person #6: 3 Person #7: 2 Person #8: 2.8 Person #9: 3.2 Person #10: 3.8 continue for (int soda=0; soda < SODAS; soda++) for (int person=0; person < PEOPLE; person++) { sodaSum[soda] += scores[soda][person]; personSum[person] += scores[soda][person]; } DecimalFormat fmt = new DecimalFormat ("0.#"); System.out.println ("Averages:\n"); System.out.println ("Soda #" + (soda+1) + ": " + fmt.format ((float)sodaSum[soda]/PEOPLE)); System.out.println (); System.out.println ("Person #" + (person+1) + ": " + fmt.format ((float)personSum[person]/SODAS)); Copyright © 2012 Pearson Education, Inc.
789
Multidimensional Arrays
An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each dimension has its own length constant Because each dimension is an array of array references, the arrays within one dimension can be of different lengths these are sometimes called ragged arrays Copyright © 2012 Pearson Education, Inc.
790
Outline Declaring and Using Arrays Arrays of Objects
Variable Length Parameter Lists Two-Dimensional Arrays Polygons and Polylines Mouse Events and Key Events Copyright © 2012 Pearson Education, Inc.
791
Polygons and Polylines
Arrays can be helpful in graphics processing For example, they can be used to store a list of coordinates A polygon is a multisided, closed shape A polyline is similar to a polygon except that its endpoints do not meet, and it cannot be filled See Rocket.java See RocketPanel.java Copyright © 2012 Pearson Education, Inc.
792
//********************************************************************
// Rocket.java Author: Lewis/Loftus // // Demonstrates the use of polygons and polylines. import javax.swing.JFrame; public class Rocket { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Rocket"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); RocketPanel panel = new RocketPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
793
//********************************************************************
// Rocket.java Author: Lewis/Loftus // // Demonstrates the use of polygons and polylines. import javax.swing.JFrame; public class Rocket { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Rocket"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); RocketPanel panel = new RocketPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
794
//********************************************************************
// RocketPanel.java Author: Lewis/Loftus // // Demonstrates the use of polygons and polylines. import javax.swing.JPanel; import java.awt.*; public class RocketPanel extends JPanel { private int[] xRocket = {100, 120, 120, 130, 130, 70, 70, 80, 80}; private int[] yRocket = {15, 40, 115, 125, 150, 150, 125, 115, 40}; private int[] xWindow = {95, 105, 110, 90}; private int[] yWindow = {45, 45, 70, 70}; private int[] xFlame = {70, 70, 75, 80, 90, 100, 110, 115, 120, 130, 130}; private int[] yFlame = {155, 170, 165, 190, 170, 175, 160, 185, 160, 175, 155}; continue Copyright © 2012 Pearson Education, Inc.
795
//-----------------------------------------------------------------
continue // // Constructor: Sets up the basic characteristics of this panel. public RocketPanel() { setBackground (Color.black); setPreferredSize (new Dimension(200, 200)); } // Draws a rocket using polygons and polylines. public void paintComponent (Graphics page) super.paintComponent (page); page.setColor (Color.cyan); page.fillPolygon (xRocket, yRocket, xRocket.length); page.setColor (Color.gray); page.fillPolygon (xWindow, yWindow, xWindow.length); page.setColor (Color.red); page.drawPolyline (xFlame, yFlame, xFlame.length); Copyright © 2012 Pearson Education, Inc.
796
The Polygon Class The Polygon class can also be used to define and draw a polygon It is part of the java.awt package Versions of the overloaded drawPolygon and fillPolygon methods take a single Polygon object as a parameter instead of arrays of coordinates Copyright © 2012 Pearson Education, Inc.
797
Outline Declaring and Using Arrays Arrays of Objects
Variable Length Parameter Lists Two-Dimensional Arrays Polygons and Polylines Mouse Events and Key Events Copyright © 2012 Pearson Education, Inc.
798
Mouse Events Events related to the mouse are separated into mouse events and mouse motion events Mouse Events: mouse pressed the mouse button is pressed down mouse released the mouse button is released mouse clicked the mouse button is pressed down and released without moving the mouse in between mouse entered the mouse pointer is moved onto (over) a component mouse exited the mouse pointer is moved off of a component
799
Mouse Events Mouse motion events:
Listeners for mouse events are created using the MouseListener and MouseMotionListener interfaces A MouseEvent object is passed to the appropriate method when a mouse event occurs mouse moved the mouse is moved mouse dragged the mouse is moved while the mouse button is pressed down Copyright © 2012 Pearson Education, Inc.
800
Mouse Events For a given program, we may only care about one or two mouse events To satisfy the implementation of a listener interface, empty methods must be provided for unused events See Dots.java See DotsPanel.java Copyright © 2012 Pearson Education, Inc.
801
//********************************************************************
// Dots.java Author: Lewis/Loftus // // Demonstrates mouse events. import javax.swing.JFrame; public class Dots { // // Creates and displays the application frame. public static void main (String[] args) JFrame frame = new JFrame ("Dots"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new DotsPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
802
//********************************************************************
// Dots.java Author: Lewis/Loftus // // Demonstrates mouse events. import javax.swing.JFrame; public class Dots { // // Creates and displays the application frame. public static void main (String[] args) JFrame frame = new JFrame ("Dots"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new DotsPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
803
//********************************************************************
// DotsPanel.java Author: Lewis/Loftus // // Represents the primary panel for the Dots program. import java.util.ArrayList; import javax.swing.JPanel; import java.awt.*; import java.awt.event.*; public class DotsPanel extends JPanel { private final int SIZE = 6; // radius of each dot private ArrayList<Point> pointList; continue Copyright © 2012 Pearson Education, Inc.
804
//-----------------------------------------------------------------
continue // // Constructor: Sets up this panel to listen for mouse events. public DotsPanel() { pointList = new ArrayList<Point>(); addMouseListener (new DotsListener()); setBackground (Color.black); setPreferredSize (new Dimension(300, 200)); } // Draws all of the dots stored in the list. public void paintComponent (Graphics page) super.paintComponent(page); page.setColor (Color.green); for (Point spot : pointList) page.fillOval (spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2); page.drawString ("Count: " + pointList.size(), 5, 15); Copyright © 2012 Pearson Education, Inc.
805
//*****************************************************************
continue //***************************************************************** // Represents the listener for mouse events. private class DotsListener implements MouseListener { // // Adds the current point to the list of points and redraws // the panel whenever the mouse button is pressed. public void mousePressed (MouseEvent event) pointList.add(event.getPoint()); repaint(); } // Provide empty definitions for unused event methods. public void mouseClicked (MouseEvent event) {} public void mouseReleased (MouseEvent event) {} public void mouseEntered (MouseEvent event) {} public void mouseExited (MouseEvent event) {} Copyright © 2012 Pearson Education, Inc.
806
Mouse Events Rubberbanding is the visual effect in which a shape is "stretched" as it is drawn using the mouse The following example continually redraws a line as the mouse is dragged See RubberLines.java See RubberLinesPanel.java Copyright © 2012 Pearson Education, Inc.
807
//********************************************************************
// RubberLines.java Author: Lewis/Loftus // // Demonstrates mouse events and rubberbanding. import javax.swing.JFrame; public class RubberLines { // // Creates and displays the application frame. public static void main (String[] args) JFrame frame = new JFrame ("Rubber Lines"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new RubberLinesPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
808
//********************************************************************
// RubberLines.java Author: Lewis/Loftus // // Demonstrates mouse events and rubberbanding. import javax.swing.JFrame; public class RubberLines { // // Creates and displays the application frame. public static void main (String[] args) JFrame frame = new JFrame ("Rubber Lines"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new RubberLinesPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
809
//********************************************************************
// RubberLinesPanel.java Author: Lewis/Loftus // // Represents the primary drawing panel for the RubberLines program. import javax.swing.JPanel; import java.awt.*; import java.awt.event.*; public class RubberLinesPanel extends JPanel { private Point point1 = null, point2 = null; // // Constructor: Sets up this panel to listen for mouse events. public RubberLinesPanel() LineListener listener = new LineListener(); addMouseListener (listener); addMouseMotionListener (listener); setBackground (Color.black); setPreferredSize (new Dimension(400, 200)); } continue Copyright © 2012 Pearson Education, Inc.
810
//-----------------------------------------------------------------
continue // // Draws the current line from the initial mouse-pressed point to // the current position of the mouse. public void paintComponent (Graphics page) { super.paintComponent (page); page.setColor (Color.yellow); if (point1 != null && point2 != null) page.drawLine (point1.x, point1.y, point2.x, point2.y); } //***************************************************************** // Represents the listener for all mouse events. private class LineListener implements MouseListener, MouseMotionListener // // Captures the initial position at which the mouse button is // pressed. public void mousePressed (MouseEvent event) point1 = event.getPoint(); Copyright © 2012 Pearson Education, Inc.
811
//--------------------------------------------------------------
continue // // Gets the current position of the mouse as it is dragged and // redraws the line to create the rubberband effect. public void mouseDragged (MouseEvent event) { point2 = event.getPoint(); repaint(); } // Provide empty definitions for unused event methods. public void mouseClicked (MouseEvent event) {} public void mouseReleased (MouseEvent event) {} public void mouseEntered (MouseEvent event) {} public void mouseExited (MouseEvent event) {} public void mouseMoved (MouseEvent event) {} Copyright © 2012 Pearson Education, Inc.
812
Key Events A key event is generated when the user types on the keyboard Listeners for key events are created by implementing the KeyListener interface A KeyEvent object is passed to the appropriate method when a key event occurs key pressed a key on the keyboard is pressed down key released a key on the keyboard is released key typed a key on the keyboard is pressed down and released Copyright © 2012 Pearson Education, Inc.
813
Key Events The component that generates a key event is the one that has the current keyboard focus Constants in the KeyEvent class can be used to determine which key was pressed The following example "moves" an image of an arrow as the user types the keyboard arrow keys See Direction.java See DirectionPanel.java Copyright © 2012 Pearson Education, Inc.
814
//********************************************************************
// Direction.java Author: Lewis/Loftus // // Demonstrates key events. import javax.swing.JFrame; public class Direction { // // Creates and displays the application frame. public static void main (String[] args) JFrame frame = new JFrame ("Direction"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new DirectionPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
815
//********************************************************************
// Direction.java Author: Lewis/Loftus // // Demonstrates key events. import javax.swing.JFrame; public class Direction { // // Creates and displays the application frame. public static void main (String[] args) JFrame frame = new JFrame ("Direction"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new DirectionPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
816
//********************************************************************
// DirectionPanel.java Author: Lewis/Loftus // // Represents the primary display panel for the Direction program. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DirectionPanel extends JPanel { private final int WIDTH = 300, HEIGHT = 200; private final int JUMP = 10; // increment for image movement private final int IMAGE_SIZE = 31; private ImageIcon up, down, right, left, currentImage; private int x, y; continue Copyright © 2012 Pearson Education, Inc.
817
//-----------------------------------------------------------------
continue // // Constructor: Sets up this panel and loads the images. public DirectionPanel() { addKeyListener (new DirectionListener()); x = WIDTH / 2; y = HEIGHT / 2; up = new ImageIcon ("arrowUp.gif"); down = new ImageIcon ("arrowDown.gif"); left = new ImageIcon ("arrowLeft.gif"); right = new ImageIcon ("arrowRight.gif"); currentImage = right; setBackground (Color.black); setPreferredSize (new Dimension(WIDTH, HEIGHT)); setFocusable(true); } Copyright © 2012 Pearson Education, Inc.
818
//-----------------------------------------------------------------
continue // // Draws the image in the current location. public void paintComponent (Graphics page) { super.paintComponent (page); currentImage.paintIcon (this, page, x, y); } //***************************************************************** // Represents the listener for keyboard activity. private class DirectionListener implements KeyListener // // Responds to the user pressing arrow keys by adjusting the // image and image location accordingly. public void keyPressed (KeyEvent event) switch (event.getKeyCode()) case KeyEvent.VK_UP: currentImage = up; y -= JUMP; break; Copyright © 2012 Pearson Education, Inc.
819
case KeyEvent.VK_DOWN: currentImage = down; y += JUMP; break;
continue case KeyEvent.VK_DOWN: currentImage = down; y += JUMP; break; case KeyEvent.VK_LEFT: currentImage = left; x -= JUMP; case KeyEvent.VK_RIGHT: currentImage = right; x += JUMP; } repaint(); // // Provide empty definitions for unused event methods. public void keyTyped (KeyEvent event) {} public void keyReleased (KeyEvent event) {} Copyright © 2012 Pearson Education, Inc.
820
Summary Chapter 8 has focused on: array declaration and use
bounds checking and capacity arrays that store object references variable length parameter lists multidimensional arrays polygons and polylines mouse events and keyboard events Copyright © 2012 Pearson Education, Inc.
821
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 9 Inheritance Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
822
Inheritance Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 9 focuses on: deriving new classes from existing classes the protected modifier creating class hierarchies abstract classes indirect visibility of inherited members designing for inheritance the GUI component class hierarchy extending listener adapter classes the Timer class Copyright © 2012 Pearson Education, Inc.
823
Outline Creating Subclasses Overriding Methods Class Hierarchies
Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright © 2012 Pearson Education, Inc.
824
Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined by the parent class Copyright © 2012 Pearson Education, Inc.
825
Inheritance Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled triangular arrowhead pointing to the parent class Vehicle Car Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the parent Copyright © 2012 Pearson Education, Inc.
826
Inheritance A programmer can tailor a derived class as needed by adding new variables or methods, or by modifying the inherited ones One benefit of inheritance is software reuse By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software Copyright © 2012 Pearson Education, Inc.
827
Deriving Subclasses In Java, we use the reserved word extends to establish an inheritance relationship public class Car extends Vehicle { // class contents } See Words.java See Book.java See Dictionary.java Copyright © 2012 Pearson Education, Inc.
828
//********************************************************************
// Words.java Author: Lewis/Loftus // // Demonstrates the use of an inherited method. public class Words { // // Instantiates a derived class and invokes its inherited and // local methods. public static void main (String[] args) Dictionary webster = new Dictionary(); System.out.println ("Number of pages: " + webster.getPages()); System.out.println ("Number of definitions: " + webster.getDefinitions()); System.out.println ("Definitions per page: " + webster.computeRatio()); } Copyright © 2012 Pearson Education, Inc.
829
Output Number of pages: 1500 Number of definitions: 52500
Definitions per page: 35.0 //******************************************************************** // Words.java Author: Lewis/Loftus // // Demonstrates the use of an inherited method. public class Words { // // Instantiates a derived class and invokes its inherited and // local methods. public static void main (String[] args) Dictionary webster = new Dictionary(); System.out.println ("Number of pages: " + webster.getPages()); System.out.println ("Number of definitions: " + webster.getDefinitions()); System.out.println ("Definitions per page: " + webster.computeRatio()); } Copyright © 2012 Pearson Education, Inc.
830
//********************************************************************
// Book.java Author: Lewis/Loftus // // Represents a book. Used as the parent of a derived class to // demonstrate inheritance. public class Book { protected int pages = 1500; // // Pages mutator. public void setPages (int numPages) pages = numPages; } // Pages accessor. public int getPages () return pages; Copyright © 2012 Pearson Education, Inc.
831
//********************************************************************
// Dictionary.java Author: Lewis/Loftus // // Represents a dictionary, which is a book. Used to demonstrate // inheritance. public class Dictionary extends Book { private int definitions = 52500; // // Prints a message using both local and inherited values. public double computeRatio () return (double) definitions/pages; } continue Copyright © 2012 Pearson Education, Inc.
832
//----------------------------------------------------------------
continue // // Definitions mutator. public void setDefinitions (int numDefinitions) { definitions = numDefinitions; } // Definitions accessor. public int getDefinitions () return definitions; Copyright © 2012 Pearson Education, Inc.
833
The protected Modifier
Visibility modifiers affect the way that class members can be used in a child class Variables and methods declared with private visibility cannot be referenced in a child class They can be referenced in the child class if they are declared with public visibility -- but public variables violate the principle of encapsulation There is a third visibility modifier that helps in inheritance situations: protected Copyright © 2012 Pearson Education, Inc.
834
The protected Modifier
The protected modifier allows a child class to reference a variable or method in the child class It provides more encapsulation than public visibility, but is not as tightly encapsulated as private visibility A protected variable is also visible to any class in the same package as the parent class See Appendix E for details of all Java modifiers Protected variables and methods can be shown with a # symbol preceding them in UML diagrams Copyright © 2012 Pearson Education, Inc.
835
Class Diagram for Words
Book # pages : int + pageMessage() : void Dictionary - definitions : int + definitionMessage() : void Words + main (args : String[]) : void Copyright © 2012 Pearson Education, Inc.
836
The super Reference Constructors are not inherited, even though they have public visibility Yet we often want to use the parent's constructor to set up the "parent's part" of the object The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor A child’s constructor is responsible for calling the parent’s constructor Copyright © 2012 Pearson Education, Inc.
837
The super Reference The first line of a child’s constructor should use the super reference to call the parent’s constructor The super reference can also be used to reference other variables and methods defined in the parent’s class See Words2.java See Book2.java See Dictionary2.java Copyright © 2012 Pearson Education, Inc.
838
//********************************************************************
// Words2.java Author: Lewis/Loftus // // Demonstrates the use of the super reference. public class Words2 { // // Instantiates a derived class and invokes its inherited and // local methods. public static void main (String[] args) Dictionary2 webster = new Dictionary2 (1500, 52500); System.out.println ("Number of pages: " + webster.getPages()); System.out.println ("Number of definitions: " + webster.getDefinitions()); System.out.println ("Definitions per page: " + webster.computeRatio()); } Copyright © 2012 Pearson Education, Inc.
839
Output Number of pages: 1500 Number of definitions: 52500
Definitions per page: 35.0 //******************************************************************** // Words2.java Author: Lewis/Loftus // // Demonstrates the use of the super reference. public class Words2 { // // Instantiates a derived class and invokes its inherited and // local methods. public static void main (String[] args) Dictionary2 webster = new Dictionary2 (1500, 52500); System.out.println ("Number of pages: " + webster.getPages()); System.out.println ("Number of definitions: " + webster.getDefinitions()); System.out.println ("Definitions per page: " + webster.computeRatio()); } Copyright © 2012 Pearson Education, Inc.
840
//********************************************************************
// Book2.java Author: Lewis/Loftus // // Represents a book. Used as the parent of a derived class to // demonstrate inheritance and the use of the super reference. public class Book2 { protected int pages; // // Constructor: Sets up the book with the specified number of // pages. public Book2 (int numPages) pages = numPages; } continue Copyright © 2012 Pearson Education, Inc.
841
//----------------------------------------------------------------
continue // // Pages mutator. public void setPages (int numPages) { pages = numPages; } // Pages accessor. public int getPages () return pages; Copyright © 2012 Pearson Education, Inc.
842
//********************************************************************
// Dictionary2.java Author: Lewis/Loftus // // Represents a dictionary, which is a book. Used to demonstrate // the use of the super reference. public class Dictionary2 extends Book2 { private int definitions; // // Constructor: Sets up the dictionary with the specified number // of pages and definitions. public Dictionary2 (int numPages, int numDefinitions) super(numPages); definitions = numDefinitions; } continue Copyright © 2012 Pearson Education, Inc.
843
//-----------------------------------------------------------------
continue // // Prints a message using both local and inherited values. public double computeRatio () { return (double) definitions/pages; } // // Definitions mutator. public void setDefinitions (int numDefinitions) definitions = numDefinitions; // Definitions accessor. public int getDefinitions () return definitions; Copyright © 2012 Pearson Education, Inc.
844
Multiple Inheritance Java supports single inheritance, meaning that a derived class can have only one parent class Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents Collisions, such as the same variable name in two parents, have to be resolved Multiple inheritance is generally not needed, and Java does not support it Copyright © 2012 Pearson Education, Inc.
845
Outline Creating Subclasses Overriding Methods Class Hierarchies
Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright © 2012 Pearson Education, Inc.
846
Overriding Methods A child class can override the definition of an inherited method in favor of its own The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked See Messages.java See Thought.java See Advice.java Copyright © 2012 Pearson Education, Inc.
847
//********************************************************************
// Messages.java Author: Lewis/Loftus // // Demonstrates the use of an overridden method. public class Messages { // // Creates two objects and invokes the message method in each. public static void main (String[] args) Thought parked = new Thought(); Advice dates = new Advice(); parked.message(); dates.message(); // overridden } Copyright © 2012 Pearson Education, Inc.
848
Output I feel like I'm diagonally parked in a parallel universe.
Warning: Dates in calendar are closer than they appear. //******************************************************************** // Messages.java Author: Lewis/Loftus // // Demonstrates the use of an overridden method. public class Messages { // // Creates two objects and invokes the message method in each. public static void main (String[] args) Thought parked = new Thought(); Advice dates = new Advice(); parked.message(); dates.message(); // overridden } Copyright © 2012 Pearson Education, Inc.
849
//********************************************************************
// Thought.java Author: Lewis/Loftus // // Represents a stray thought. Used as the parent of a derived // class to demonstrate the use of an overridden method. public class Thought { // // Prints a message. public void message() System.out.println ("I feel like I'm diagonally parked in a " + "parallel universe."); System.out.println(); } Copyright © 2012 Pearson Education, Inc.
850
//********************************************************************
// Advice.java Author: Lewis/Loftus // // Represents some thoughtful advice. Used to demonstrate the use // of an overridden method. public class Advice extends Thought { // // Prints a message. This method overrides the parent's version. public void message() System.out.println ("Warning: Dates in calendar are closer " + "than they appear."); System.out.println(); super.message(); // explicitly invokes the parent's version } Copyright © 2012 Pearson Education, Inc.
851
Overriding A method in the parent class can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden The concept of overriding can be applied to data and is called shadowing variables Shadowing variables should be avoided because it tends to cause unnecessarily confusing code Copyright © 2012 Pearson Education, Inc.
852
Overloading vs. Overriding
Overloading deals with multiple methods with the same name in the same class, but with different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading lets you define a similar operation in different ways for different parameters Overriding lets you define a similar operation in different ways for different object types Copyright © 2012 Pearson Education, Inc.
853
Quick Check True or False? A child class may define a method with
the same name as a method in the parent. A child class can override the constructor of the parent class. A child class cannot override a final method It is considered poor design when a child class overrides a method from the parent. A child class may define a variable with the same name as a variable in the parent. Copyright © 2012 Pearson Education, Inc.
854
Quick Check True or False? A child class may define a method with True
the same name as a method in the parent. A child class can override the constructor of the parent class. A child class cannot override a final method It is considered poor design when a child class overrides a method from the parent. A child class may define a variable with the same name as a variable in the parent. True False True, but shouldn't Copyright © 2012 Pearson Education, Inc.
855
Outline Creating Subclasses Overriding Methods Class Hierarchies
Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright © 2012 Pearson Education, Inc.
856
Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Copyright © 2012 Pearson Education, Inc.
857
Class Hierarchies Two children of the same parent are called siblings
Common features should be put as high in the hierarchy as is reasonable An inherited member is passed continually down the line Therefore, a child class inherits from all its ancestor classes There is no single class hierarchy that is appropriate for all situations Copyright © 2012 Pearson Education, Inc.
858
The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies Copyright © 2012 Pearson Education, Inc.
859
The Object Class The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we define the toString method, we are actually overriding an inherited definition The toString method in the Object class is defined to return a string that contains the name of the object’s class along with a hash code Copyright © 2012 Pearson Education, Inc.
860
The Object Class The equals method of the Object class returns true if two references are aliases We can override equals in any class to define equality in some more appropriate way As we've seen, the String class defines the equals method to return true if two String objects contain the same characters The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version Copyright © 2012 Pearson Education, Inc.
861
Abstract Classes An abstract class is a placeholder in a class hierarchy that represents a generic concept An abstract class cannot be instantiated We use the modifier abstract on the class header to declare a class as abstract: public abstract class Product { // class contents } Copyright © 2012 Pearson Education, Inc.
862
Abstract Classes An abstract class often contains abstract methods with no definitions (like an interface) Unlike an interface, the abstract modifier must be applied to each abstract method Also, an abstract class typically contains non- abstract methods with full definitions A class declared as abstract does not have to contain abstract methods -- simply declaring it as abstract makes it so Copyright © 2012 Pearson Education, Inc.
863
Abstract Classes The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract An abstract method cannot be defined as final or static The use of abstract classes is an important element of software design – it allows us to establish common elements in a hierarchy that are too general to instantiate Copyright © 2012 Pearson Education, Inc.
864
Interface Hierarchies
Inheritance can be applied to interfaces That is, one interface can be derived from another interface The child interface inherits all abstract methods of the parent A class implementing the child interface must define all methods from both interfaces Class hierarchies and interface hierarchies are distinct (they do not overlap) Copyright © 2012 Pearson Education, Inc.
865
Quick Check What are some methods defined by the Object class?
What is an abstract class? Copyright © 2012 Pearson Education, Inc.
866
Quick Check What are some methods defined by the Object class?
What is an abstract class? String toString() boolean equals(Object obj) Object clone() An abstract class is a placeholder in the class hierarchy, defining a general concept and gathering elements common to all derived classes. An abstract class cannot be instantiated. Copyright © 2012 Pearson Education, Inc.
867
Outline Creating Subclasses Overriding Methods Class Hierarchies
Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright © 2012 Pearson Education, Inc.
868
Visibility Revisited It's important to understand one subtle issue related to inheritance and visibility All variables and methods of a parent class, even private members, are inherited by its children As we've mentioned, private members cannot be referenced by name in the child class However, private members inherited by child classes exist and can be referenced indirectly Copyright © 2012 Pearson Education, Inc.
869
Visibility Revisited Because the parent can refer to the private member, the child can reference it indirectly using its parent's methods The super reference can be used to refer to the parent class, even if no object of the parent exists See FoodAnalyzer.java See FoodItem.java See Pizza.java Copyright © 2012 Pearson Education, Inc.
870
//********************************************************************
// FoodAnalyzer.java Author: Lewis/Loftus // // Demonstrates indirect access to inherited private members. public class FoodAnalyzer { // // Instantiates a Pizza object and prints its calories per // serving. public static void main (String[] args) Pizza special = new Pizza (275); System.out.println ("Calories per serving: " + special.caloriesPerServing()); } Copyright © 2012 Pearson Education, Inc.
871
Output Calories per serving: 309
//******************************************************************** // FoodAnalyzer.java Author: Lewis/Loftus // // Demonstrates indirect access to inherited private members. public class FoodAnalyzer { // // Instantiates a Pizza object and prints its calories per // serving. public static void main (String[] args) Pizza special = new Pizza (275); System.out.println ("Calories per serving: " + special.caloriesPerServing()); } Output Calories per serving: 309 Copyright © 2012 Pearson Education, Inc.
872
//********************************************************************
// FoodItem.java Author: Lewis/Loftus // // Represents an item of food. Used as the parent of a derived class // to demonstrate indirect referencing. public class FoodItem { final private int CALORIES_PER_GRAM = 9; private int fatGrams; protected int servings; // // Sets up this food item with the specified number of fat grams // and number of servings. public FoodItem (int numFatGrams, int numServings) fatGrams = numFatGrams; servings = numServings; } continue Copyright © 2012 Pearson Education, Inc.
873
//-----------------------------------------------------------------
continue // // Computes and returns the number of calories in this food item // due to fat. private int calories() { return fatGrams * CALORIES_PER_GRAM; } // Computes and returns the number of fat calories per serving. public int caloriesPerServing() return (calories() / servings); Copyright © 2012 Pearson Education, Inc.
874
//********************************************************************
// Pizza.java Author: Lewis/Loftus // // Represents a pizza, which is a food item. Used to demonstrate // indirect referencing through inheritance. public class Pizza extends FoodItem { // // Sets up a pizza with the specified amount of fat (assumes // eight servings). public Pizza (int fatGrams) super (fatGrams, 8); } Copyright © 2012 Pearson Education, Inc.
875
Outline Creating Subclasses Overriding Methods Class Hierarchies
Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright © 2012 Pearson Education, Inc.
876
Designing for Inheritance
As we've discussed, taking the time to create a good software design reaps long-term benefits Inheritance issues are an important part of an object-oriented design Properly designed inheritance relationships can contribute greatly to the elegance, maintainability, and reuse of the software Let's summarize some of the issues regarding inheritance that relate to a good software design Copyright © 2012 Pearson Education, Inc.
877
Inheritance Design Issues
Every derivation should be an is-a relationship Think about the potential future of a class hierarchy, and design classes to be reusable and flexible Find common characteristics of classes and push them as high in the class hierarchy as appropriate Override methods as appropriate to tailor or change the functionality of a child Add new variables to children, but don't redefine (shadow) inherited variables Copyright © 2012 Pearson Education, Inc.
878
Inheritance Design Issues
Allow each class to manage its own data; use the super reference to invoke the parent's constructor to set up its data Override general methods such as toString and equals with appropriate definitions Use abstract classes to represent general concepts that derived classes have in common Use visibility modifiers carefully to provide needed access without violating encapsulation Copyright © 2012 Pearson Education, Inc.
879
Restricting Inheritance
If the final modifier is applied to a method, that method cannot be overridden in any derived classes If the final modifier is applied to an entire class, then that class cannot be used to derive any children at all Therefore, an abstract class cannot be declared as final Copyright © 2012 Pearson Education, Inc.
880
Outline Creating Subclasses Overriding Methods Class Hierarchies
Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright © 2012 Pearson Education, Inc.
881
The Component Class Hierarchy
The Java classes that define GUI components are part of a class hierarchy Swing GUI components typically are derived from the JComponent class which is derived from the Container class which is derived from the Component class Many Swing components can serve as (limited) containers, because they are derived from the Container class For example, a JLabel object can contain an ImageIcon Copyright © 2012 Pearson Education, Inc.
882
Partial Component Class Hierarchy
Copyright © 2012 Pearson Education, Inc.
883
The Component Class Hierarchy
An applet is another good example of inheritance Recall that when we define an applet, we extend the JApplet class The JApplet class already handles all the details about applet creation and execution, including: interaction with a Web browser accepting applet parameters through HTML enforcing security restrictions Copyright © 2012 Pearson Education, Inc.
884
The Component Class Hierarchy
Our applet classes only have to deal with issues that specifically relate to what our particular applet will do When we define paintComponent method of an applet, we are actually overriding a method defined originally in the JComponent class and inherited by the JApplet class Copyright © 2012 Pearson Education, Inc.
885
Event Adapter Classes Inheritance also gives us a alternate technique for creating listener classes We've seen that listener classes can be created by implementing a particular interface, such as MouseListener We can also create a listener class by extending an event adapter class If a listener interface has more than one method, it has a corresponding adapter class, such as the MouseAdapter class Copyright © 2012 Pearson Education, Inc.
886
Event Adapter Classes Each adapter class implements the corresponding listener, providing empty method definitions When you derive a listener class from an adapter class, you only need to override the event methods that pertain to the program Empty definitions for unused event methods are automatically provided via inheritance See OffCenter.java See OffCenterPanel.java Copyright © 2012 Pearson Education, Inc.
887
//********************************************************************
// OffCenter.java Author: Lewis/Loftus // // Demonstrates the use of an event adapter class. import javax.swing.*; public class OffCenter { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Off Center"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new OffCenterPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
888
//********************************************************************
// OffCenter.java Author: Lewis/Loftus // // Demonstrates the use of an event adapter class. import javax.swing.*; public class OffCenter { // // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Off Center"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new OffCenterPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
889
//********************************************************************
// OffCenterPanel.java Author: Lewis/Loftus // // Represents the primary drawing panel for the OffCenter program. import java.awt.*; import java.awt.event.*; import java.text.DecimalFormat; import javax.swing.*; public class OffCenterPanel extends JPanel { private final int WIDTH=300, HEIGHT=300; private DecimalFormat fmt; private Point current; private int centerX, centerY; private double length; continue Copyright © 2012 Pearson Education, Inc.
890
//-----------------------------------------------------------------
continue // // Constructor: Sets up the panel and necessary data. public OffCenterPanel() { addMouseListener (new OffCenterListener()); centerX = WIDTH / 2; centerY = HEIGHT / 2; fmt = new DecimalFormat ("0.##"); setPreferredSize (new Dimension(WIDTH, HEIGHT)); setBackground (Color.yellow); } Copyright © 2012 Pearson Education, Inc.
891
//-----------------------------------------------------------------
continue // // Draws a line from the mouse pointer to the center point of // the applet and displays the distance. public void paintComponent (Graphics page) { super.paintComponent (page); page.setColor (Color.black); page.drawOval (centerX-3, centerY-3, 6, 6); if (current != null) page.drawLine (current.x, current.y, centerX, centerY); page.drawString ("Distance: " + fmt.format(length), 10, 15); } Copyright © 2012 Pearson Education, Inc.
892
//*****************************************************************
continue //***************************************************************** // Represents the listener for mouse events. Demonstrates the // ability to extend an adaptor class. private class OffCenterListener extends MouseAdapter { // // Computes the distance from the mouse pointer to the center // point of the applet. public void mouseClicked (MouseEvent event) current = event.getPoint(); length = Math.sqrt(Math.pow((current.x-centerX), 2) + Math.pow((current.y-centerY), 2)); repaint(); } Copyright © 2012 Pearson Education, Inc.
893
Outline Creating Subclasses Overriding Methods Class Hierarchies
Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright © 2012 Pearson Education, Inc.
894
The Timer Class The Timer class of the javax.swing package is a GUI component, but it has no visual representation A Timer object generates an action event at specified intervals Timers can be used to manage any events that are based on a timed interval, such as an animation To create the illusion of movement, we use a timer to change the scene after an appropriate delay Copyright © 2012 Pearson Education, Inc.
895
The Timer Class The start and stop methods of the Timer class start and stop the timer The delay can be set using the Timer constructor or using the setDelay method See Rebound.java See ReboundPanel.java Copyright © 2012 Pearson Education, Inc.
896
//********************************************************************
// Rebound.java Author: Lewis/Loftus // // Demonstrates an animation and the use of the Timer class. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Rebound { // // Displays the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Rebound"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new ReboundPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
897
//********************************************************************
// Rebound.java Author: Lewis/Loftus // // Demonstrates an animation and the use of the Timer class. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Rebound { // // Displays the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Rebound"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new ReboundPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
898
//********************************************************************
// ReboundPanel.java Author: Lewis/Loftus // // Represents the primary panel for the Rebound program. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ReboundPanel extends JPanel { private final int WIDTH = 300, HEIGHT = 100; private final int DELAY = 20, IMAGE_SIZE = 35; private ImageIcon image; private Timer timer; private int x, y, moveX, moveY; continue Copyright © 2012 Pearson Education, Inc.
899
//********************************************************************
// ReboundPanel.java Author: Lewis/Loftus // // Represents the primary panel for the Rebound program. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ReboundPanel extends JPanel { private final int WIDTH = 300, HEIGHT = 100; private final int DELAY = 20, IMAGE_SIZE = 35; private ImageIcon image; private Timer timer; private int x, y, moveX, moveY; continue Copyright © 2012 Pearson Education, Inc.
900
//-----------------------------------------------------------------
continue // // Sets up the panel, including the timer for the animation. public ReboundPanel() { timer = new Timer(DELAY, new ReboundListener()); image = new ImageIcon ("happyFace.gif"); x = 0; y = 40; moveX = moveY = 3; setPreferredSize (new Dimension(WIDTH, HEIGHT)); setBackground (Color.black); timer.start(); } // Draws the image in the current location. public void paintComponent (Graphics page) super.paintComponent (page); image.paintIcon (this, page, x, y); Copyright © 2012 Pearson Education, Inc.
901
//*****************************************************************
continue //***************************************************************** // Represents the action listener for the timer. private class ReboundListener implements ActionListener { // // Updates the position of the image and possibly the direction // of movement whenever the timer fires an action event. public void actionPerformed (ActionEvent event) x += moveX; y += moveY; if (x <= 0 || x >= WIDTH-IMAGE_SIZE) moveX = moveX * -1; if (y <= 0 || y >= HEIGHT-IMAGE_SIZE) moveY = moveY * -1; repaint(); } Copyright © 2012 Pearson Education, Inc.
902
Summary Chapter 9 focused on:
deriving new classes from existing classes the protected modifier creating class hierarchies abstract classes indirect visibility of inherited members designing for inheritance the GUI component class hierarchy extending listener adapter classes the Timer class Copyright © 2012 Pearson Education, Inc.
903
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 10 Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
904
Polymorphism Polymorphism is an object-oriented concept that allows us to create versatile software designs Chapter 10 focuses on: defining polymorphism and its benefits using inheritance to create polymorphic references using interfaces to create polymorphic references using polymorphism to implement sorting and searching algorithms additional GUI components Copyright © 2012 Pearson Education, Inc.
905
Outline Late Binding Polymorphism via Inheritance
Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders Copyright © 2012 Pearson Education, Inc.
906
Binding Consider the following method invocation: obj.doIt();
At some point, this invocation is bound to the definition of the method that it invokes If this binding occurred at compile time, then that line of code would call the same method every time However, Java defers method binding until run time -- this is called dynamic binding or late binding Copyright © 2012 Pearson Education, Inc.
907
Polymorphism The term polymorphism literally means "having many forms"
A polymorphic reference is a variable that can refer to different types of objects at different points in time The method called through a polymorphic reference can change from one invocation to the next All object references in Java are potentially polymorphic Copyright © 2012 Pearson Education, Inc.
908
Polymorphism Suppose we create the following reference variable:
Occupation job; This reference can point to an Occupation object, or to any object of any compatible type This compatibility can be established using inheritance or using interfaces Careful use of polymorphic references can lead to elegant, robust software designs Copyright © 2012 Pearson Education, Inc.
909
Outline Late Binding Polymorphism via Inheritance
Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders Copyright © 2012 Pearson Education, Inc.
910
References and Inheritance
An object reference can refer to an object of any class related to it by inheritance For example, if Holiday is the superclass of Christmas, then a Holiday reference could be used to refer to a Christmas object Holiday Christmas Holiday day; day = new Christmas(); Copyright © 2012 Pearson Education, Inc.
911
References and Inheritance
These type compatibility rules are just an extension of the is-a relationship established by inheritance Assigning a Christmas object to a Holiday reference is fine because Christmas is-a holiday Assigning a child object to a parent reference can be performed by simple assignment Assigning an parent object to a child reference can be done also, but must be done with a cast After all, Christmas is a holiday but not all holidays are Christmas Copyright © 2012 Pearson Education, Inc.
912
Polymorphism via Inheritance
Now suppose the Holiday class has a method called celebrate, and Christmas overrides it What method is invoked by the following? day.celebrate(); The type of the object being referenced, not the reference type, determines which method is invoked If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes that version Copyright © 2012 Pearson Education, Inc.
913
Polymorphism via Inheritance
Note that the compiler restricts invocations based on the type of the reference So if Christmas had a method called getTree that Holiday didn't have, the following would cause a compiler error: day.getTree(); // compiler error Remember, the compiler doesn't "know" which type of holiday is being referenced A cast can be used to allow the call: ((Christmas)day).getTree(); Copyright © 2012 Pearson Education, Inc.
914
Quick Check If MusicPlayer is the parent of CDPlayer, are the following assignments valid? MusicPlayer mplayer = new CDPlayer(); CDPlayer cdplayer = new MusicPlayer(); Copyright © 2012 Pearson Education, Inc.
915
Quick Check If MusicPlayer is the parent of CDPlayer, are the following assignments valid? MusicPlayer mplayer = new CDPlayer(); CDPlayer cdplayer = new MusicPlayer(); Yes, because a CDPlayer is-a MusicPlayer No, you'd have to use a cast (and you shouldn't knowingly assign a super class object to a subclass reference) Copyright © 2012 Pearson Education, Inc.
916
Polymorphism via Inheritance
Consider the following class hierarchy: StaffMember Executive Hourly Volunteer Employee Copyright © 2012 Pearson Education, Inc.
917
Polymorphism via Inheritance
Let's look at an example that pays a set of diverse employees using a polymorphic method See Firm.java See Staff.java See StaffMember.java See Volunteer.java See Employee.java See Executive.java See Hourly.java Copyright © 2012 Pearson Education, Inc.
918
//********************************************************************
// Firm.java Author: Lewis/Loftus // // Demonstrates polymorphism via inheritance. public class Firm { // // Creates a staff of employees for a firm and pays them. public static void main (String[] args) Staff personnel = new Staff(); personnel.payday(); } Copyright © 2012 Pearson Education, Inc.
919
Output Output (continued) Name: Sam Address: 123 Main Line
Phone: Social Security Number: Paid: Name: Carla Address: 456 Off Line Phone: Social Security Number: Paid: Name: Woody Address: 789 Off Rocker Phone: Social Security Number: Paid: Output (continued) Name: Diane Address: 678 Fifth Ave. Phone: Social Security Number: Current hours: 40 Paid: 422.0 Name: Norm Address: 987 Suds Blvd. Phone: Thanks! Name: Cliff Address: 321 Duds Lane Phone: //******************************************************************** // Firm.java Author: Lewis/Loftus // // Demonstrates polymorphism via inheritance. public class Firm { // // Creates a staff of employees for a firm and pays them. public static void main (String[] args) Staff personnel = new Staff(); personnel.payday(); } Copyright © 2012 Pearson Education, Inc.
920
//********************************************************************
// Staff.java Author: Lewis/Loftus // // Represents the personnel staff of a particular business. public class Staff { private StaffMember[] staffList; // // Constructor: Sets up the list of staff members. public Staff () staffList = new StaffMember[6]; continue Copyright © 2012 Pearson Education, Inc.
921
staffList[0] = new Executive ("Sam", "123 Main Line",
continue staffList[0] = new Executive ("Sam", "123 Main Line", " ", " ", ); staffList[1] = new Employee ("Carla", "456 Off Line", " ", " ", ); staffList[2] = new Employee ("Woody", "789 Off Rocker", " ", " ", ); staffList[3] = new Hourly ("Diane", "678 Fifth Ave.", " ", " ", 10.55); staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.", " "); staffList[5] = new Volunteer ("Cliff", "321 Duds Lane", " "); ((Executive)staffList[0]).awardBonus (500.00); ((Hourly)staffList[3]).addHours (40); } Copyright © 2012 Pearson Education, Inc.
922
//-----------------------------------------------------------------
continue // // Pays all staff members. public void payday () { double amount; for (int count=0; count < staffList.length; count++) System.out.println (staffList[count]); amount = staffList[count].pay(); // polymorphic if (amount == 0.0) System.out.println ("Thanks!"); else System.out.println ("Paid: " + amount); System.out.println (" "); } Copyright © 2012 Pearson Education, Inc.
923
//********************************************************************
// StaffMember.java Author: Lewis/Loftus // // Represents a generic staff member. abstract public class StaffMember { protected String name; protected String address; protected String phone; // // Constructor: Sets up this staff member using the specified // information. public StaffMember (String eName, String eAddress, String ePhone) name = eName; address = eAddress; phone = ePhone; } continue Copyright © 2012 Pearson Education, Inc.
924
//-----------------------------------------------------------------
continue // // Returns a string including the basic employee information. public String toString() { String result = "Name: " + name + "\n"; result += "Address: " + address + "\n"; result += "Phone: " + phone; return result; } // Derived classes must define the pay method for each type of // employee. public abstract double pay(); Copyright © 2012 Pearson Education, Inc.
925
//********************************************************************
// Volunteer.java Author: Lewis/Loftus // // Represents a staff member that works as a volunteer. public class Volunteer extends StaffMember { // // Constructor: Sets up this volunteer using the specified // information. public Volunteer (String eName, String eAddress, String ePhone) super (eName, eAddress, ePhone); } // Returns a zero pay value for this volunteer. public double pay() return 0.0; Copyright © 2012 Pearson Education, Inc.
926
//********************************************************************
// Employee.java Author: Lewis/Loftus // // Represents a general paid employee. public class Employee extends StaffMember { protected String socialSecurityNumber; protected double payRate; // // Constructor: Sets up this employee with the specified // information. public Employee (String eName, String eAddress, String ePhone, String socSecNumber, double rate) super (eName, eAddress, ePhone); socialSecurityNumber = socSecNumber; payRate = rate; } continue Copyright © 2012 Pearson Education, Inc.
927
//-----------------------------------------------------------------
continue // // Returns information about an employee as a string. public String toString() { String result = super.toString(); result += "\nSocial Security Number: " + socialSecurityNumber; return result; } // Returns the pay rate for this employee. public double pay() return payRate; Copyright © 2012 Pearson Education, Inc.
928
//********************************************************************
// Executive.java Author: Lewis/Loftus // // Represents an executive staff member, who can earn a bonus. public class Executive extends Employee { private double bonus; // // Constructor: Sets up this executive with the specified // information. public Executive (String eName, String eAddress, String ePhone, String socSecNumber, double rate) super (eName, eAddress, ePhone, socSecNumber, rate); bonus = 0; // bonus has yet to be awarded } continue Copyright © 2012 Pearson Education, Inc.
929
//-----------------------------------------------------------------
continue // // Awards the specified bonus to this executive. public void awardBonus (double execBonus) { bonus = execBonus; } // Computes and returns the pay for an executive, which is the // regular employee payment plus a one-time bonus. public double pay() double payment = super.pay() + bonus; bonus = 0; return payment; Copyright © 2012 Pearson Education, Inc.
930
//********************************************************************
// Hourly.java Author: Lewis/Loftus // // Represents an employee that gets paid by the hour. public class Hourly extends Employee { private int hoursWorked; // // Constructor: Sets up this hourly employee using the specified // information. public Hourly (String eName, String eAddress, String ePhone, String socSecNumber, double rate) super (eName, eAddress, ePhone, socSecNumber, rate); hoursWorked = 0; } continue Copyright © 2012 Pearson Education, Inc.
931
//-----------------------------------------------------------------
continue // // Adds the specified number of hours to this employee's // accumulated hours. public void addHours (int moreHours) { hoursWorked += moreHours; } // Computes and returns the pay for this hourly employee. public double pay() double payment = payRate * hoursWorked; hoursWorked = 0; return payment; Copyright © 2012 Pearson Education, Inc.
932
//-----------------------------------------------------------------
continue // // Returns information about this hourly employee as a string. public String toString() { String result = super.toString(); result += "\nCurrent hours: " + hoursWorked; return result; } Copyright © 2012 Pearson Education, Inc.
933
Outline Late Binding Polymorphism via Inheritance
Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders Copyright © 2012 Pearson Education, Inc.
934
Polymorphism via Interfaces
Interfaces can be used to set up polymorphic references as well Suppose we declare an interface called Speaker as follows: public interface Speaker { public void speak(); public void announce (String str); } Copyright © 2012 Pearson Education, Inc.
935
Polymorphism via Interfaces
An interface name can be used as the type of an object reference variable: Speaker current; The current reference can be used to point to any object of any class that implements the Speaker interface The version of speak invoked by the following line depends on the type of object that current is referencing: current.speak(); Copyright © 2012 Pearson Education, Inc.
936
Polymorphism via Interfaces
Now suppose two classes, Philosopher and Dog, both implement the Speaker interface, providing distinct versions of the speak method In the following code, the first call to speak invokes one version and the second invokes another: Speaker guest = new Philospher(); guest.speak(); guest = new Dog(); Copyright © 2012 Pearson Education, Inc.
937
Polymorphism via Interfaces
As with class reference types, the compiler will restrict invocations to methods in the interface For example, even if Philosopher also had a method called pontificate, the following would still cause a compiler error: Speaker special = new Philospher(); special.pontificate(); // compiler error Remember, the compiler bases its rulings on the type of the reference Copyright © 2012 Pearson Education, Inc.
938
Quick Check Would the following statements be valid?
Speaker first = new Dog(); Philosopher second = new Philosopher(); second.pontificate(); first = second; Copyright © 2012 Pearson Education, Inc.
939
Quick Check Would the following statements be valid?
Speaker first = new Dog(); Philosopher second = new Philosopher(); second.pontificate(); first = second; Yes, all assignments and method calls are valid as written Copyright © 2012 Pearson Education, Inc.
940
Outline Late Binding Polymorphism via Inheritance
Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders Copyright © 2012 Pearson Education, Inc.
941
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific criteria: sort test scores in ascending numeric order sort a list of people alphabetically by last name There are many algorithms, which vary in efficiency, for sorting a list of items We will examine two specific algorithms: Selection Sort Insertion Sort Copyright © 2012 Pearson Education, Inc.
942
Selection Sort The strategy of Selection Sort:
select a value and put it in its final place in the list repeat for all other values In more detail: find the smallest value in the list switch it with the value in the first position find the next smallest value in the list switch it with the value in the second position repeat until all values are in their proper places Copyright © 2012 Pearson Education, Inc.
943
Selection Sort Copyright © 2012 Pearson Education, Inc.
944
Swapping The processing of the selection sort algorithm includes the swapping of two values Swapping requires three assignment statements and a temporary storage location To swap the values of first and second: temp = first; first = second; second = temp; Copyright © 2012 Pearson Education, Inc.
945
Polymorphism in Sorting
Recall that a class that implements the Comparable interface defines a compareTo method to determine the relative order of its objects We can use polymorphism to develop a generic sort for any set of Comparable objects The sorting method accepts as a parameter an array of Comparable objects That way, one method can be used to sort an array of People, or Books, or whatever Copyright © 2012 Pearson Education, Inc.
946
Selection Sort This technique allows each class to decide for itself what it means for one object to be less than another Let's look at an example that sorts an array of Contact objects The selectionSort method is a static method in the Sorting class See PhoneList.java See Sorting.java See Contact.java Copyright © 2012 Pearson Education, Inc.
947
//********************************************************************
// PhoneList.java Author: Lewis/Loftus // // Driver for testing a sorting algorithm. public class PhoneList { // // Creates an array of Contact objects, sorts them, then prints // them. public static void main (String[] args) Contact[] friends = new Contact[8]; friends[0] = new Contact ("John", "Smith", " "); friends[1] = new Contact ("Sarah", "Barnes", " "); friends[2] = new Contact ("Mark", "Riley", " "); friends[3] = new Contact ("Laura", "Getz", " "); friends[4] = new Contact ("Larry", "Smith", " "); friends[5] = new Contact ("Frank", "Phelps", " "); friends[6] = new Contact ("Mario", "Guzman", " "); friends[7] = new Contact ("Marsha", "Grant", " "); continue Copyright © 2012 Pearson Education, Inc.
948
Sorting.selectionSort(friends); for (Contact friend : friends)
continue Sorting.selectionSort(friends); for (Contact friend : friends) System.out.println (friend); } Copyright © 2012 Pearson Education, Inc.
949
Output Barnes, Sarah 215-555-3827 continue Getz, Laura 663-555-3984
Grant, Marsha Guzman, Mario Phelps, Frank Riley, Mark Smith, John Smith, Larry continue Sorting.selectionSort(friends); for (Contact friend : friends) System.out.println (friend); } Copyright © 2012 Pearson Education, Inc.
950
The static selectionSort method in the Sorting class:
// // Sorts the specified array of objects using the selection // sort algorithm. public static void selectionSort (Comparable[] list) { int min; Comparable temp; for (int index = 0; index < list.length-1; index++) min = index; for (int scan = index+1; scan < list.length; scan++) if (list[scan].compareTo(list[min]) < 0) min = scan; // Swap the values temp = list[min]; list[min] = list[index]; list[index] = temp; } Copyright © 2012 Pearson Education, Inc.
951
//********************************************************************
// Contact.java Author: Lewis/Loftus // // Represents a phone contact. public class Contact implements Comparable { private String firstName, lastName, phone; // // Constructor: Sets up this contact with the specified data. public Contact (String first, String last, String telephone) firstName = first; lastName = last; phone = telephone; } continue Copyright © 2012 Pearson Education, Inc.
952
//-----------------------------------------------------------------
continue // // Returns a description of this contact as a string. public String toString () { return lastName + ", " + firstName + "\t" + phone; } public boolean equals (Object other) return (lastName.equals(((Contact)other).getLastName()) && firstName.equals(((Contact)other).getFirstName())); Copyright © 2012 Pearson Education, Inc.
953
//-----------------------------------------------------------------
continue // // Uses both last and first names to determine ordering. public int compareTo (Object other) { int result; String otherFirst = ((Contact)other).getFirstName(); String otherLast = ((Contact)other).getLastName(); if (lastName.equals(otherLast)) result = firstName.compareTo(otherFirst); else result = lastName.compareTo(otherLast); return result; } Copyright © 2012 Pearson Education, Inc.
954
//-----------------------------------------------------------------
continue // // First name accessor. public String getFirstName () { return firstName; } // Last name accessor. public String getLastName () return lastName; Copyright © 2012 Pearson Education, Inc.
955
Insertion Sort The strategy of Insertion Sort: In more detail:
pick any item and insert it into its proper place in a sorted sublist repeat until all items have been inserted In more detail: consider the first item to be a sorted sublist (of one item) insert the second item into the sorted sublist, shifting the first item as needed to make room to insert the new one insert the third item into the sorted sublist (of two items), shifting items as necessary repeat until all values are inserted into their proper positions Copyright © 2012 Pearson Education, Inc.
956
Insertion Sort Copyright © 2012 Pearson Education, Inc.
957
The static insertionSort method in the Sorting class:
// // Sorts the specified array of objects using the insertion // sort algorithm. public static void insertionSort (Comparable[] list) { for (int index = 1; index < list.length; index++) Comparable key = list[index]; int position = index; // Shift larger values to the right while (position > 0 && key.compareTo(list[position-1]) < 0) list[position] = list[position-1]; position--; } list[position] = key; Copyright © 2012 Pearson Education, Inc.
958
Comparing Sorts The Selection and Insertion sort algorithms are similar in efficiency They both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list Approximately n2 number of comparisons are made to sort a list of size n We therefore say that these sorts are of order n2 Other sorts are more efficient: order n log2 n Copyright © 2012 Pearson Education, Inc.
959
Outline Late Binding Polymorphism via Inheritance
Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders Copyright © 2012 Pearson Education, Inc.
960
Searching Searching is the process of finding a target element within a group of items called the search pool The target may or may not be in the search pool We want to perform the search efficiently, minimizing the number of comparisons Let's look at two classic searching approaches: linear search and binary search As we did with sorting, we'll implement the searches with polymorphic Comparable parameters Copyright © 2012 Pearson Education, Inc.
961
Linear Search A linear search begins at one end of a list and examines each element in turn Eventually, either the item is found or the end of the list is encountered Copyright © 2012 Pearson Education, Inc.
962
Binary Search A binary search assumes the list of items in the search pool is sorted It eliminates a large part of the search pool with a single comparison A binary search first examines the middle element of the list -- if it matches the target, the search is over If it doesn't, only one half of the remaining elements need be searched Since they are sorted, the target can only be in one half of the other Copyright © 2012 Pearson Education, Inc.
963
Binary Search The process continues by comparing the middle element of the remaining viable candidates Each comparison eliminates approximately half of the remaining data Eventually, the target is found or the data is exhausted Copyright © 2012 Pearson Education, Inc.
964
Searching The search methods are implemented as static methods in the Searching class See PhoneList2.java See Searching.java Copyright © 2012 Pearson Education, Inc.
965
//********************************************************************
// PhoneList2.java Author: Lewis/Loftus // // Driver for testing searching algorithms. public class PhoneList2 { // // Creates an array of Contact objects, sorts them, then prints // them. public static void main (String[] args) Contact test, found; Contact[] friends = new Contact[8]; friends[0] = new Contact ("John", "Smith", " "); friends[1] = new Contact ("Sarah", "Barnes", " "); friends[2] = new Contact ("Mark", "Riley", " "); friends[3] = new Contact ("Laura", "Getz", " "); friends[4] = new Contact ("Larry", "Smith", " "); friends[5] = new Contact ("Frank", "Phelps", " "); friends[6] = new Contact ("Mario", "Guzman", " "); friends[7] = new Contact ("Marsha", "Grant", " "); continue Copyright © 2012 Pearson Education, Inc.
966
test = new Contact ("Frank", "Phelps", "");
continue test = new Contact ("Frank", "Phelps", ""); found = (Contact) Searching.linearSearch(friends, test); if (found != null) System.out.println ("Found: " + found); else System.out.println ("The contact was not found."); System.out.println (); Sorting.selectionSort(friends); test = new Contact ("Mario", "Guzman", ""); found = (Contact) Searching.binarySearch(friends, test); } Copyright © 2012 Pearson Education, Inc.
967
Output continue Found: Phelps, Frank 322-555-2284
Found: Guzman, Mario continue test = new Contact ("Frank", "Phelps", ""); found = (Contact) Searching.linearSearch(friends, test); if (found != null) System.out.println ("Found: " + found); else System.out.println ("The contact was not found."); System.out.println (); Sorting.selectionSort(friends); test = new Contact ("Mario", "Guzman", ""); found = (Contact) Searching.binarySearch(friends, test); } Copyright © 2012 Pearson Education, Inc.
968
The linearSearch method in the Searching class:
// // Searches the specified array of objects for the target using // a linear search. Returns a reference to the target object from // the array if found, and null otherwise. public static Comparable linearSearch (Comparable[] list, Comparable target) { int index = 0; boolean found = false; while (!found && index < list.length) if (list[index].equals(target)) found = true; else index++; } if (found) return list[index]; return null; Copyright © 2012 Pearson Education, Inc.
969
The binarySearch method in the Searching class:
// // Searches the specified array of objects for the target using // a binary search. Assumes the array is already sorted in // ascending order when it is passed in. Returns a reference to // the target object from the array if found, and null otherwise. public static Comparable binarySearch (Comparable[] list, Comparable target) { int min=0, max=list.length, mid=0; boolean found = false; while (!found && min <= max) mid = (min+max) / 2; if (list[mid].equals(target)) found = true; else if (target.compareTo(list[mid]) < 0) max = mid-1; min = mid+1; } continue Copyright © 2012 Pearson Education, Inc.
970
continue if (found) return list[mid]; else return null; }
Copyright © 2012 Pearson Education, Inc.
971
Outline Late Binding Polymorphism via Inheritance
Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders Copyright © 2012 Pearson Education, Inc.
972
Event Processing Polymorphism plays an important role in the development of a Java graphical user interface Consider the following code: JButton button = new JButton(); button.addActionListener(new MyListener()); Note that the addActionListener method is accepting a MyListener object as a parameter In fact, we can pass the addActionListener method any object that implements the ActionListener interface Copyright © 2012 Pearson Education, Inc.
973
Event Processing The code for addActionListener accepts a parameter of type ActionListener (the interface) Because of polymorphism, any object that implements that interface is compatible with the parameter reference variable The component can call the actionPerformed method because of the relationship between the listener class and the interface Extending an adapter class to create a listener represents the same situation; the adapter class implements the appropriate interface already Copyright © 2012 Pearson Education, Inc.
974
Outline Late Binding Polymorphism via Inheritance
Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders Copyright © 2012 Pearson Education, Inc.
975
Dialog Boxes Recall that a dialog box is a small window that "pops up" to interact with the user for a brief, specific purpose We used the JOptionPane class in Chapter 6 to create dialog boxes for presenting information, confirming an action, or accepting an input value Let's now look at two other classes that let us create specialized dialog boxes Copyright © 2012 Pearson Education, Inc.
976
File Choosers Situations often arise where we want the user to select a file stored on a disk drive, usually so that its contents can be read and processed A file chooser, represented by the JFileChooser class, simplifies this process The user can browse the disk and filter the file types displayed See DisplayFile.java Copyright © 2012 Pearson Education, Inc.
977
//********************************************************************
// DisplayFile.java Author: Lewis/Loftus // // Demonstrates the use of a file chooser and a text area. import java.util.Scanner; import java.io.*; import javax.swing.*; public class DisplayFile { // // Opens a file chooser dialog, reads the selected file and // loads it into a text area. public static void main (String[] args) throws IOException JFrame frame = new JFrame ("Display File"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JTextArea ta = new JTextArea (20, 30); JFileChooser chooser = new JFileChooser(); int status = chooser.showOpenDialog (null); continue Copyright © 2012 Pearson Education, Inc.
978
if (status != JFileChooser.APPROVE_OPTION)
continue if (status != JFileChooser.APPROVE_OPTION) ta.setText ("No File Chosen"); else { File file = chooser.getSelectedFile(); Scanner scan = new Scanner (file); String info = ""; while (scan.hasNext()) info += scan.nextLine() + "\n"; ta.setText (info); } frame.getContentPane().add (ta); frame.pack(); frame.setVisible(true); Copyright © 2012 Pearson Education, Inc.
979
if (status != JFileChooser.APPROVE_OPTION)
continue if (status != JFileChooser.APPROVE_OPTION) ta.setText ("No File Chosen"); else { File file = chooser.getSelectedFile(); Scanner scan = new Scanner (file); String info = ""; while (scan.hasNext()) info += scan.nextLine() + "\n"; ta.setText (info); } frame.getContentPane().add (ta); frame.pack(); frame.setVisible(true); Copyright © 2012 Pearson Education, Inc.
980
Color Choosers In many situations we want to allow the user to select a color A color chooser, represented by the JColorChooser class, simplifies this process The user can choose a color from a palette or specify the color using RGB values See DisplayColor.java Copyright © 2012 Pearson Education, Inc.
981
//********************************************************************
// DisplayColor.java Author: Lewis/Loftus // // Demonstrates the use of a color chooser. import javax.swing.*; import java.awt.*; public class DisplayColor { // // Presents a frame with a colored panel, then allows the user // to change the color multiple times using a color chooser. public static void main (String[] args) JFrame frame = new JFrame ("Display Color"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JPanel colorPanel = new JPanel(); colorPanel.setBackground (Color.white); colorPanel.setPreferredSize (new Dimension (300, 100)); continue Copyright © 2012 Pearson Education, Inc.
982
frame.getContentPane().add (colorPanel); frame.pack();
continue frame.getContentPane().add (colorPanel); frame.pack(); frame.setVisible(true); Color shade = Color.white; int again; do { shade = JColorChooser.showDialog (frame, "Pick a Color!", shade); colorPanel.setBackground (shade); again = JOptionPane.showConfirmDialog (null, "Display another color?"); } while (again == JOptionPane.YES_OPTION); Copyright © 2012 Pearson Education, Inc.
983
frame.getContentPane().add (colorPanel); frame.pack();
continue frame.getContentPane().add (colorPanel); frame.pack(); frame.setVisible(true); Color shade = Color.white; int again; do { shade = JColorChooser.showDialog (frame, "Pick a Color!", shade); colorPanel.setBackground (shade); again = JOptionPane.showConfirmDialog (null, "Display another color?"); } while (again == JOptionPane.YES_OPTION); Copyright © 2012 Pearson Education, Inc.
984
Outline Late Binding Polymorphism via Inheritance
Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders Copyright © 2012 Pearson Education, Inc.
985
Sliders A slider is a GUI component that allows the user to specify a value within a numeric range A slider can be oriented vertically or horizontally and can have optional tick marks and labels The minimum and maximum values for the slider are set using the JSlider constructor A slider produces a change event when the slider is moved, indicating that the slider and the value it represents has changed Copyright © 2012 Pearson Education, Inc.
986
Sliders Let's look at an example that uses three sliders to change values representing the color components of an RGB value See SlideColor.java See SlideColorPanel.java Copyright © 2012 Pearson Education, Inc.
987
//********************************************************************
// SlideColor.java Authors: Lewis/Loftus // // Demonstrates the use slider components. import java.awt.*; import javax.swing.*; public class SlideColor { // // Presents up a frame with a control panel and a panel that // changes color as the sliders are adjusted. public static void main (String[] args) JFrame frame = new JFrame ("Slide Colors"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new SlideColorPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
988
//********************************************************************
// SlideColor.java Authors: Lewis/Loftus // // Demonstrates the use slider components. import java.awt.*; import javax.swing.*; public class SlideColor { // // Presents up a frame with a control panel and a panel that // changes color as the sliders are adjusted. public static void main (String[] args) JFrame frame = new JFrame ("Slide Colors"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new SlideColorPanel()); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
989
//********************************************************************
// SlideColorPanel.java Authors: Lewis/Loftus // // Represents the slider control panel for the SlideColor program. import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class SlideColorPanel extends JPanel { private JPanel controls, colorPanel; private JSlider rSlider, gSlider, bSlider; private JLabel rLabel, gLabel, bLabel; // // Sets up the sliders and their labels, aligning them along // their left edge using a box layout. public SlideColorPanel() rSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0); rSlider.setMajorTickSpacing (50); rSlider.setMinorTickSpacing (10); rSlider.setPaintTicks (true); rSlider.setPaintLabels (true); rSlider.setAlignmentX (Component.LEFT_ALIGNMENT); continue Copyright © 2012 Pearson Education, Inc.
990
gSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
continue gSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0); gSlider.setMajorTickSpacing (50); gSlider.setMinorTickSpacing (10); gSlider.setPaintTicks (true); gSlider.setPaintLabels (true); gSlider.setAlignmentX (Component.LEFT_ALIGNMENT); bSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0); bSlider.setMajorTickSpacing (50); bSlider.setMinorTickSpacing (10); bSlider.setPaintTicks (true); bSlider.setPaintLabels (true); bSlider.setAlignmentX (Component.LEFT_ALIGNMENT); SliderListener listener = new SliderListener(); rSlider.addChangeListener (listener); gSlider.addChangeListener (listener); bSlider.addChangeListener (listener); rLabel = new JLabel ("Red: 0"); rLabel.setAlignmentX (Component.LEFT_ALIGNMENT); gLabel = new JLabel ("Green: 0"); gLabel.setAlignmentX (Component.LEFT_ALIGNMENT); bLabel = new JLabel ("Blue: 0"); bLabel.setAlignmentX (Component.LEFT_ALIGNMENT); Copyright © 2012 Pearson Education, Inc.
991
controls = new JPanel();
continue controls = new JPanel(); BoxLayout layout = new BoxLayout (controls, BoxLayout.Y_AXIS); controls.setLayout (layout); controls.add (rLabel); controls.add (rSlider); controls.add (Box.createRigidArea (new Dimension (0, 20))); controls.add (gLabel); controls.add (gSlider); controls.add (bLabel); controls.add (bSlider); colorPanel = new JPanel(); colorPanel.setPreferredSize (new Dimension (100, 100)); colorPanel.setBackground (new Color (0, 0, 0)); add (controls); add (colorPanel); } Copyright © 2012 Pearson Education, Inc.
992
//*****************************************************************
continue //***************************************************************** // Represents the listener for all three sliders. private class SliderListener implements ChangeListener { private int red, green, blue; // // Gets the value of each slider, then updates the labels and // the color panel. public void stateChanged (ChangeEvent event) red = rSlider.getValue(); green = gSlider.getValue(); blue = bSlider.getValue(); rLabel.setText ("Red: " + red); gLabel.setText ("Green: " + green); bLabel.setText ("Blue: " + blue); colorPanel.setBackground (new Color (red, green, blue)); } Copyright © 2012 Pearson Education, Inc.
993
Summary Chapter 10 has focused on:
defining polymorphism and its benefits using inheritance to create polymorphic references using interfaces to create polymorphic references using polymorphism to implement sorting and searching algorithms additional GUI components Copyright © 2012 Pearson Education, Inc.
994
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 11 Exceptions Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
995
Exceptions Exception handling is an important aspect of object-oriented design Chapter 11 focuses on: the purpose of exceptions exception messages the try-catch statement propagating exceptions the exception class hierarchy GUI mnemonics and tool tips more GUI components and containers Copyright © 2012 Pearson Education, Inc.
996
Outline Exception Handling The try-catch Statement Exception Classes
I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes Copyright © 2012 Pearson Education, Inc.
997
Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught Copyright © 2012 Pearson Education, Inc.
998
Exception Handling The Java API has a predefined set of exceptions that can occur during execution A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program The manner in which an exception is processed is an important design consideration Copyright © 2012 Pearson Education, Inc.
999
Exception Handling If an exception is ignored (not caught) by the program, the program will terminate and produce an appropriate message The message includes a call stack trace that: indicates the line on which the exception occurred shows the method call trail that lead to the attempted execution of the offending line See Zero.java Copyright © 2012 Pearson Education, Inc.
1000
//********************************************************************
// Zero.java Author: Lewis/Loftus // // Demonstrates an uncaught exception. public class Zero { // // Deliberately divides by zero to produce an exception. public static void main (String[] args) int numerator = 10; int denominator = 0; System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); } Copyright © 2012 Pearson Education, Inc.
1001
Output (when program terminates)
Exception in thread "main" java.lang.ArithmeticException: / by zero at Zero.main(Zero.java:17) //******************************************************************** // Zero.java Author: Lewis/Loftus // // Demonstrates an uncaught exception. public class Zero { // // Deliberately divides by zero to produce an exception. public static void main (String[] args) int numerator = 10; int denominator = 0; System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); } Copyright © 2012 Pearson Education, Inc.
1002
Outline Exception Handling The try-catch Statement Exception Classes
I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes Copyright © 2012 Pearson Education, Inc.
1003
The try Statement To handle an exception in a program, use a try- catch statement A try block is followed by one or more catch clauses Each catch clause has an associated exception type and is called an exception handler When an exception occurs within the try block, processing immediately jumps to the first catch clause that matches the exception type See ProductCodes.java Copyright © 2012 Pearson Education, Inc.
1004
//********************************************************************
// ProductCodes.java Author: Lewis/Loftus // // Demonstrates the use of a try-catch block. import java.util.Scanner; public class ProductCodes { // // Counts the number of product codes that are entered with a // zone of R and and district greater than 2000. public static void main (String[] args) String code; char zone; int district, valid = 0, banned = 0; Scanner scan = new Scanner (System.in); System.out.print ("Enter product code (XXX to quit): "); code = scan.nextLine(); continue Copyright © 2012 Pearson Education, Inc.
1005
while (!code.equals ("XXX")) { try zone = code.charAt(9);
continue while (!code.equals ("XXX")) { try zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } catch (StringIndexOutOfBoundsException exception) System.out.println ("Improper code length: " + code); catch (NumberFormatException exception) System.out.println ("District is not numeric: " + code); System.out.print ("Enter product code (XXX to quit): "); code = scan.nextLine(); System.out.println ("# of valid codes entered: " + valid); System.out.println ("# of banned codes entered: " + banned); Copyright © 2012 Pearson Education, Inc.
1006
Sample Run Enter product code (XXX to quit): TRV2475A5R-14
continue while (!code.equals ("XXX")) { try zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } catch (StringIndexOutOfBoundsException exception) System.out.println ("Improper code length: " + code); catch (NumberFormatException exception) System.out.println ("District is not numeric: " + code); System.out.print ("Enter product code (XXX to quit): "); code = scan.nextLine(); System.out.println ("# of valid codes entered: " + valid); System.out.println ("# of banned codes entered: " + banned); Sample Run Enter product code (XXX to quit): TRV2475A5R-14 Enter product code (XXX to quit): TRD1704A7R-12 Enter product code (XXX to quit): TRL2k74A5R-11 District is not numeric: TRL2k74A5R-11 Enter product code (XXX to quit): TRQ2949A6M-04 Enter product code (XXX to quit): TRV2105A2 Improper code length: TRV2105A2 Enter product code (XXX to quit): TRQ2778A7R-19 Enter product code (XXX to quit): XXX # of valid codes entered: 4 # of banned codes entered: 2 Copyright © 2012 Pearson Education, Inc.
1007
The finally Clause A try statement can have an optional finally clause, which is always executed If no exception is generated, the statements in the finally clause are executed after the statements in the try block finish If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause finish Copyright © 2012 Pearson Education, Inc.
1008
Exception Propagation
An exception can be handled at a higher level if it is not appropriate to handle it where it occurs Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method See Propagation.java See ExceptionScope.java Copyright © 2012 Pearson Education, Inc.
1009
//********************************************************************
// Propagation.java Author: Lewis/Loftus // // Demonstrates exception propagation. public class Propagation { // // Invokes the level1 method to begin the exception demonstration. static public void main (String[] args) ExceptionScope demo = new ExceptionScope(); System.out.println("Program beginning."); demo.level1(); System.out.println("Program ending."); } Copyright © 2012 Pearson Education, Inc.
1010
Output Program beginning. Level 1 beginning. Level 2 beginning.
The exception message is: / by zero The call stack trace: java.lang.ArithmeticException: / by zero at ExceptionScope.level3(ExceptionScope.java:54) at ExceptionScope.level2(ExceptionScope.java:41) at ExceptionScope.level1(ExceptionScope.java:18) at Propagation.main(Propagation.java:17) Level 1 ending. Program ending. //******************************************************************** // Propagation.java Author: Lewis/Loftus // // Demonstrates exception propagation. public class Propagation { // // Invokes the level1 method to begin the exception demonstration. static public void main (String[] args) ExceptionScope demo = new ExceptionScope(); System.out.println("Program beginning."); demo.level1(); System.out.println("Program ending."); } Copyright © 2012 Pearson Education, Inc.
1011
//********************************************************************
// ExceptionScope.java Author: Lewis/Loftus // // Demonstrates exception propagation. public class ExceptionScope { // // Catches and handles the exception that is thrown in level3. public void level1() System.out.println("Level 1 beginning."); try level2(); } catch (ArithmeticException problem) System.out.println (); System.out.println ("The exception message is: " + problem.getMessage()); continue Copyright © 2012 Pearson Education, Inc.
1012
System.out.println ("The call stack trace:");
continue System.out.println ("The call stack trace:"); problem.printStackTrace(); System.out.println (); } System.out.println("Level 1 ending."); // // Serves as an intermediate level. The exception propagates // through this method back to level1. public void level2() { System.out.println("Level 2 beginning."); level3 (); System.out.println("Level 2 ending."); Copyright © 2012 Pearson Education, Inc.
1013
//-----------------------------------------------------------------
continue // // Performs a calculation to produce an exception. It is not // caught and handled at this level. public void level3 () { int numerator = 10, denominator = 0; System.out.println("Level 3 beginning."); int result = numerator / denominator; System.out.println("Level 3 ending."); } Copyright © 2012 Pearson Education, Inc.
1014
Outline Exception Handling The try-catch Statement Exception Classes
I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes Copyright © 2012 Pearson Education, Inc.
1015
The Exception Class Hierarchy
Exception classes in the Java API are related by inheritance, forming an exception class hierarchy All error and exception classes are descendents of the Throwable class A programmer can define an exception by extending the Exception class or one of its descendants The parent class used depends on how the new exception will be used Copyright © 2012 Pearson Education, Inc.
1016
The Exception Class Hierarchy
Copyright © 2012 Pearson Education, Inc.
1017
Checked Exceptions An exception is either checked or unchecked
A checked exception must either be caught or must be listed in the throws clause of any method that may throw or propagate it A throws clause is appended to the method header The compiler will issue an error if a checked exception is not caught or listed in a throws clause Copyright © 2012 Pearson Education, Inc.
1018
Unchecked Exceptions An unchecked exception does not require explicit handling, though it could be processed that way The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants Errors are similar to RuntimeException and its descendants in that: Errors should not be caught Errors do not require a throws clause Copyright © 2012 Pearson Education, Inc.
1019
Quick Check Which of these exceptions are checked and which are unchecked? NullPointerException IndexOutOfBoundsException ClassNotFoundException NoSuchMethodException ArithmeticException Copyright © 2012 Pearson Education, Inc.
1020
Quick Check Which of these exceptions are checked and which are unchecked? NullPointerException IndexOutOfBoundsException ClassNotFoundException NoSuchMethodException ArithmeticException Unchecked Checked Copyright © 2012 Pearson Education, Inc.
1021
The throw Statement Exceptions are thrown using the throw statement
Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown See CreatingExceptions.java See OutOfRangeException.java Copyright © 2012 Pearson Education, Inc.
1022
//********************************************************************
// CreatingExceptions.java Author: Lewis/Loftus // // Demonstrates the ability to define an exception via inheritance. import java.util.Scanner; public class CreatingExceptions { // // Creates an exception object and possibly throws it. public static void main (String[] args) throws OutOfRangeException final int MIN = 25, MAX = 40; Scanner scan = new Scanner (System.in); OutOfRangeException problem = new OutOfRangeException ("Input value is out of range."); continue Copyright © 2012 Pearson Education, Inc.
1023
System.out.print ("Enter an integer value between " + MIN +
continue System.out.print ("Enter an integer value between " + MIN + " and " + MAX + ", inclusive: "); int value = scan.nextInt(); // Determine if the exception should be thrown if (value < MIN || value > MAX) throw problem; System.out.println ("End of main method."); // may never reach } Copyright © 2012 Pearson Education, Inc.
1024
Sample Run Enter an integer value between 25 and 40, inclusive: 69
Exception in thread "main" OutOfRangeException: Input value is out of range. at CreatingExceptions.main(CreatingExceptions.java:20) continue System.out.print ("Enter an integer value between " + MIN + " and " + MAX + ", inclusive: "); int value = scan.nextInt(); // Determine if the exception should be thrown if (value < MIN || value > MAX) throw problem; System.out.println ("End of main method."); // may never reach } Copyright © 2012 Pearson Education, Inc.
1025
//********************************************************************
// OutOfRangeException.java Author: Lewis/Loftus // // Represents an exceptional condition in which a value is out of // some particular range. public class OutOfRangeException extends Exception { // // Sets up the exception object with a particular message. OutOfRangeException (String message) super (message); } Copyright © 2012 Pearson Education, Inc.
1026
Quick Check What is the matter with this code?
System.out.println("Before throw"); throw new OutOfRangeException("Too High"); System.out.println("After throw"); Copyright © 2012 Pearson Education, Inc.
1027
Quick Check What is the matter with this code?
System.out.println("Before throw"); throw new OutOfRangeException("Too High"); System.out.println("After throw"); The throw is not conditional and therefore always occurs. The second println statement can never be reached. Copyright © 2012 Pearson Education, Inc.
1028
Outline Exception Handling The try-catch Statement Exception Classes
I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes Copyright © 2012 Pearson Education, Inc.
1029
I/O Exceptions Let's examine issues related to exceptions and I/O
A stream is a sequence of bytes that flow from a source to a destination In a program, we read information from an input stream and write information to an output stream A program can manage multiple streams simultaneously Copyright © 2012 Pearson Education, Inc.
1030
Standard I/O There are three standard I/O streams:
standard output – defined by System.out standard input – defined by System.in standard error – defined by System.err We use System.out when we execute println statements System.out and System.err typically represent the console window System.in typically represents keyboard input, which we've used many times with Scanner Copyright © 2012 Pearson Education, Inc.
1031
The IOException Class Operations performed by some I/O classes may throw an IOException A file might not exist Even if the file exists, a program may not be able to find it The file might not contain the kind of data we expect An IOException is a checked exception Copyright © 2012 Pearson Education, Inc.
1032
Writing Text Files In Chapter 5 we explored the use of the Scanner class to read input from a text file Let's now examine other classes that let us write data to a text file The FileWriter class represents a text output file, but with minimal support for manipulating data Therefore, we also rely on PrintStream objects, which have print and println methods defined for them Copyright © 2012 Pearson Education, Inc.
1033
Writing Text Files Finally, we'll also use the PrintWriter class for advanced internationalization and error checking We build the class that represents the output file by combining these classes appropriately Output streams should be closed explicitly See TestData.java Copyright © 2012 Pearson Education, Inc.
1034
//********************************************************************
// TestData.java Author: Lewis/Loftus // // Demonstrates I/O exceptions and the use of a character file // output stream. import java.util.Random; import java.io.*; public class TestData { // // Creates a file of test data that consists of ten lines each // containing ten integer values in the range 10 to 99. public static void main (String[] args) throws IOException final int MAX = 10; int value; String file = "test.dat"; Random rand = new Random(); continue Copyright © 2012 Pearson Education, Inc.
1035
FileWriter fw = new FileWriter (file);
continue FileWriter fw = new FileWriter (file); BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw); for (int line=1; line <= MAX; line++) { for (int num=1; num <= MAX; num++) value = rand.nextInt (90) + 10; outFile.print (value + " "); } outFile.println (); outFile.close(); System.out.println ("Output file has been created: " + file); Copyright © 2012 Pearson Education, Inc.
1036
Output Sample test.dat File Output file has been created: test.dat
continue FileWriter fw = new FileWriter (file); BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw); for (int line=1; line <= MAX; line++) { for (int num=1; num <= MAX; num++) value = rand.nextInt (90) + 10; outFile.print (value + " "); } outFile.println (); outFile.close(); System.out.println ("Output file has been created: " + file); Sample test.dat File Copyright © 2012 Pearson Education, Inc.
1037
Outline Exception Handling The try-catch Statement Exception Classes
I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes Copyright © 2012 Pearson Education, Inc.
1038
Tool Tips A tool tip provides a short pop-up description when the mouse cursor rests momentarily on a component A tool tip is assigned using the setToolTipText method of a Swing component JButton button = new JButton("Compute"); button.setToolTipText("Calculate size"); Copyright © 2012 Pearson Education, Inc.
1039
Mnemonics A mnemonic is a keyboard alternative for pushing a button or selecting a menu option The mnemonic character should be chosen from the component's label, and is underlined The user activates the component by holding down the ALT key and pressing the mnemonic character JButton button = new JButton("Calculate"); button.setMnemonic("C"); Copyright © 2012 Pearson Education, Inc.
1040
Disabled Components Components can be disabled if they should not be used A disabled component is "grayed out" and will not respond to user interaction The status is set using the setEnabled method: JButton button = new JButton ("Do It"); button.setEnabled (false); Copyright © 2012 Pearson Education, Inc.
1041
Light Bulb Example The right combination of special features such as tool tips and mnemonics can enhance the usefulness of a GUI See LightBulb.java See LightBulbPanel.java See LightBulbControls.java Copyright © 2012 Pearson Education, Inc.
1042
//********************************************************************
// LightBulb.java Author: Lewis/Loftus // // Demonstrates mnemonics and tool tips. import javax.swing.*; import java.awt.*; public class LightBulb { // // Sets up a frame that displays a light bulb image that can be // turned on and off. public static void main (String[] args) JFrame frame = new JFrame ("Light Bulb"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); LightBulbPanel bulb = new LightBulbPanel(); LightBulbControls controls = new LightBulbControls (bulb); continue Copyright © 2012 Pearson Education, Inc.
1043
JPanel panel = new JPanel(); panel.setBackground (Color.black);
continue JPanel panel = new JPanel(); panel.setBackground (Color.black); panel.setLayout (new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add (Box.createRigidArea (new Dimension (0, 20))); panel.add (bulb); panel.add (Box.createRigidArea (new Dimension (0, 10))); panel.add (controls); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
1044
JPanel panel = new JPanel(); panel.setBackground (Color.black);
continue JPanel panel = new JPanel(); panel.setBackground (Color.black); panel.setLayout (new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add (Box.createRigidArea (new Dimension (0, 20))); panel.add (bulb); panel.add (Box.createRigidArea (new Dimension (0, 10))); panel.add (controls); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
1045
//********************************************************************
// LightBulbPanel.java Author: Lewis/Loftus // // Represents the image for the LightBulb program. import javax.swing.*; import java.awt.*; public class LightBulbPanel extends JPanel { private boolean on; private ImageIcon lightOn, lightOff; private JLabel imageLabel; continue Copyright © 2012 Pearson Education, Inc.
1046
//-----------------------------------------------------------------
continue // // Constructor: Sets up the images and the initial state. public LightBulbPanel() { lightOn = new ImageIcon ("lightBulbOn.gif"); lightOff = new ImageIcon ("lightBulbOff.gif"); setBackground (Color.black); on = true; imageLabel = new JLabel (lightOff); add (imageLabel); } Copyright © 2012 Pearson Education, Inc.
1047
//-----------------------------------------------------------------
continue // // Paints the panel using the appropriate image. public void paintComponent (Graphics page) { super.paintComponent(page); if (on) imageLabel.setIcon (lightOn); else imageLabel.setIcon (lightOff); } // Sets the status of the light bulb. public void setOn (boolean lightBulbOn) on = lightBulbOn; Copyright © 2012 Pearson Education, Inc.
1048
//********************************************************************
// LightBulbControls.java Author: Lewis/Loftus // // Represents the control panel for the LightBulb program. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class LightBulbControls extends JPanel { private LightBulbPanel bulb; private JButton onButton, offButton; continue Copyright © 2012 Pearson Education, Inc.
1049
//-----------------------------------------------------------------
continue // // Sets up the lightbulb control panel. public LightBulbControls (LightBulbPanel bulbPanel) { bulb = bulbPanel; onButton = new JButton ("On"); onButton.setEnabled (false); onButton.setMnemonic ('n'); onButton.setToolTipText ("Turn it on!"); onButton.addActionListener (new OnListener()); offButton = new JButton ("Off"); offButton.setEnabled (true); offButton.setMnemonic ('f'); offButton.setToolTipText ("Turn it off!"); offButton.addActionListener (new OffListener()); setBackground (Color.black); add (onButton); add (offButton); } Copyright © 2012 Pearson Education, Inc.
1050
//*****************************************************************
continue //***************************************************************** // Represents the listener for the On button. private class OnListener implements ActionListener { // // Turns the bulb on and repaints the bulb panel. public void actionPerformed (ActionEvent event) bulb.setOn (true); onButton.setEnabled (false); offButton.setEnabled (true); bulb.repaint(); } Copyright © 2012 Pearson Education, Inc.
1051
//*****************************************************************
continue //***************************************************************** // Represents the listener for the Off button. private class OffListener implements ActionListener { // // Turns the bulb off and repaints the bulb panel. public void actionPerformed (ActionEvent event) bulb.setOn (false); onButton.setEnabled (true); offButton.setEnabled (false); bulb.repaint(); } Copyright © 2012 Pearson Education, Inc.
1052
Outline Exception Handling The try-catch Statement Exception Classes
I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes Copyright © 2012 Pearson Education, Inc.
1053
Combo Boxes A combo box provides a menu from which the user can choose one of several options The currently selected option is shown in the combo box A combo box shows its options only when the user presses it using the mouse Options can be established using an array of strings or using the addItem method Copyright © 2012 Pearson Education, Inc.
1054
The JukeBox Program A combo box generates an action event when the user makes a selection from it See JukeBox.java See JukeBoxControls.java Copyright © 2012 Pearson Education, Inc.
1055
//********************************************************************
// JukeBox.java Author: Lewis/Loftus // // Demonstrates the use of a combo box. import javax.swing.*; public class JukeBox { // // Creates and displays the controls for a juke box. public static void main (String[] args) JFrame frame = new JFrame ("Java Juke Box"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JukeBoxControls controlPanel = new JukeBoxControls(); frame.getContentPane().add(controlPanel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
1056
//********************************************************************
// JukeBox.java Author: Lewis/Loftus // // Demonstrates the use of a combo box. import javax.swing.*; public class JukeBox { // // Creates and displays the controls for a juke box. public static void main (String[] args) JFrame frame = new JFrame ("Java Juke Box"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JukeBoxControls controlPanel = new JukeBoxControls(); frame.getContentPane().add(controlPanel); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
1057
//********************************************************************
// JukeBoxControls.java Author: Lewis and Loftus // // Represents the control panel for the juke box. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.applet.AudioClip; import java.net.URL; public class JukeBoxControls extends JPanel { private JComboBox musicCombo; private JButton stopButton, playButton; private AudioClip[] music; private AudioClip current; // // Sets up the GUI for the juke box. public JukeBoxControls() URL url1, url2, url3, url4, url5, url6; url1 = url2 = url3 = url4 = url5 = url6 = null; continue Copyright © 2012 Pearson Education, Inc.
1058
// Obtain and store the audio clips to play try {
continue // Obtain and store the audio clips to play try { url1 = new URL ("file", "localhost", "westernBeat.wav"); url2 = new URL ("file", "localhost", "classical.wav"); url3 = new URL ("file", "localhost", "jeopardy.au"); url4 = new URL ("file", "localhost", "newAgeRythm.wav"); url5 = new URL ("file", "localhost", "eightiesJam.wav"); url6 = new URL ("file", "localhost", "hitchcock.wav"); } catch (Exception exception) {} music = new AudioClip[7]; music[0] = null; // Corresponds to "Make a Selection..." music[1] = JApplet.newAudioClip (url1); music[2] = JApplet.newAudioClip (url2); music[3] = JApplet.newAudioClip (url3); music[4] = JApplet.newAudioClip (url4); music[5] = JApplet.newAudioClip (url5); music[6] = JApplet.newAudioClip (url6); JLabel titleLabel = new JLabel ("Java Juke Box"); titleLabel.setAlignmentX (Component.CENTER_ALIGNMENT); Copyright © 2012 Pearson Education, Inc.
1059
musicCombo = new JComboBox (musicNames);
continue musicCombo = new JComboBox (musicNames); musicCombo.setAlignmentX (Component.CENTER_ALIGNMENT); // Set up the buttons playButton = new JButton ("Play", new ImageIcon ("play.gif")); playButton.setBackground (Color.white); playButton.setMnemonic ('p'); stopButton = new JButton ("Stop", new ImageIcon ("stop.gif")); stopButton.setBackground (Color.white); stopButton.setMnemonic ('s'); JPanel buttons = new JPanel(); buttons.setLayout (new BoxLayout (buttons, BoxLayout.X_AXIS)); buttons.add (playButton); buttons.add (Box.createRigidArea (new Dimension(5,0))); buttons.add (stopButton); buttons.setBackground (Color.cyan); // Set up this panel setPreferredSize (new Dimension (300, 100)); setBackground (Color.cyan); setLayout (new BoxLayout (this, BoxLayout.Y_AXIS)); Copyright © 2012 Pearson Education, Inc.
1060
musicCombo.addActionListener (new ComboListener());
continue musicCombo.addActionListener (new ComboListener()); stopButton.addActionListener (new ButtonListener()); playButton.addActionListener (new ButtonListener()); current = null; } //***************************************************************** // Represents the action listener for the combo box. private class ComboListener implements ActionListener { // // Stops playing the current selection (if any) and resets // the current selection to the one chosen. public void actionPerformed (ActionEvent event) if (current != null) current.stop(); current = music[musicCombo.getSelectedIndex()]; Copyright © 2012 Pearson Education, Inc.
1061
//*****************************************************************
continue //***************************************************************** // Represents the action listener for both control buttons. private class ButtonListener implements ActionListener { // // Stops the current selection (if any) in either case. If // the play button was pressed, start playing it again. public void actionPerformed (ActionEvent event) if (current != null) current.stop(); if (event.getSource() == playButton) current.play(); } Copyright © 2012 Pearson Education, Inc.
1062
Outline Exception Handling The try-catch Statement Exception Classes
I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes Copyright © 2012 Pearson Education, Inc.
1063
Scroll Panes A scroll pane is useful for images or information too large to fit in a reasonably-sized area A scroll pane offers a limited view of the component it contains It provides vertical and/or horizontal scroll bars that allow the user to scroll to other areas of the component No event listener is needed for a scroll pane See TransitMap.java Copyright © 2012 Pearson Education, Inc.
1064
//********************************************************************
// TransitMap.java Authors: Lewis/Loftus // // Demonstrates the use a scroll pane. import java.awt.*; import javax.swing.*; public class TransitMap { // // Presents a frame containing a scroll pane used to view a large // map of the Philadelphia subway system. public static void main (String[] args) // SEPTA = SouthEast Pennsylvania Transit Authority JFrame frame = new JFrame ("SEPTA Transit Map"); continue Copyright © 2012 Pearson Education, Inc.
1065
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
continue frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); ImageIcon image = new ImageIcon ("septa.jpg"); JLabel imageLabel = new JLabel (image); JScrollPane sp = new JScrollPane (imageLabel); sp.setPreferredSize (new Dimension (450, 400)); frame.getContentPane().add (sp); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
1066
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
continue frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); ImageIcon image = new ImageIcon ("septa.jpg"); JLabel imageLabel = new JLabel (image); JScrollPane sp = new JScrollPane (imageLabel); sp.setPreferredSize (new Dimension (450, 400)); frame.getContentPane().add (sp); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
1067
Split Panes A split pane is a container that displays two components separated by a moveable divider bar The two components can be displayed side by side, or one on top of the other Copyright © 2012 Pearson Education, Inc.
1068
Split Panes The orientation of the split pane is set using the HORIZONTAL_SPLIT or VERTICAL_SPLIT constants The divider bar can be set so that it can be fully expanded with one click of the mouse The components can be continuously adjusted as the divider bar is moved, or wait until it stops moving Split panes can be nested Copyright © 2012 Pearson Education, Inc.
1069
Lists The Swing Jlist class represents a list of items from which the user can choose The contents of a JList object can be specified using an array of objects A JList object generates a list selection event when the current selection changes See PickImage.java See ListPanel.java Copyright © 2012 Pearson Education, Inc.
1070
//********************************************************************
// PickImage.java Authors: Lewis/Loftus // // Demonstrates the use a split pane and a list. import java.awt.*; import javax.swing.*; public class PickImage { // // Creates and displays a frame containing a split pane. The // user selects an image name from the list to be displayed. public static void main (String[] args) JFrame frame = new JFrame ("Pick Image"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); continue Copyright © 2012 Pearson Education, Inc.
1071
JLabel imageLabel = new JLabel(); JPanel imagePanel = new JPanel();
continue JLabel imageLabel = new JLabel(); JPanel imagePanel = new JPanel(); imagePanel.add (imageLabel); imagePanel.setBackground (Color.white); ListPanel imageList = new ListPanel (imageLabel); JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageList, imagePanel); sp.setOneTouchExpandable (true); frame.getContentPane().add (sp); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
1072
JLabel imageLabel = new JLabel(); JPanel imagePanel = new JPanel();
continue JLabel imageLabel = new JLabel(); JPanel imagePanel = new JPanel(); imagePanel.add (imageLabel); imagePanel.setBackground (Color.white); ListPanel imageList = new ListPanel (imageLabel); JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageList, imagePanel); sp.setOneTouchExpandable (true); frame.getContentPane().add (sp); frame.pack(); frame.setVisible(true); } Copyright © 2012 Pearson Education, Inc.
1073
//********************************************************************
// ListPanel.java Authors: Lewis/Loftus // // Represents the list of images for the PickImage program. import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class ListPanel extends JPanel { private JLabel label; private JList list; continue Copyright © 2012 Pearson Education, Inc.
1074
//-----------------------------------------------------------------
continue // // Loads the list of image names into the list. public ListPanel (JLabel imageLabel) { label = imageLabel; String[] fileNames = { "circuit.gif", "duke.gif", "hammock.gif", "justin.jpg", "kayla.jpg", "tiger.jpg", "toucan.gif", "worldmap.gif" }; list = new JList (fileNames); list.addListSelectionListener (new ListListener()); list.setSelectionMode (ListSelectionModel.SINGLE_SELECTION); add (list); setBackground (Color.white); } Copyright © 2012 Pearson Education, Inc.
1075
//*****************************************************************
continue //***************************************************************** // Represents the listener for the list of images. private class ListListener implements ListSelectionListener { public void valueChanged (ListSelectionEvent event) if (list.isSelectionEmpty()) label.setIcon (null); else String fileName = (String)list.getSelectedValue(); ImageIcon image = new ImageIcon (fileName); label.setIcon (image); } Copyright © 2012 Pearson Education, Inc.
1076
Lists A JList object can be set so that multiple items can be selected at the same time The list selection mode can be one of three options: single selection – only one item can be selected at a time single interval selection – multiple, contiguous items can be selected at a time multiple interval selection – any combination of items can be selected The list selection mode is defined by a ListSelectionModel object Copyright © 2012 Pearson Education, Inc.
1077
Summary Chapter 11 has focused on: the purpose of exceptions
exception messages the try-catch statement propagating exceptions the exception class hierarchy GUI mnemonics and tool tips more GUI components and containers Copyright © 2012 Pearson Education, Inc.
1078
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 12 Recursion Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
1079
Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems Chapter 12 focuses on: thinking in a recursive manner programming in a recursive manner the correct use of recursion recursion examples Copyright © 2012 Pearson Education, Inc.
1080
Outline Recursive Thinking Recursive Programming Using Recursion
Recursion in Graphics Copyright © 2012 Pearson Education, Inc.
1081
Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word, a recursive definition is often not helpful But in other situations, a recursive definition can be an appropriate way to express a concept Before applying recursion to programming, it is best to practice thinking recursively Copyright © 2012 Pearson Education, Inc.
1082
Recursive Definitions
Consider the following list of numbers: 24, 88, 40, 37 Such a list can be defined as follows: A List is a: number or a: number comma List That is, a List is defined to be a single number, or a number followed by a comma followed by a List The concept of a List is used to define itself Copyright © 2012 Pearson Education, Inc.
1083
Recursive Definitions
The recursive part of the LIST definition is used several times, terminating with the non-recursive part: Copyright © 2012 Pearson Education, Inc.
1084
Infinite Recursion All recursive definitions have to have a non- recursive part called the base case If they didn't, there would be no way to terminate the recursive path Such a definition would cause infinite recursion This problem is similar to an infinite loop, but the non-terminating "loop" is part of the definition itself Copyright © 2012 Pearson Education, Inc.
1085
Recursive Factorial N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive This definition can be expressed recursively as: 1! = 1 N! = N * (N-1)! A factorial is defined in terms of another factorial Eventually, the base case of 1! is reached Copyright © 2012 Pearson Education, Inc.
1086
Recursive Factorial 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 120 24 6 2
Copyright © 2012 Pearson Education, Inc.
1087
Quick Check Write a recursive definition of 5 * n, where n > 0.
Copyright © 2012 Pearson Education, Inc.
1088
Quick Check Write a recursive definition of 5 * n, where n > 0.
5 * 1 = 5 5 * n = 5 + (5 * (n-1)) Copyright © 2012 Pearson Education, Inc.
1089
Outline Recursive Thinking Recursive Programming Using Recursion
Recursion in Graphics Copyright © 2012 Pearson Education, Inc.
1090
Recursive Programming
A recursive method is a method that invokes itself A recursive method must be structured to handle both the base case and the recursive case Each call to the method sets up a new execution environment, with new parameters and local variables As with any method call, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself) Copyright © 2012 Pearson Education, Inc.
1091
Sum of 1 to N Consider the problem of computing the sum of all the numbers between 1 and any positive integer N This problem can be recursively defined as: Copyright © 2012 Pearson Education, Inc.
1092
Sum of 1 to N The summation could be implemented recursively as follows: // This method returns the sum of 1 to num public int sum (int num) { int result; if (num == 1) result = 1; else result = num + sum (n-1); return result; } Copyright © 2012 Pearson Education, Inc.
1093
Sum of 1 to N Copyright © 2012 Pearson Education, Inc.
1094
Recursive Programming
Note that just because we can use recursion to solve a problem, doesn't mean we should We usually would not use recursion to solve the summation problem, because the iterative version is easier to understand However, for some problems, recursion provides an elegant solution, often cleaner than an iterative version You must carefully decide whether recursion is the correct technique for any problem Copyright © 2012 Pearson Education, Inc.
1095
Indirect Recursion A method invoking itself is considered to be direct recursion A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again For example, method m1 could invoke m2, which invokes m3, which in turn invokes m1 again This is called indirect recursion, and requires all the same care as direct recursion It is often more difficult to trace and debug Copyright © 2012 Pearson Education, Inc.
1096
Indirect Recursion Copyright © 2012 Pearson Education, Inc.
1097
Outline Recursive Thinking Recursive Programming Using Recursion
Recursion in Graphics Copyright © 2012 Pearson Education, Inc.
1098
Maze Traversal We can use recursion to find a path through a maze
From each location, we can search in each direction The recursive calls keep track of the path through the maze The base case is an invalid move or reaching the final destination See MazeSearch.java See Maze.java Copyright © 2012 Pearson Education, Inc.
1099
//********************************************************************
// MazeSearch.java Author: Lewis/Loftus // // Demonstrates recursion. public class MazeSearch { // // Creates a new maze, prints its original form, attempts to // solve it, and prints out its final form. public static void main (String[] args) Maze labyrinth = new Maze(); System.out.println (labyrinth); if (labyrinth.traverse (0, 0)) System.out.println ("The maze was successfully traversed!"); else System.out.println ("There is no possible path."); } Copyright © 2012 Pearson Education, Inc.
1100
Output The maze was successfully traversed! //******************************************************************** // MazeSearch.java Author: Lewis/Loftus // // Demonstrates recursion. public class MazeSearch { // // Creates a new maze, prints its original form, attempts to // solve it, and prints out its final form. public static void main (String[] args) Maze labyrinth = new Maze(); System.out.println (labyrinth); if (labyrinth.traverse (0, 0)) System.out.println ("The maze was successfully traversed!"); else System.out.println ("There is no possible path."); } Copyright © 2012 Pearson Education, Inc.
1101
//********************************************************************
// Maze.java Author: Lewis/Loftus // // Represents a maze of characters. The goal is to get from the // top left corner to the bottom right, following a path of 1s. public class Maze { private final int TRIED = 3; private final int PATH = 7; private int[][] grid = { {1,1,1,0,1,1,0,0,0,1,1,1,1}, {1,0,1,1,1,0,1,1,1,1,0,0,1}, {0,0,0,0,1,0,1,0,1,0,1,0,0}, {1,1,1,0,1,1,1,0,1,0,1,1,1}, {1,0,1,0,0,0,0,1,1,1,0,0,1}, {1,0,1,1,1,1,1,1,0,1,1,1,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,1,1,1,1,1,1,1,1,1,1,1} }; continued Copyright © 2012 Pearson Education, Inc.
1102
if (done) // this location is part of the final path
continued if (done) // this location is part of the final path grid[row][column] = PATH; } return done; // // Determines if a specific location is valid. private boolean valid (int row, int column) { boolean result = false; // check if cell is in the bounds of the matrix if (row >= 0 && row < grid.length && column >= 0 && column < grid[row].length) // check if cell is not blocked and not previously tried if (grid[row][column] == 1) result = true; return result; Copyright © 2012 Pearson Education, Inc.
1103
//-----------------------------------------------------------------
continued // // Returns the maze as a string. public String toString () { String result = "\n"; for (int row=0; row < grid.length; row++) for (int column=0; column < grid[row].length; column++) result += grid[row][column] + ""; result += "\n"; } return result; Copyright © 2012 Pearson Education, Inc.
1104
Towers of Hanoi The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide onto the pegs The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller ones on top The goal is to move all of the disks from one peg to another under the following rules: Move only one disk at a time A larger disk cannot be put on top of a smaller one Copyright © 2012 Pearson Education, Inc.
1105
Original Configuration
Towers of Hanoi Original Configuration Move 1 Move 2 Move 3
1106
Towers of Hanoi Move 4 Move 5 Move 6 Move 7 (done)
1107
Towers of Hanoi An iterative solution to the Towers of Hanoi is quite complex A recursive solution is much shorter and more elegant See SolveTowers.java See TowersOfHanoi.java Copyright © 2012 Pearson Education, Inc.
1108
//********************************************************************
// SolveTowers.java Author: Lewis/Loftus // // Demonstrates recursion. public class SolveTowers { // // Creates a TowersOfHanoi puzzle and solves it. public static void main (String[] args) TowersOfHanoi towers = new TowersOfHanoi (4); towers.solve(); } Copyright © 2012 Pearson Education, Inc.
1109
Output Move one disk from 1 to 2 Move one disk from 1 to 3
//******************************************************************** // SolveTowers.java Author: Lewis/Loftus // // Demonstrates recursion. public class SolveTowers { // // Creates a TowersOfHanoi puzzle and solves it. public static void main (String[] args) TowersOfHanoi towers = new TowersOfHanoi (4); towers.solve(); } Copyright © 2012 Pearson Education, Inc.
1110
//********************************************************************
// TowersOfHanoi.java Author: Lewis/Loftus // // Represents the classic Towers of Hanoi puzzle. public class TowersOfHanoi { private int totalDisks; // // Sets up the puzzle with the specified number of disks. public TowersOfHanoi (int disks) totalDisks = disks; } // Performs the initial call to moveTower to solve the puzzle. // Moves the disks from tower 1 to tower 3 using tower 2. public void solve () moveTower (totalDisks, 1, 3, 2); continued Copyright © 2012 Pearson Education, Inc.
1111
//-----------------------------------------------------------------
continued // // Moves the specified number of disks from one tower to another // by moving a subtower of n-1 disks out of the way, moving one // disk, then moving the subtower back. Base case of 1 disk. private void moveTower (int numDisks, int start, int end, int temp) { if (numDisks == 1) moveOneDisk (start, end); else moveTower (numDisks-1, start, temp, end); moveTower (numDisks-1, temp, end, start); } // Prints instructions to move one disk from the specified start // tower to the specified end tower. private void moveOneDisk (int start, int end) System.out.println ("Move one disk from " + start + " to " + end); Copyright © 2012 Pearson Education, Inc.
1112
Outline Recursive Thinking Recursive Programming Using Recursion
Recursion in Graphics Copyright © 2012 Pearson Education, Inc.
1113
Tiled Pictures Consider the task of repeatedly displaying a set of images in a mosaic Three quadrants contain individual images Upper-left quadrant repeats pattern The base case is reached when the area for the images shrinks to a certain size See TiledPictures.java Copyright © 2012 Pearson Education, Inc.
1114
//********************************************************************
// TiledPictures.java Author: Lewis/Loftus // // Demonstrates the use of recursion. import java.awt.*; import javax.swing.JApplet; public class TiledPictures extends JApplet { private final int APPLET_WIDTH = 320; private final int APPLET_HEIGHT = 320; private final int MIN = 20; // smallest picture size private Image world, everest, goat; continue Copyright © 2012 Pearson Education, Inc.
1115
//-----------------------------------------------------------------
continue // // Loads the images. public void init() { world = getImage (getDocumentBase(), "world.gif"); everest = getImage (getDocumentBase(), "everest.gif"); goat = getImage (getDocumentBase(), "goat.gif"); setSize (APPLET_WIDTH, APPLET_HEIGHT); } // Draws the three images, then calls itself recursively. public void drawPictures (int size, Graphics page) page.drawImage (everest, 0, size/2, size/2, size/2, this); page.drawImage (goat, size/2, 0, size/2, size/2, this); page.drawImage (world, size/2, size/2, size/2, size/2, this); if (size > MIN) drawPictures (size/2, page); Copyright © 2012 Pearson Education, Inc.
1116
//-----------------------------------------------------------------
continue // // Performs the initial call to the drawPictures method. public void paint (Graphics page) { drawPictures (APPLET_WIDTH, page); } Copyright © 2012 Pearson Education, Inc.
1117
//-----------------------------------------------------------------
continue // // Performs the initial call to the drawPictures method. public void paint (Graphics page) { drawPictures (APPLET_WIDTH, page); } Copyright © 2012 Pearson Education, Inc.
1118
Fractals A fractal is a geometric shape made up of the same pattern repeated in different sizes and orientations The Koch Snowflake is a particular fractal that begins with an equilateral triangle To get a higher order of the fractal, the sides of the triangle are replaced with angled line segments See KochSnowflake.java See KochPanel.java Copyright © 2012 Pearson Education, Inc.
1119
//********************************************************************
// KochSnowflake.java Author: Lewis/Loftus // // Demonstrates the use of recursion in graphics. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KochSnowflake extends JApplet implements ActionListener { private final int APPLET_WIDTH = 400; private final int APPLET_HEIGHT = 440; private final int MIN = 1, MAX = 9; private JButton increase, decrease; private JLabel titleLabel, orderLabel; private KochPanel drawing; private JPanel appletPanel, tools; continue Copyright © 2012 Pearson Education, Inc.
1120
//-----------------------------------------------------------------
continue // // Sets up the components for the applet. public void init() { tools = new JPanel (); tools.setLayout (new BoxLayout(tools, BoxLayout.X_AXIS)); tools.setPreferredSize (new Dimension (APPLET_WIDTH, 40)); tools.setBackground (Color.yellow); tools.setOpaque (true); titleLabel = new JLabel ("The Koch Snowflake"); titleLabel.setForeground (Color.black); increase = new JButton (new ImageIcon ("increase.gif")); increase.setPressedIcon (new ImageIcon ("increasePressed.gif")); increase.setMargin (new Insets (0, 0, 0, 0)); increase.addActionListener (this); decrease = new JButton (new ImageIcon ("decrease.gif")); decrease.setPressedIcon (new ImageIcon ("decreasePressed.gif")); decrease.setMargin (new Insets (0, 0, 0, 0)); decrease.addActionListener (this); Copyright © 2012 Pearson Education, Inc.
1121
orderLabel = new JLabel ("Order: 1");
continue orderLabel = new JLabel ("Order: 1"); orderLabel.setForeground (Color.black); tools.add (titleLabel); tools.add (Box.createHorizontalStrut (40)); tools.add (decrease); tools.add (increase); tools.add (Box.createHorizontalStrut (20)); tools.add (orderLabel); drawing = new KochPanel (1); appletPanel = new JPanel(); appletPanel.add (tools); appletPanel.add (drawing); getContentPane().add (appletPanel); setSize (APPLET_WIDTH, APPLET_HEIGHT); } Copyright © 2012 Pearson Education, Inc.
1122
//-----------------------------------------------------------------
continue // // Determines which button was pushed, and sets the new order // if it is in range. public void actionPerformed (ActionEvent event) { int order = drawing.getOrder(); if (event.getSource() == increase) order++; else order--; if (order >= MIN && order <= MAX) orderLabel.setText ("Order: " + order); drawing.setOrder (order); repaint(); } Copyright © 2012 Pearson Education, Inc.
1123
//-----------------------------------------------------------------
continue // // Determines which button was pushed, and sets the new order // if it is in range. public void actionPerformed (ActionEvent event) { int order = drawing.getOrder(); if (event.getSource() == increase) order++; else order--; if (order >= MIN && order <= MAX) orderLabel.setText ("Order: " + order); drawing.setOrder (order); repaint(); } Copyright © 2012 Pearson Education, Inc.
1124
Koch Snowflakes < x5, y5> < x1, y1> < x5, y5>
Becomes Copyright © 2012 Pearson Education, Inc.
1125
//********************************************************************
// KochPanel.java Author: Lewis/Loftus // // Represents a drawing surface on which to paint a Koch Snowflake. import java.awt.*; import javax.swing.JPanel; public class KochPanel extends JPanel { private final int PANEL_WIDTH = 400; private final int PANEL_HEIGHT = 400; private final double SQ = Math.sqrt(3.0) / 6; private final int TOPX = 200, TOPY = 20; private final int LEFTX = 60, LEFTY = 300; private final int RIGHTX = 340, RIGHTY = 300; private int current; // current order continue Copyright © 2012 Pearson Education, Inc.
1126
//-----------------------------------------------------------------
continue // // Draws the fractal recursively. The base case is order 1 for // which a simple straight line is drawn. Otherwise three // intermediate points are computed, and each line segment is // drawn as a fractal. public void drawFractal (int order, int x1, int y1, int x5, int y5, Graphics page) { int deltaX, deltaY, x2, y2, x3, y3, x4, y4; if (order == 1) page.drawLine (x1, y1, x5, y5); else deltaX = x5 - x1; // distance between end points deltaY = y5 - y1; x2 = x1 + deltaX / 3; // one third y2 = y1 + deltaY / 3; x3 = (int) ((x1+x5)/2 + SQ * (y1-y5)); // tip of projection y3 = (int) ((y1+y5)/2 + SQ * (x5-x1)); Copyright © 2012 Pearson Education, Inc.
1127
x4 = x1 + deltaX * 2/3; // two thirds y4 = y1 + deltaY * 2/3;
continue x4 = x1 + deltaX * 2/3; // two thirds y4 = y1 + deltaY * 2/3; drawFractal (order-1, x1, y1, x2, y2, page); drawFractal (order-1, x2, y2, x3, y3, page); drawFractal (order-1, x3, y3, x4, y4, page); drawFractal (order-1, x4, y4, x5, y5, page); } // // Performs the initial calls to the drawFractal method. public void paintComponent (Graphics page) { super.paintComponent (page); page.setColor (Color.green); drawFractal (current, TOPX, TOPY, LEFTX, LEFTY, page); drawFractal (current, LEFTX, LEFTY, RIGHTX, RIGHTY, page); drawFractal (current, RIGHTX, RIGHTY, TOPX, TOPY, page); Copyright © 2012 Pearson Education, Inc.
1128
//-----------------------------------------------------------------
continue // // Sets the fractal order to the value specified. public void setOrder (int order) { current = order; } // Returns the current order. public int getOrder () return current; Copyright © 2012 Pearson Education, Inc.
1129
Summary Chapter 12 has focused on: thinking in a recursive manner
programming in a recursive manner the correct use of recursion recursion examples Copyright © 2012 Pearson Education, Inc.
1130
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 13 Collections Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc.
1131
Collections A collection is an object that helps us organize and manage other objects Chapter 13 focuses on: the concept of a collection separating the interface from the implementation dynamic data structures linked lists queues and stacks trees and graphs generics Copyright © 2012 Pearson Education, Inc.
1132
Outline Collections and Data Structures Dynamic Representations
Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc.
1133
Collections A collection is an object that serves as a repository for other objects A collection provides services for adding, removing, and otherwise managing the elements it contains Sometimes the elements in a collection are ordered, sometimes they are not Sometimes collections are homogeneous, containing all the same type of objects, and sometimes they are heterogeneous Copyright © 2012 Pearson Education, Inc.
1134
Abstraction Collections can be implemented in many different ways
Collections should be abstractions That is, they should hide unneeded details We want to separate the interface of the structure from its underlying implementation This helps manage complexity and makes it possible to change the implementation without changing the interface Copyright © 2012 Pearson Education, Inc.
1135
Abstract Data Types An abstract data type (ADT) is an organized collection of information and a set of operations used to manage that information The set of operations defines the interface to the ADT In one sense, as long as the ADT fulfills the promises of the interface, it doesn't matter how the ADT is implemented Objects are a good programming mechanism to create ADTs because their internal details are encapsulated Copyright © 2012 Pearson Education, Inc.
1136
Outline Collections and Data Structures Dynamic Representations
Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc.
1137
Dynamic Structures A static data structure has a fixed size
This meaning is different from the meaning of the static modifier Arrays are static; once you define the number of elements it can hold, the size doesn’t change A dynamic data structure grows and shrinks at execution time as required by its contents A dynamic data structure is implemented using object references as links Copyright © 2012 Pearson Education, Inc.
1138
Object References Recall that an object reference is a variable that stores the address of an object A reference also can be called a pointer References often are depicted graphically: student John Smith 40725 3.58 Copyright © 2012 Pearson Education, Inc.
1139
References as Links Object references can be used to create links between objects Suppose a class contains a reference to another object of the same class: class Node { int info; Node next; } Copyright © 2012 Pearson Education, Inc.
1140
References as Links References can be used to create a variety of linked structures, such as a linked list: Copyright © 2012 Pearson Education, Inc.
1141
Intermediate Nodes The objects being stored should not be concerned with the details of the data structure in which they may be stored For example, the Student class should not have to store a link to the next Student object in the list Instead, use a separate node class with two parts: a reference to an independent object a link to the next node in the list The internal representation becomes a linked list of nodes Copyright © 2012 Pearson Education, Inc.
1142
Magazine Collection Let’s explore an example of a collection of Magazine objects, managed by the MagazineList class, which has an private inner class called MagazineNode See MagazineRack.java See MagazineList.java See Magazine.java Copyright © 2012 Pearson Education, Inc.
1143
//*******************************************************************
// MagazineRack.java Author: Lewis/Loftus // // Driver to exercise the MagazineList collection. public class MagazineRack { // // Creates a MagazineList object, adds several magazines to the // list, then prints it. public static void main (String[] args) MagazineList rack = new MagazineList(); rack.add (new Magazine("Time")); rack.add (new Magazine("Woodworking Today")); rack.add (new Magazine("Communications of the ACM")); rack.add (new Magazine("House and Garden")); rack.add (new Magazine("GQ")); System.out.println (rack); } Copyright © 2012 Pearson Education, Inc.
1144
Output Time Woodworking Today Communications of the ACM
House and Garden GQ //******************************************************************* // MagazineRack.java Author: Lewis/Loftus // // Driver to exercise the MagazineList collection. public class MagazineRack { // // Creates a MagazineList object, adds several magazines to the // list, then prints it. public static void main (String[] args) MagazineList rack = new MagazineList(); rack.add (new Magazine("Time")); rack.add (new Magazine("Woodworking Today")); rack.add (new Magazine("Communications of the ACM")); rack.add (new Magazine("House and Garden")); rack.add (new Magazine("GQ")); System.out.println (rack); } Copyright © 2012 Pearson Education, Inc.
1145
//*******************************************************************
// MagazineList.java Author: Lewis/Loftus // // Represents a collection of magazines. public class MagazineList { private MagazineNode list; // // Sets up an initially empty list of magazines. public MagazineList() list = null; } continue Copyright © 2012 Pearson Education, Inc.
1146
//----------------------------------------------------------------
continue // // Creates a new MagazineNode object and adds it to the end of // the linked list. public void add (Magazine mag) { MagazineNode node = new MagazineNode (mag); MagazineNode current; if (list == null) list = node; else current = list; while (current.next != null) current = current.next; current.next = node; } Copyright © 2012 Pearson Education, Inc.
1147
//----------------------------------------------------------------
continue // // Returns this list of magazines as a string. public String toString () { String result = ""; MagazineNode current = list; while (current != null) result += current.magazine + "\n"; current = current.next; } return result; Copyright © 2012 Pearson Education, Inc.
1148
//*****************************************************************
continue //***************************************************************** // An inner class that represents a node in the magazine list. // The public variables are accessed by the MagazineList class. private class MagazineNode { public Magazine magazine; public MagazineNode next; // // Sets up the node public MagazineNode (Magazine mag) magazine = mag; next = null; } Copyright © 2012 Pearson Education, Inc.
1149
//********************************************************************
// Magazine.java Author: Lewis/Loftus // // Represents a single magazine. public class Magazine { private String title; // // Sets up the new magazine with its title. public Magazine (String newTitle) title = newTitle; } // Returns this magazine as a string. public String toString () return title; Copyright © 2012 Pearson Education, Inc.
1150
Inserting a Node A node can be inserted into a linked list with a few reference changes: Copyright © 2012 Pearson Education, Inc.
1151
Quick Check Write code that inserts newNode after the node pointed to by current. Copyright © 2012 Pearson Education, Inc.
1152
Quick Check Write code that inserts newNode after the node pointed to by current. newNode.next = current.next; current.next = newNode; Copyright © 2012 Pearson Education, Inc.
1153
Deleting a Node Likewise, a node can be removed from a linked list by changing the next pointer of the preceding node: Copyright © 2012 Pearson Education, Inc.
1154
Other Dynamic Representations
It may be convenient to implement a list as a doubly linked list, with next and previous references: Copyright © 2012 Pearson Education, Inc.
1155
Other Dynamic Representations
Another approach is to use a separate header node, with a count and references to both the front and rear of the list: Copyright © 2012 Pearson Education, Inc.
1156
Outline Collections and Data Structures Dynamic Representations
Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc.
1157
Classic Data Structures
Now we'll examine some common data structures that are helpful in many situations Classic linear data structures include queues and stacks Classic nonlinear data structures include trees and graphs Copyright © 2012 Pearson Education, Inc.
1158
Queues A queue is a list that adds items only to the rear of the list and removes them only from the front It is a FIFO data structure: First-In, First-Out Analogy: a line of people at a bank teller’s window Copyright © 2012 Pearson Education, Inc.
1159
Queues Classic operations for a queue
enqueue - add an item to the rear of the queue dequeue (or serve) - remove an item from the front of the queue empty - returns true if the queue is empty Queues often are helpful in simulations or any situation in which items get “backed up” while awaiting processing Copyright © 2012 Pearson Education, Inc.
1160
Queues A queue can be represented by a singly-linked list; it is most efficient if the references point from the front toward the rear of the queue A queue can be represented by an array, using the remainder operator (%) to “wrap around” when the end of the array is reached and space is available at the front of the array Copyright © 2012 Pearson Education, Inc.
1161
Stacks A stack ADT is also linear, like a list or a queue
Items are added and removed from only one end of a stack It is therefore LIFO: Last-In, First-Out Analogies: a stack of plates or a stack of books Copyright © 2012 Pearson Education, Inc.
1162
Stacks Stacks often are drawn vertically:
Copyright © 2012 Pearson Education, Inc.
1163
Stacks Clasic stack operations:
push - add an item to the top of the stack pop - remove an item from the top of the stack peek (or top) - retrieves the top item without removing it empty - returns true if the stack is empty A stack can be represented by a singly-linked list, with the first node in the list being to top element on the stack A stack can also be represented by an array, with the bottom of the stack at index 0 Copyright © 2012 Pearson Education, Inc.
1164
Stacks The java.util package contains a Stack class
The Stack operations operate on Object references Suppose a message has been encoded by reversing the letters of each word See Decode.java Copyright © 2012 Pearson Education, Inc.
1165
//********************************************************************
// Decode.java Author: Lewis/Loftus // // Demonstrates the use of the Stack class. import java.util.*; public class Decode { // // Decodes a message by reversing each word in a string. public static void main (String[] args) Scanner scan = new Scanner (System.in); Stack word = new Stack(); String message; int index = 0; System.out.println ("Enter the coded message:"); message = scan.nextLine(); System.out.println ("The decoded message is:"); continue Copyright © 2012 Pearson Education, Inc.
1166
while (index < message.length()) { // Push word onto stack
continue while (index < message.length()) { // Push word onto stack while (index < message.length() && message.charAt(index) != ' ') word.push (new Character(message.charAt(index))); index++; } // Print word in reverse while (!word.empty()) System.out.print (((Character)word.pop()).charValue()); System.out.print (" "); System.out.println(); Copyright © 2012 Pearson Education, Inc.
1167
Sample Run Enter the coded message: artxE eseehc esaelp
The decoded message is: Extra cheese please continue while (index < message.length()) { // Push word onto stack while (index < message.length() && message.charAt(index) != ' ') word.push (new Character(message.charAt(index))); index++; } // Print word in reverse while (!word.empty()) System.out.print (((Character)word.pop()).charValue()); System.out.print (" "); System.out.println(); Copyright © 2012 Pearson Education, Inc.
1168
Outline Collections and Data Structures Dynamic Representations
Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc.
1169
Trees A tree is a non-linear data structure that consists of a root node and potentially many levels of additional nodes that form a hierarchy Nodes that have no children are called leaf nodes Nodes except for the root and leaf nodes are called internal nodes In a general tree, each node can have many child nodes Copyright © 2012 Pearson Education, Inc.
1170
A General Tree Copyright © 2012 Pearson Education, Inc.
1171
Binary Trees In a binary tree, each node can have no more than two child nodes Trees are typically are represented using references as dynamic links For binary trees, this requires storing only two links per node to the left and right child Copyright © 2012 Pearson Education, Inc.
1172
Graphs A graph is another non-linear structure
Unlike a tree, a graph does not have a root Any node in a graph can be connected to any other node by an edge Analogy: the highway system connecting cities on a map Copyright © 2012 Pearson Education, Inc.
1173
Graphs Copyright © 2012 Pearson Education, Inc.
1174
Digraphs In a directed graph or digraph, each edge has a specific direction. Edges with direction sometimes are called arcs Analogy: airline flights between airports Copyright © 2012 Pearson Education, Inc.
1175
Digraphs Copyright © 2012 Pearson Education, Inc.
1176
Representing Graphs Both graphs and digraphs can be represented using dynamic links or using arrays. As always, the representation should facilitate the intended operations and make them convenient to implement Copyright © 2012 Pearson Education, Inc.
1177
Outline Collections and Data Structures Dynamic Representations
Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc.
1178
Collection Classes The Java standard library contains several classes that represent collections, often referred to as the Java Collections API Their underlying implementation is implied in the class names such as ArrayList and LinkedList Several interfaces are used to define operations on the collections, such as List, Set, SortedSet, Map, and SortedMap Copyright © 2012 Pearson Education, Inc.
1179
Generics As mentioned in Chapter 5, Java supports generic types, which are useful when defining collections A class can be defined to operate on a generic data type which is specified when the class is instantiated: LinkedList<Book> myList = new LinkedList<Book>(); By specifying the type stored in a collection, only objects of that type can be added to it Furthermore, when an object is removed, its type is already established Copyright © 2012 Pearson Education, Inc.
1180
Summary Chapter 13 has focused on: the concept of a collection
separating the interface from the implementation dynamic data structures linked lists queues and stacks trees and graphs generics Copyright © 2012 Pearson Education, Inc.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.