Você está na página 1de 475

Complete Instructors Manual For Bronsons Object Oriented Program Development Using Java: A Class Centered Approach Philip

King and Paul A. Nagin

Complete Instructors Manual For Bronsons Object Oriented Program Development Using Java: A Class Centered Approach

Philip King and Paul A. Nagin, Ph.D. Chimborazo, LLC

CONTENTS: Chapter 1........................................................................................Page 1 Chapter 2........................................................................................Page 15 Chapter 3........................................................................................Page 32 Chapter 4........................................................................................Page 49 Chapter 5........................................................................................Page 70 Chapter 6........................................................................................Page 96 Chapter 7......................................................................................Page 123 Chapter 8......................................................................................Page 135 Chapter 9......................................................................................Page 155 Chapter 10....................................................................................Page 165 Chapter 11....................................................................................Page 205 Chapter 12....................................................................................Page 217 Chapter 13....................................................................................Page 244 Chapter 14....................................................................................Page 265

Note: Each chapter contains the following material I. Overview Key Concepts Problem Areas II. Answers to odd-numbered exercises III. Sample test bank and answers Note: All programming solutions were tested in Visual Studio 6.0.

Page

I. OVERVIEW: Chapter 1 Introduction This chapter provides an introduction to computer science and a brief background on programming languages. The concepts of objects and classes are explained and a specific structure that will be used throughout the text for constructing Java classes and programs is presented. Additionally, two specific classes provided in Java for displaying output are presented; one that contains methods for displaying text on a video screen and one for constructing a simple graphical user interface (GUI) using graphical shapes. Both of these class methods are used within the context of a complete program for displaying data on a video screen. 1.1 Computer Science and Programming Languages Programming Languages 1.2 Objects and Classes A First Java Class 1.3. Constructing a Java Program 1.4 The PrintStream class' print() and println() Methods 1.5 Using the javax.swing Package 1.6 Programming Style 1.7 Common Programming Errors 1.8 Chapter Review 1.9 Chapter Supplement: Computer Hardware Potential Problem areas: This chapter is a straightforward introduction to programming languages and program design concepts. It has the advantage of getting the students onto the computer almost immediately. It provides a brief background into computing concepts and should not be a problem for any students. The GUI method calls can be a bit overwhelming for beginning students.

Page

NOTE: Be sure the students understand how to set up the Java environment and how to create and build a program. This can be a major source of confusion.

Page

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 1.1 1. Define the following terms: a. Computer Program A computer program is a self contained set of instructions and data used to operate a computer to produce a specific result. This term can be used interchangeably with the term software. b. Programming Programming is the process of developing and writing a program or software. c. Programming Language The programming language is a set of instructions that can be used to construct a program. d. High-Level Language A programming language that uses instructions that resemble natural languages, such as English, and can be run on a variety of computer types is a termed a high-level language. e. Low-Level Language A programming language type that uses instructions that are directly tied to one type of computer is a low-level language. f. Machine Language Machine language is the language upon which all computers fundamentally operate. g. Assembly Language

Page

A low-level computer language aimed at simplifying programming. It uses easy to read symbols that represent the opcodes used in machine language. h. Procedure-Oriented Language In a procedure-oriented language the available instructions are used to create self-contained units referred to as procedures. i. Object-Oriented Language A type of programming language that requires the definition of the objects it will be creating. This includes describing both the general characteristics of the objects themselves and specific units to manipulate them. j. Source Program Programs written in a computer language are referred to as a source program (or source code). k. Compiler A compiler is a program that translates a high level program into a complete unit that is ready to be executed on the host machine. l. Assembler An assembler is a program that converts assembly language programs into machine language. 3. Describe the differences between assemblers, interpreters, and compilers Assemblers work only to translate assembly code into machine level instructions. Therefore, assemblers operate on low level languages. Interpreters and compilers operate on high level languages. The difference between an interpreter and a compiler is that an interpreter translates the instructions in a high level language individually and then

Page

executes those instructions immediately upon translation. A compiler on the other hand translates the entire high-level program into a complete unit before any instructions in the source program are executed. 5. Rewrite the machine level instructions listed in Exercise 4a using assembly language notation. Use the symbolic notation names ADD, SUB, MUL, and DIV for addition, subtraction, multiplications, and division operations respectively. In writing the instructions, use decimal values for the addresses. Opcod e 110000 00 111100 00 101000 00 110100 00 Solution: ADD MUL SUB DIV 1 2 4 5 2 3 3 3 1st Operand 00000000000 1 00000000001 0 00000000010 0 00000000010 1 2nd Operand 00000000000 10 00000000000 11 00000000000 11 00000000000 11

Exercises 1.2 1a. What are the two main sections of a Java class?

Page

The two main sections of a Java class are the data declarations section and the methods section. 1b. Within the first section of a Java class, what information must be provided? The minimum amount of information that must be provided within the data declarations section of a Java class is a list of the type of data needed for the class and a name for each of those data items. 1c. What information is provided by the second section in a Java class? The methods section of a Java class defines how to combine the data components that are listed in the data declarations section to produce a desired result. 3a. List the items that you would need to build a staircase having five steps. Concrete Wood Hammer Nails Saw Tape Measure

3b. Write a set of instructions for assembling the items listed in Exercise 3a. Use the saw, tape measure, hammer, and nails to create an open box shape out of the wood (four slabs of wood required to create this box). This box will serve as the frame for pouring and shaping the concrete into steps. The width of the box should be five times

Page

the width that one desires for each individual step. The length and height of the box should be the length and height desired for each step in the staircase. Fill the box with concrete and allow the concrete to dry. This block becomes the base step. Create another box of the same length and height. The width however, should be only four times the width desired for each step. Place the new wooden frame on top of the previous concrete block and aligned at the back. Fill frame with concrete and allow to dry Repeat the previous three steps. At each iteration decrement the width of the next block of concrete by the width desired for each individual step (while keeping constant the other two dimensions) until one arrives at the desired number of steps (which in this case is five). 5. Obtain a set of assembly instructions from a recent item that you have built (for example, a bicycle or a backyard basketball hoop). Identify the major elements in the assembly instructions that correspond to the section and items listed in Figure 1-9. The students should find a set of assembly instructions and categorize the items as specified. Answers will depend greatly upon the person answering. 7. Assume you are to create a plan for a Java program that simulates the tossing of a single die. For this plan, list the data item(s) and a set of methods that would be useful for such a

Page

program. Select a class name and data item names of your own choosing. Class Name: TossDie Class Data Declaration Section: dieNumber: An integer between 1-6 that corresponds to the last number rolled on the die Class Method Definition Section: initializeDie: A method to set the die to some known value rollDie: A method to simulate the rolling of the die getLastRoll: A method for telling the programmer the last number rolled 9. Assume that you are to create a Java program that calculates the floor space of a rectangular room. For this plan, list the data item(s) and a set of methods that would be useful for such a program. Select a class name and data item names of your own choosing. Class Name: ComputeFloorSpace Class Data Declaration Section: width: A real number corresponding to the width of a room length: A real number corresponding to the length of a room Class Method Definition Section: initialize: A method to set the class items to some known value

Page

getWidth: A method for letting the programmer know the room width getLength: A method for letting the programmer know the room length getArea: Uses the length and width to calculate the floor area 11. Assume that you are to create a Java program that calculates and displays the volume of a cylinder. List the data item(s) and a set of methods that would be useful for such a program. Select a class name and data item names of your own choosing. Class Name: ComputeCylinderVolume Class Data Declaration Section: o radius: A real number storing the radius of the cylinder o length: A real number storing the length of the cylinder Class Method Definition Section: o initializeCylinder: Sets the class data items to some known value o getRadius: Lets the programmer know the radius of the cylinder o getLength: Lets the programmer know the length of the cylinder o computeVolume: Computes the volume of the cylinder 13. Enter and compile the class provided in Figure 1-13. Students should enter and compile the program in Figure 1-13.

Page

10

15. Modify the ShowFirstMessage class (Figure 1-13) to display the message I hate coffee!. public class ShowFirstMessage { private String message; ShowFirstMessage() { message = I hate coffee!; } public void displayMessage() { System.out.println(message); } } Exercises 1.3 1. State whether the following are valid identifiers. If they are valid, state whether or not they are descriptive. A mnemonic identifier conveys some idea about its intended purpose. If they are invalid identifiers, state why. Im1234 is valid but not descriptive power is valid and descriptive add5 is valid and descriptive newBalance is valid and descriptive newBal is valid and descriptive absVal is valid and descriptive taxes is valid and descriptive a2b3c4d5 is valid but not descriptive abcd is valid but not descriptive

Page

11

invoices is valid and descriptive netPay is valid and descriptive salesTax is valid and descriptive A12345 is valid but not descriptive do is not valid because it is a reserved word 12345 is not valid because identifiers cannot start with a number 1A2345 is not valid because identifiers cannot start with numbers while is not valid because it is a reserved word int is not valid because it is a reserved word $taxes is valid and descriptive

3. Which of the following identifiers could be class names? All of the listed identifiers could possible be class names. By convention, the identifiers NewBalance, CardGame, SendMessage, CalculateTax, DisplayAMessage, and ComputeGPA are more likely to be class names as they all start with uppercase letters. Methods and variable names, by convention only, start with lowercase letters. 5. Just as the keyword void signifies that a method returns no value, the keywords int, char, float, and double signify that a method will return an integer, a character, a floating point number, and a double-precision number, respectively. Using this information, write header lines for a main method that returns: a. Integer public static int main(String[] args) b. Character public static char main(String[] args) c. Floating point public static float main(String[] args)

Page

12

d. Double precision main(String[] args) Exercises 1.4

public

static

double

1. Enter and execute QuickText Program 1-1 on your computer. Students should enter and execute the program. 3a. Using print(), write a Java program that displays your name on one line, your street address on the second line, and your city, state, and zip code on the third line. public class Address { public static void main(String[] args) { System.out.println(Philip King); System.out.println(1010 10th Street); System.out.println(Lubbock, TX, 79410); } } 3b. Run the program you have written for Exercise 3a. on your computer Students should run the program in Exercise 3a. 5a. What is the minimum number of print() methods you would need to display the following? PART NO. PRICE

Page

13

T1267 T1300 T2401 T4482

$6.34 $8.92 $65.40 $36.99

Only one print() method is required to print out the above table. The escape sequence \n will also be required. 5b. What is the minimum number of println() method calls needed to display the table in Exercise 5a? The programmer would need to use six println() method calls to generate the above table assuming that no print() method calls were also used. One println() is required to generate the underline pattern. 5c. What is the preferable number of either print() or println() methods you would use to produce the table shown in Exercise 5a? The preferred method to print out the six short lines of the table in Exercise 5a would be to use six println() statements as it results in code that is easiest to read. 5d. Write a complete Java program to produce the output illustrated in Exercise 5a. class DrawTable { public static void main(String[] { System.out.println(PART NO. System.out.println(-------System.out.println(T1267

args) PRICE); -----); $6.34);

Page

14

System.out.println(T1300 System.out.println(T2401 System.out.println(T4482 } }

$8.92); $65.40); $36.99);

5e. Run the program you have written for Exercise 5d on a computer. Students should compile and run the code in Exercise 5d. Exercises 1.5 1. Enter and run QuickTest Program 1-4 on your computer. Students should enter and run the specified program. 3. Write and execute a Java program that displays your name on one line, your street address on a second line, and your city, state, and zip code on the third line within a dialog box that uses an information icon. import javax.swing.*; public class DisplayAddress { public static void main(String[] args) { JOptionPane.showMessageDialog(null, Philip King\n1010 10th Street\nLubbock, TX, 79410, My Address, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }

Page

15

5. Write and execute a Java program that displays the following data in a dialog box that does not display and icon. Part No. T1267 T1300 Price $6.34 $8.92

import javax.swing.*; public class DisplayTable { public static void main(String[] args) { JOptionPane.showMessageDialog(null, Part No. Price\nT1267 $6.34\nT1300 $8.92, Table Example, JOptionPane.PLAIN_MESSAGE); } } System.exit(0);

Exercises 1.6 1a. Will the following program work? public class TestIt { public static void main(String[] args) {System.out.println(Hello World!);}} The above code will compile and execute without problems.

Page

16

1b. Why is the program given in Exercise 1a. not a good program? The code given is not a good program because it does not utilize proper indentation in order to make the program easier to read and understand.

Page

17

III. Sample Test Questions Chapter 1 1) Java is a ____ programming language. a) low-level b) high-level c) business-oriented d) CPU-oriented Answer: (B) 2) Object-oriented languages are especially well-suited for a) easy translation into machine language b) procedure-oriented environments c) assisting a programmer to choose the proper algorithm to use for her application d) GUI applications Answer: (D) 3) The Java language was originally designed for a) system applications b) scientific applications c) business applications d) consumer-electronics Answer: (D) 4) An algorithm

Page

18

a) is a step-by-step solution to a problem b) is no longer needed when using the Java language c) is similar to a logarithm d) concentrates on the syntactic solution to a problem Answer: (A)

5) An interpreted language a) translates and executes statements one line at a time b) translates statements and executes as a complete unit c) translates and executes statements from one human language to another d) attempts to understand hidden meaning in program code Answer: (A) 6) A compiled language a) translates and executes statements one line at a time b) translates statements and executes as a complete unit c) translates statements from one human language to another d) attempts to understand hidden meaning in program code Answer: (B) 7) The primary task of a compiler is to

Page

19

a) translate from source code to object code b) translate from object code to source code c) provide an algorithmic solution to a problem d) generate meaningful error messages Answer: (A) 8) The operations performed by a class are called a) objects b) syntax c) methods d) identifiers Answer: (C) 9) An identifier a) could begin with a letter or digit and can contain other letters, digits, or underscores b) could begin with a digit and can contain other letters, digits, or underscores c) could begin with a letter, digit, or underscore and can contain other letters, digits, or underscores d) could begin with a letter or underscore and can contain other letters, digits, or underscores. Answer: (D) 10) An identifiers name should be mnemonic. This means that it should

Page

20

a) give some indication as to its purpose b) be easy to spell c) be guaranteed to be a valid identifier in any standard programming language. d) be case sensitive Answer: (A) 11) System.out.println() a) sends data to the printer b) sends data to the screen c) receives data from the keyboard d) receives data from any input device Answer: (B) 12) In a println statement, the characters \n a) are collectively called a newline escape sequence b) are illegal c) cause the output to appear on a new device d) cause the output to show the characters \n Answer: (A) 13) Which of the following is an acceptable, one-line comment a) // comment text // b) /* comment text /* c) /* comment text

Page

21

d) /* comment text // Answer: (A) 14) A dialog a) can only be used to output information to the user b) is either a warning or an information message c) is not allowed with the swing package d) always requests user input Answer: (D) 15) A reserved word a) can be used as variable name in Java code b) can be easily redefined by the user in Java code c) cannot be used in Java source code d) is a predefined word with a special purpose in Java Answer: (D) 16) A package in Java a) typically consists of related classes that reside in the same directory b) consists of related classes residing across multiple directories c) cannot be created by a programmer d) typically consists of unrelated classes residing in the same directory Answer: (A)

Page

22

17) Which of the following is a characteristic of low-level languages a) requires a compiler to convert to machine code b) allows for very portable programs across various machines c) extremely slow execution time d) machine dependent Answer: (D) 18) The import statement a) is not needed in Java b) tells the compiler it can search for a particular class within the specified package c) places your source code into a package d) cannot use the asterisk to specify a class search within a package Answer: (B) 19) A literal string entered in Java source code CANNOT a) use escape sequences b) span multiple lines between a pair of quotation marks c) use both capital and lowercase letters d) be used as method parameters Answer: (B) 20) Every Java class is derived from

Page

23

a) the String class b) the OutputStream class c) the PrintStream class d) the Object class Answer: (D)

Page

24

I. OVERVIEW: Chapter 2 Writing Java Programs Java programs process different types of data in different ways. For example, calculating the bacteria growth in a polluted pond requires mathematical operations on numerical data, whereas sorting a list of names requires comparison operations using alphabetical data. Java has two fundamental types of data, known as primitive and reference types, respectively. In this chapter we introduce Java's primitive data types and the operations that can be performed on them. Additionally, we present the proper use of both class and method variables for storing both primitive and reference type data. We then show how to construct a completed class having both a data declaration and method definition section. Finally, we focus on assignment operations, which are extremely important in constructing class methods. 2.1 Data Values and Arithmetic Operations 2.2 Constructing a Data Declaration Section: Variables 2.3 Completing the Class: Methods 2.4 Assignment Operations Assignment Variations Accumulating Counting 2.5 Program Design and Development: Object Identification 2.6 Common Programming Errors 2.7 Chapter Review Potential Problem areas: Students new to programming will start to feel overwhelmed by the details. Object identification is introduced and will be a source of confusion for some time. Suggest that class time is spent doing group exercises in which students are asked to choose classes from a problem description.

Page

25

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 2.1 1. Determine data types appropriate for the following data: a. The average of two speeds Floating point data type b. The number of transistors in a circuit: Integer data type c. The length of the golden gate bridge Floating point data type d. The part numbers in a machine Integer data type e. The distance from Brooklyn, N.Y. to Newark, N.J. Floating point data type f. The single character prefix that specifies circuit components: Character data type 3. Convert the following decimal numbers into exponential notation 126 656.23 3426.95 4893.2 .321 .0123 .006789 1.26e2 6.5623e2 3.42695e3 4.8932e3 3.21e-1 1.23e-2 6.789e-3

Page

26

5a. Repeat Exercise 4a using the letters of your own last name. To store the last name KING, Java requires 8 bytes. 5b. Repeat Exercise 4b using the letters of your own last name K I N G 00000000 00000000 00000000 00000000 01001011 01001001 01001110 01000111

7. Determine the value of the following integer expressions: 1) 3 + 4 * 6 = 27 2) 3 * 4 / 6 + 6 = 12 / 6 + 6 = 8 3) 2 * 3 / 12 * 8 / 4 = 6 / 12 * 8 / 4 = 0 * 8 / 4 = 0 4) 10 * (1 + 7 * 3) = 10 * (1 + 21) = 10 * 22 = 220 5) 20 2 / 6 + 3 = 20 0 + 3 = 23 6) 20 2 / (6 + 3) = 20 2 / 9 = 20 0 = 20 7) (20 2) / 6 + 3 = 18 / 6 + 3 = 3 + 3 = 6 8) (20 2) / (6 + 3) = 18 / 9 = 2 9) 50 % 20 = 10 10) (10 + 3) % 4 = 13 % 4 = 1 9. Evaluate the following expressions and list the data type of the result. In evaluating the expressions be aware of the data types of all intermediate calculations. a. 10.0 + 15 / 2 + 4.3 10.0 + 7 + 4.3 = 21.3 (Floating point type returned)

b. 10.0 + 15.0 / 2 + 4.3 10.0 + 7.5 + 4.3 = 21.8

Page

27

(Floating point type returned) c. 3.0 * 4 / 6 + 6 d. 3 * 4.0 / 6 + 6 e. 20.0 2 / 6 + 3 f. 10 + 17 * 3 + 4 g. 10 + 17 / 3. + 4 19.6666(repeated) h. 3.0 * 4 % 6 + 6 i. 10 + 17 % 3 + 4. 12.0/6 + 6 = 2.0 + 6 = 8.0 (Floating point type returned) 12.0 / 6 + 6 = 2.0 + 6 = 8.0 (Floating point type returned) 20.0 0 + 3 = 23.0 (Floating point type returned) 10 + 51 + 4 = 65 (Integer type returned) 10 + 5.666(repeated) + 4 = (Floating point type returned) 12.0 % 6 + 6 = 0.0 + 6 = 6.0 (Floating point type returned) 10 + 2 + 4. = 16.0 (Floating point type returned)

11. Repeat Exercise 10 assuming that distance has the value 1.0, v has the value 50.0, n has the value 10.0, and t has the value 5.0. a. n / t + 3 10.0 / 5.0 + 3 = 2.0 + 3 = 5.0 b. v / t + n 10 * distance 50.0 / 5.0 + 10.0 10 * 1.0 = 10.0 + 10.0 10.0 = 10.0 c. v 3 * n + 4 * distance 50.0 3 * 10.0 + 4 * 1.0 = 50.0 30.0 + 4.0 = 24.0 d. distance / 5 1.0 / 5 = 0.2

Page

28

e. f. g. h.

18 / t t * n v / 20 (v + n) / (t + distance) 10.0 i. v + n / t + distance 1.0 = 53.0

18 / 5.0 = 3.6 -5.0 * 10.0 = -50.0 -50.0 / 20 = -2.5 (50.0 + 10.0) / (5.0 + 1.0) = 60.0 / 6.0 = 50.0 + 10.0 / 5.0 + 1.0 = 50.0 + 2.0 +

13. Enter and execute Program 2-1 on your computer Students should enter and execute the specified program. 15. Determine the output of the following program: public class Test2 { public static void main(String[] args) { System.out.println(The remainder of 9 divided by 4 is + (9 % 4)); System.out.println(The remainder of 17 divided by 3 is + (17 % 3)); } } Solution: The remainder of 9 divided by 4 is 1 The remainder of 17 divided by 3 is 2

Page

29

17. Write a Java program that displays the results of the expressions 15 / 4, 15 % 4, and 5 * 3 (6 * 4). Calculate the value of these expressions manually to verify that the displayed values are correct. public class DisplayStuff { public static void main(String[] args) { System.out.println(15 / 4 is + (15 / 4)); System.out.println(15 % 4 is + (15 % 4)); System.out.println(5 * 3 (6 * 4) is + (5 * 3 (6 * 4))); } } Exercises 2.2 1. State whether the following variable names are valid or invalid. If they are invalid, state the reason. proda valid newbal valid 9ab6 invalid (variable name cannot start with a number) c1234 valid while invalid (while is a reserved word) sum.of invalid (periods are not allowed in a variable name) abcd valid $total valid average valid

Page

30

_c3 valid new bal invalid (spaces are not allowed) grade1 valid 12345 invalid (variable names cannot start with a digit) a1b2c3d4 valid finGrad valid 3a. Write a declaration statement to declare that count will be an instance variable used to store an integer value. private int count; 3b. Write a declaration statement to declare that grade will be an instance variable used to store a single-precision number. private float grade; 3c. Write a declaration statement to declare that yield will be an instance variable used to store a character. private char yield; 5. Write declaration statements for the following instance variables (The keyword private may be replaced with another value) a. firstNumber and secondNumber used to store integers private int firstNumber; private int secondNumber; b. price, yield, and coupon used to store single-precision numbers

Page

31

private float price; private float yield; private float coupon; c. maturity used to store a double-precision number private double maturity; 7. Create a class structure for a class named Date. The data declaration section should have instance variables for data consisting of an integer month, integer day, and integer year. public class Date { private int month; private int day; private int year; } 9. Create a class structure for a class named Circle. The data declaration section should have an instance variable for data consisting of a single precision radius. public class Circle { private float radius; }

11. Compile and execute Program 2-2.

Page

32

Students should compile and execute the specified program. 13. Create a QuickTest Program named UseTwoNumbers that declares and creates two objects named firstPair and secondPair from the TwoNumbers class presented in this section. public class UseTwoNumbers { public static void main(String[] args) { TwoNumbers firstPair; TwoNumbers secondPair; firstPair = new TwoNumbers(); secondPair = new TwoNumbers(); } }

Exercises 2.3 1. Compile Program 2-2 Students should compile the specified program. 3. Compile Program 2-4 and execute Program 2-3 to use the RoomType class provided in Program 2-4. Verify that the output is the same as that produced in Exercise 2. Students should compile and execute the specified programs. 5. Modify the showValues() and calculateArea() methods in either Program 2-3 or Program 2-5 to display all values using a dialog box. import javax.swing.*; public void showValues()

Page

33

{ String message = length = + length + \n width = + width; JOptionPane.showMessageDialog(null, message, Class Values, JOptionPane.INF ORMATION_MESSAGE); } public void calculateArea() { String message = Areas = + (length * width); JOptionPane.showMessageDialog(null, message, Area, JOptionPane.INF ORMATION_MESSAGE); }

7a. Construct a Time class containing the integer data members seconds, minutes, and hours. Have the class contain a user-written default constructor that initializes each data member with a default value of 0. The final member method should be an accessor method that displays the value of all the data members. public class Time { private int seconds; private int minutes; private int hours;

Page

34

public Time() { seconds = 0; minutes = 0; hours = 0; } public void displayTime() { System.out.println(The time is: + hours + : + minutes + : + seconds); } } 7b. Include the class written for Exercise 7a within the context of a complete program. public class UseTime { public static void main(String[] args) { Time myTime = new Time(); myTime.displayTime(); } } Exercises 2.4 1. Determine and correct the errors in the following main() methods. public static void main(String[] args) { width = 15

Page

35

area = length * width; System.out.println(The area is + area);

Solution: A semicolon is missing from the width initialization statement. The variables width, length, and area were not declared. The variable length was not initialized.

public static void main(String[] args) { int length, width, area; area = length*width; length = 20; width = 15; System.out.println(The area is + area); Solution The variables length and width are initialized AFTER they are used. The closing brace used to signal the end of the method is missing. public static void main(String[] args) { int length = 20; width = 15, area; length*width = area; System.out.println(The area is , area; }

Page

36

Solution The variables width and area are not declared and initialized correctly The two sides of the equals operator need to be swapped. The string parameter of the println() method is not concatenated correctly. The comma should be replaced with a plus sign. The println() method is missing its closing parenthesis. 3a. Write a QuickTest program to calculate the circumference of a circle. The equation for determining the circumference of a circle is circumference = 2 * 3.1416 * radius. Assume that the circle has a radius of 3.3 inches. public class QuickTest { public static void main(String[] args) { float radius = 3.3F; System.out.println(The circumference of a circle with radius + 3.3 inches is + (2.0F * 3.1416F * radius) + inches.); } } 3b. Run the program written for Exercise 3a on a computer. Students should run the above program.

Page

37

5a. Write a QuickTest program to calculate the volume of a swimming pool. The equation for determining the volume is volume = length * width * depth. Assume that the pool has length of 25 feet, a width of 10 feet, and a depth of 6 feet. public class QuickTest { public static void main(String[] args) { int width = 10; int length = 25; int depth = 6; System.out.println(The Volume of a swimming pool with width + 10 feet, length 25 feet, and depth 6 feet + is + (width*length*depth) + cubic feet.); } } 5b. Run the program written for Exercise 5a on a computer. Students should run the above program. 7a. Write a QuickTest program to calculate the dollar amount in a piggy bank. The bank currently contains 12 half dollars, 20 quarters, 32 dimes, 45 nickels, and 27 pennies. public class QuickTest {

Page

38

public static void main(String[] args) { int numHalfDollars = 12; int numQuarters = 20; int numDimes = 32; int numNickels = 45; int numPennies = 27; float total; total total total total total = += += += += numHalfDollars numQuarters numDimes numNickels numPennies * * * * * 0.50F; 0.25F; 0.10F; 0.05F; 0.01F;

System.out.println( The total amount of money in the piggy bank is + total); } } 7b. Run the program written for Exercise 7a on a computer. Students should execute the above program. 9a. Write a QuickTest program to calculate the elapsed time it took to make a 183.67 mile trip. The equation for computing elapsed time is elapsed time = total distance / average speed . Assume that the average speed during the trip was 58 miles per hour. public class QuickTest { public static void main(String[] args) { float tripDistance = 183.67F;

Page

39

float avgSpeed = 58.0F; float timeElapsed; timeElapsed = tripDistance / avgSpeed; System.out.println(Total time for the trip is + timeElapsed + hours.); } } 9b. Run the program written for Exercise 9a on a computer. Students should execute the above program. 11. By mistake, a programmer reordered the statements in QuickTest Program 2-9 as follows: public class SubTotals { public static void main(String[] args) { int sum; sum = 0; sum = sum + 96; sum = sum + 70; sum = sum + 85; sum = sum + 60; System.out.println(The value of initially set to + sum); System.out.println( sum is now + System.out.println( sum is now + System.out.println( sum is now + System.out.println( The final sum sum);

sum is sum); sum); sum); is +

Page

40

} } Determine the output of this program. Solution: The value of sum is initially set to 311 sum is now 311 sum is now 311 sum is now 311 The final sum is 311

Exercises 2.5 1. Define the following terms. a. An attribute is a property of interest. b. An objects behavior is a description of how it reacts with its environment. c. A class is the category of objects defined by a given set of attributes and behaviors. d. An identity is a name by which an object can be uniquely identified within a program. e. A model is a representation of a problem. f. An object is derived from the general class and comes into existence with specific values assigned to its attributes. It is a specific item that is modeled generically by a class.

Page

41

g. An object-diagram is a diagram that specifies the attributes and behavior of a particular object. It is useful for creating a general class that can be used to represent that object. h. An objects state is the particular way (determined by specific values and attributes) that the object exists. i. Values are assigned to the attributes of an object. 3. Classify each of the following as either classes or objects. a. b. c. d. e. f. g. h. i. Maple Trees is a class. Ford Automobiles is a class. My collie dog is an object. The oak tree in my yard is an object. Boeing 767 planes is a class. Your Ford Taurus is an object. Kitchen tables is a class. Student desks is a class. The chair you are sitting on is an object.

5. For each of the following, what behavior might be of interest to someone considering buying the item? a. Car You might want to know if the windows are power windows, if it can operate in cruise control, can use four-wheel drive or antilock brakes, etc. b. Cassette Player For a cassette player, you might want to know if it can record tapes, play in stereo, fast forward through songs, etc. 7a. List as many attributes and behaviors that would be of interest in a program that simulates dealing a hand of playing cards. For this, assume any card game that you are familiar with.

Page

42

Card Game: Solitaire To deal a hand of solitaire, one only needs to know where to put the cards. No other information is necessary. Class SolitaireHand Attributes: The number of cards in the draw pile The number of card stacks in the playing area The number of cards to be places in each stack in the playing area Behaviors: Deal the cards 7b. What attributes of the cards would not be of interest for the purpose of the simulation? For dealing a hand of solitaire, one does not need to know any particular information about the cards. The program only needs to know where to put each card. The values of the cards The color of the cards Which cards are face cards Etc.

9. The class examples considered in this section have consisted of inanimate objects. Do you think that animate objects such as pets and even human beings could be modeled in terms of attributes and behavior? Why or why not?

Page

43

There should be no reason as to why one could not model an animate object using a Java class. The complexity of the model will however be determined by the purpose of the program needing the model. For example, if one wished to keep a record of prisoners at a jail, then he or she could create a class called Prisoner with the following attributes: height weight eye color hair color age build crime committed etc.

11. Consider the problem of adding two numbers. a. From a procedural-orientation, the mathematical operation for which to concentrate would be addition. b. From an object-orientation, one would need a class representing a generic number of the type one is interested in with clearly defined behavior allowing the addition of two objects derived from that class.

Page

44

III. Sample Test Questions Chapter 2 1) A literal value is a value that a) does not need to be included in a compiled program b) explicitly identifies itself c) is always a number d) is never a number Answer: (B) 2) An atomic data type is a) not decomposable into a smaller data type supported by the language b) defined as the smallest data type, in bytes, supported by the language c) a data type from which other atomic data types can be derived d) can be split into smaller, subatomic, data types Answer: (A) 3) What is the output of the following line of code? System.out.println(Answer is + 3 / 2 + 4); a) Answer is 5 b) Answer is 5.5 c) Answer is 1.54 d) Answer is 14 Answer: (D)

Page

45

4) If the line of code shown below was found in a Java source program, what would be the value stored in result and what would its data type be? result = 4. / 8 + 3 % 2.5; a) 1.0, single precision number b) 1.0, double precision number c) 1.5, single precision number d) 1.5, integer number Answer: (B) 5) All variables must have a) an expression and a specification b) syntax and logic c) a data type and a name d) memory location and status flag Answer: (C) 6) Expressions containing operators with the same precedence are evaluated according to their a) associativity b) hierarchy c) relative precedence d) locally defined precedence Answer: (A)

Page

46

7) Memory leak problems a) were not problems before Java was developed b) represent a potential source of program error and must be carefully considered by the Java programmer c) are not a concern to the Java programmer d) occur when a program allows its stored data to leak into and corrupt data within other running applications Answer: (C) 8) Which of the following is an invalid Java identifier? a) __a123 b) $$__5 c) %_23a d) _123_$_56$66 Answer: (C) 9) A constructor method a) is only needed when a class requires user input b) specifies a return value of void c) must always be explicitly supplied by the programmer d) is used to initialize instance variables when the object is created Answer: (D)

Page

47

10) The following constructors are defined for a class named Image. Which of the following is its default constructor? a) void Image(); b) Image(int height, int width); c) image(); d) Image(); Answer: (D) 11) Each Unicode character requires a) 1 byte b) 2 bytes c) 3 bytes d) 4 bytes Answer: (B) 12) What is the value of the following integer expression: (20 + 2) / (6 + 2)? a) 2.75 b) 22/8 c) 3 d) 2 Answer: (D) 13) Which of the following lines of Java code is allowable and illustrates coercion?

Page

48

a) int result = 3 * 4 % 7; b) float result = (5 2) / 3.0F + 9; c) float result = (5 3) * 3 12; d) int result = (3.0 * 5) / 4 * 36; Answer: (C)

14) Which of the following is not an atomic data type in Java? a) float b) char c) int d) String Answer: (D)

15) The first operation performed by Java in the expression 8 + 5 * 7 % 2 / 4 is a) + b) * c) % d) / Answer: (B) 16) A class accessor method typically allows

Page

49

a) a programmer to access the value of a class attribute b) the class to access private data in another class c) the class to access data declared within its main method d) a programmer to modify the value of a class attribute Answer: (A) 17) Which of the following assignment statements is legal? a) float result = 3.1; b) float result = 3D; c) float result = 3; d) int result = 2.4; Answer: (C) 18) In Java: a) coercion is never allowed b) coercion is performed when storing a value of some range into a variable type of greater range c) coercion is allowed when storing a value of some range into a variable type of lesser range d) is always allowed Answer: (B) 19) Java will report an error occurring at which line? [1] public static void main(String[] args) [2] {

Page

50

[3] int width = 4; [4] System.out.println(The width is + width); [5] int length = 4; [6] int totalLength; [7] System.out.println(The length is + length); [8] totalLength = totalLength + width + length; [9] } a) three b) four c) six d) eight Answer: (D) 20) Java will report an error occurring at which line? [1] public static void main(String[] args) [2] { [3] float radius = 3; [4] float PI = 3.14; [5] [6] double area = PI * radius * radius; [7] System.out.println(The area of the circle is + area); [8] } a) 3 b) 4

Page

51

c) 6 d) 7 Answer: (B)

Page

52

I. OVERVIEW: Chapter 3 Developing Class Methods To be useful, objects must be capable of interacting with other objects. Specifically, one object may desire another object to perform some task in its behalf. In theoretical terms this is referred to as one object sending a message to a second object. In response, the second object either sends the message on to another object or directly uses a method to complete the request of the first object. Ultimately, however, it is a method that completes any task or state change performed on an object. In this chapter we will see how methods are constructed to accept information through its parameter list and directly return a value that can then be passed to other methods for further processing or display. 3.1 Method and Parameter Declarations 3.2 Returning a Single Value Pass by Reference Returning Multiple Values 3.3 Method Development: Algorithms 3.4 Application: Swapping Values 3.5 static and final Variables static Methods Scope final Variables 3.6 Common Programming Errors 3.7 Chapter Summary 3.8 Chapter Supplement: Insides and Outsides

Potential Problem areas:

Page

53

The difference between arguments and parameters. The various mechanisms for passing parameters. Plan to spend time designing and implementing algorithms. Start to encourage correct style when coding programs.

Page

54

II. ANSWERS TO ODD-NUMBERED EXERCISES

Exercises 3.1 For the following method headers, determine the number, type, and order (sequence) of the values that must be passed to the method. a. public void factorial(int n) One integer value must be passed to the method. b. public void price(int type, double yield, double maturity) Three parameters of types integer and double should be passed to the method in the specified order of a single integer followed by two doubles. c. public void yield(int type, double price, double maturity) Three parameters of types integer and double should be passed to the method in the specified order of a single integer followed by two doubles. d. public void interest(char flag, double price, double time) Three parameters of types character and double should be passed to the method in the specified order of a single character followed by two doubles. e. public void total(double amount, double rate) Two values of type double should be passed to the method. f. public void roi(int a, int b, char c, char d, double e, double f) Six values consisting of types integer, character, and double should be passed to the method in the specified order of two integers, two characters, and two doubles.

Page

55

g. public void getVal(int item, int iter, char decflag, char delim) Four values consisting of types integer and character should be passed to the method in the specified order of two integers followed by two characters. 3. Add two mutator methods names setLength() and setWidth to Program 3-2s RoomType class that can be used to individually set an objects length and width, respectively. public void setLength(double len) { length = len; } public void setWidth(double wid) { width = wid; }

5. Modify Program 3-2 to include two constructors. The first constructor should be a default constructor that initializes an objects length and width variables to 12.0 and 9.9 respectively, while the second constructor should use two parameters, named initLength, and initWidth that can be used to initialize an objects instance variables when the object is created. public RoomTypeOne() { length = 12.0; width = 9.9; } public RoomTypeOne(double initWidth) { initLength, double

Page

56

length = initLength; width = initWidth;

7. Determine errors in the following class: public class Employee { public int empnum; public char code; private void showemp(int, char) { . . }

The method header for the showemp() method is missing parameter identifiers. Only the data types are declared. 9. The following program provides the same functionality as Program 3-2 but places each method in its own class. Enter and store each class in a separate file and then compile each class. Execute UseRoomTypeOne to verify that it produces the same result as Program 3-2. Students should enter, compile, and execute the code in this program and compare its results with those obtained in Program 3-2. 11a. Construct a Time class containing integer instance variables named seconds, minutes, and hours. Have the class contain two constructors The first should be a default constructor that initializes each data member with a default value of 0 and the second

Page

57

constructor should accept three integer arguments that will be used to set each instance variable. The class should also include a mutator method that accepts three integer arguments for setting the instance variables, and an accessor method for displaying the time. public class Time { private int seconds; private int minutes; private int hours; public Time() { seconds = minutes = hours = 0; } public Time(int initSeconds, int initMinutes, int initHours) { seconds = initSeconds; minutes = initMinutes; hours = initHours; } public void changeTime(int secs, int mins, int hrs) { seconds = secs; minutes = mins; hours = hrs; } public void displayTime() { System.out.println(The time is:);

Page

58

System.out.println( + hours + hours);

System.out.println( + minutes + minutes); System.out.println( + seconds + seconds); } } 11b. Include the class written for Exercise 11a within the context of a complete program. public class UseTime { public static void main(String[] args) { Time myTime0 = new Time(); Time myTime1 = new Time(10,30,13); Time myTime2 = new Time(); myTime2.changeTime(11,30,45); myTime0.displayTime(); myTime1.displayTime(); myTime2.displayTime();

} }

Exercises 3.2 1. For the following method headers, determine the number, type, and order (sequence) of values that should be passed to the method when it is called and the data type of the value returned by the method.

Page

59

a. public double getLength() This method takes zero parameters and returns a double value. b. public int getNumber() This method takes zero parameters and returns an integer value; c. public void showPrice() This method takes zero parameters and returns nothing. d. public double calculatePrice() This method takes zero parameters and returns a double value. e. public double calculatePrice(int type) This method takes one integer parameter and returns a double value. f. public char interest(char flag, double price, double maturity) Three parameters should be passed to this method in the specified order of character followed by two double values. The method returns a character value. g. public int total(double amount, double rate) Two double parameters should be passed to this method. The method returns an integer value. h. public double roi(int a, int b, char c, char d, double e, double f) Six parameters should be passed to this method in the order of two integers followed by two characters followed by two doubles. The method returns a double value. i. public void getVal(int item, int iter, char decflag) Three parameters should be passed to this method in the order of two integers followed by a character value. The method does not return a value.

Page

60

3. Modify calculateArea() method in Program 3-4 so that its header line declares a return of an integer value. Determine the error message generated by the compiler because a double-precision value is provided in the return statement. public int calculateError() The compiler will provide an error message indicating an incompatible type for return and that an explicit cast is required for proper compilation. 5a. Write a Java class named Fahrenheit that contains a single double-precision instance variable name temperature. The class should include a constructor and mutator method that permits a programmer to set an objects temperature value to a programmer selected value. Additionally, there should be an accessor method that returns an objects temperature value and a class method named celsisusValue() that returns the Celsius temperature corresponding to a Fahrenheits temperature. The Celsius value can be determined using the formula: Celsius = 5.0 / 9.0 *(Fahrenheit 32.0). public class Fahrenheit { private double temperature; public Fahrenheit(double initTemp) { temperature = initTemp; } public void changeTemperature(double newTemp) { temperature = newTemp;

Page

61

} public double getTemperature() { return temperature; } public double celciusValue() { return ( (5.0 / 9.0) * (temperature 32.0) ); } } 5b. Include the method written for Exercise 5a in a working Java program. Make sure that all class methods are called from main(). Have main() display the value returned by celsiusValue() and verify the returned value by a hand calculation. public class UseFahrenheit { public static void main(String[] args) { Fahrenheit Fahrenheit(98.6); temperature0 = new the

System.out.println(Temperature0 holds value: + temperature0.getTemperature() + degrees Fahrenheit.); temperature0.changeTemperature(212.0);

Page

62

System.out.println(Temperature0 now holds the value: + temperature0.getTemperature() + degrees Fahrenheit.); System.out.println(temperature0.getTemperature() + degrees Fahrenheit is equivalent to + + temperature0.celciusValue() + degrees Celsius.); } } 7a. Write a Java class named PolyTwo that contains three doubleprecision instance variables named a, b, and c which represent the coefficients of a second-degree polynomial (a second-degree polynomial in x is given by the expression ax 2 + bx + c, where a, b, and c are referred to as coefficients. If the coefficient, a, is zero, the expression becomes a first-degree polynomial). The class should include a constructor and mutator method that permits a programmer to set an objects variables to programmer selected values. Additionally, there should be a single accessor method that displays an objects values and a class method named polyValue() that accepts a double precision value as the parameter named x, and returns the value determined by the expression ax2 + bx + c, where a, b, and c are coefficients contained in a PolyTwo object. public class PolyTwo { private double a; private double b; private double c;

Page

63

public PolyTwo(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public void setCoefficients(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public void displayPolynomial() { System.out.println(a + x^2 + + b + x + + c); } public double polyValue(double x) { return a*x*x + b*x + c; } } 7b. Include the method written for Exercise 7a in a working Java program. Make sure that all class methods are called from main(). Have main() display the value returned by polyValue() for various values of x that are passed into the method when it is called. Verify the returned value be performing a hand calculation. public class UsePolyTwo { public static void main(String[] args)

Page

64

{ PolyTwo myPolynomial = new PolyTwo(1,2,3); is: ); myPolynomial.displayPolynomial(); System.out.println(); System.out.print(The initial polynomial

myPolynomial.setCoefficients(4,5,6); System.out.print(The new polynomial is: ); myPolynomial.displayPolynomial(); System.out.println(); polynomial

System.out.println(The evaluated at x = 5.1 is: + polyValue(5.1)); System.out.println(The evaluated at x = -1.5 is: + polyValue(-1.5)); } }

polynomial

9a. Write a Java class named Triangle that contains three instance variables named sideOne, sideTwo, and angle. The class should include a constructor and mutator method that permits a programmer to set an objects variables to programmer selected values. Additionally, there should be an accessor method that displays an objects values and a class method named hypotenuse() that returns the hypotenuse of a triangle object. (Hint: use the Pythagorean theorem c^2 = a^2 + b^2, where c is the hypotenuse

Page

65

and a and b are the other two sides of the triangle. To do this you will have to use the Java provided methods named Math.sqrt(). For example the value of Math.sqrt(25.0) is 5.0). public class Triangle { private double sideOne; private double sideTwo; private double angle; public Triangle(double sideTwo, double angle) { this.sideOne = sideOne; this.sideTwo = sideTwo; this.angle = angle; } sideOne, double

public void setAttributes(double double sideTwo, double angle) { this.sideOne = sideOne; this.sideTwo = sideTwo; this.angle = angle; }

sideOne,

public void displayAttributes() { System.out.println(Side 1: + sideOne); System.out.println(Side 2: + sideTwo); System.out.println(Angle : + angle); } public double hypotenuse() {

Page

66

if (angle != 90) return Math.sqrt(sideOne*sideOne + sideTwo*sideTwo); else return -1.0; } } 9b. Include the class written for Exercise 9a in a working Java program. Make sure that all class methods are called from main(). Have main() display the value returned by hypotenuse() and verify the returned value is correct. public class useTriangle { public static void main(String[] args) { Triangle myTriangle = Triangle(5,5,90);

new

System.out.println(Initial triangle has the following properties:); myTriangle.displayAttributes(); myTriangle.setAttributes(10,10,45); System.out.println(New triangle has the following properties:); myTriangle.displayAttributes(); System.out.println(The hypotenuse of this triangle is: + hypotenuse()); }

Page

67

} Exercises 3.3 1a. Determine the six possible step-by-step procedures (list the steps) to paint the flower shown in Figure 3-14, with the restriction that each color must be completed before a new color can be started. (Hint: One of the algorithms is; Use yellow first, green second, black last.) use yellow then green then black use yellow then black then green use green then yellow then black use green then black then yellow use black then yellow then green use black then green then yellow

1b. Which of the six painting algorithms (series of steps) is best if we are limited to using one paintbrush and there is no way to clean the brush. Since we cannot clean the brush, it would be best to paint in the order that would allow for the minimization of color corruption through paint mixing. Here, we will assume that darker colors cover more easily lighter colors. Therefore, the ideal algorithm would be to paint with yellow first, then green, and then finally black. 3. Determine and write an algorithm (list the steps) to interchange the contents of two cups of liquid. Assume that a third cup is available to hold the contents of either cup temporarily. Each cup should be rinsed before any new liquid is poured into it. Pour contents of cup 1 into cup 3

Page

68

Rinse out cup 1 Pour the contents of cup 2 into cup 1 Rinse out cup 2 Pour the contents of cup 3 into cup 2

5. Write a set of detailed, step-by-step instructions, in English, to find the smallest number in a group of three integer numbers. Choose the smaller of the first two numbers choose the smaller of the number found in the previous step and the third number 7a. Write a set of detailed, step-by-step instructions, in English, to calculate the fewest number of dollar bills needed to pay a bill of amount Total. For example, if Total were $98, the bills would consist of one $50 bill, two $20 bills, one $5 bill, and three $1 bills. For this exercise, assume that only $100, $50, $20, $10, $5, and $1 bills are available. Find largest bill that is less than or equal to Total and use that bill subtract the value of the bill from Total Repeat the previous two steps until total is less than $1 If total is zero, then stop If total is between zero and one, then use one more dollar bill

7b. Repeat Exercise 7a, but assume the bill is paid only in $1.00 bills. Add 50 cents to the total and truncate any fractional part of a dollar The integer in the previous step is the minimum number of $1 bills needed to pay the bill.

Page

69

9. Determine and write an algorithm to sort three numbers in ascending order (from lowest to highest) order. How would you solve this problem intuitively? Find the smallest number in the list of numbers and use that number as the first number in the new sorted list. Find the smaller of the two remaining numbers and use that number as the second number in the new sorted list. The third number in the sorted list will be the number remaining in the unsorted list. Intuitively, one would just sort the list without thinking about all of steps required. Exercises 3.4 1. Compile and execute Program 3-7. To execute Program 3-7 you will also have to compile either Program 3-5 or 3-6. Students should compile and execute the specified program. 3. Modify Program 3-8 so that it declares only one String instance variable named name. Then, rewrite the swap() method so that it accepts an EncapulateNames as a parameter and swaps the value referenced by the parameter with the value referenced by the object used when the method is called. For example, the method call AName.swap(BName) should switch the values contained in the objects AName and BName. The method header should be public void swap(EncapsulatesNames secName). public class EncapsulateNames { private String name;

Page

70

s1;} public String getName() {return name;} public void setName(String s1){name = s1;} public void swap(EncapsulateNames secName) { String temp = secName.getName(); secName.setName(this.name); this.name = temp; }

public EncapsulateNames(String s1) {name =

5a. Using the EncapsulateNames class as a model, construct a class named XYValues that can be used to swap the values stored in two double-precision instance variables. public class XYValues { private double XValue; private double YValue; public XYValues(double x, double y) { XValue = x; YValue = y; } public double getXValue() {return XValue;} public double getYValue() {return YValue;} public void setValues(double x, double y) {

Page

71

XValue = x; YValue = y;

public void swap() { double temp = XValue; XValue = YValue; YValue = temp; }

5b. Test the class constructed in Exercise 5a using a class named TestXYValues. public class TestXYValues { public static void main(String[] args) { XYValues test = new XYValues(5.0,10.0); System.out.println(X test.getXValue()); System.out.println(Y test.getYValue()); test.setValues(15.0,20.0); System.out.println(X test.getXValue()); System.out.println(Y test.getYValue()); test.swap(); value value is: is: + + value value is: is: + +

Page

72

System.out.println(X test.getXValue()); System.out.println(Y test.getYValue()); } } Exercises 3.5 1. Enter and execute Program 3-12.

value value

is: is:

+ +

Students should enter and execute the specified program. 3. Will the following program produce the same result as QuickTest Program 3-13? public class AverageNumbers { public static void main(String[] args) { double numOne = 12.5; double numTwo = 17.2; System.out.println(The average of + numOne + and + numTwo + is + average(numOne,numTwo)); } public static double average(double numOne, double numTwo) { return (numOne + numTwo) / 2.0;

Page

73

} } Yes, the two programs will produce the same results. 5a. For the following section of code, determine the data type and scope of all declared variables. To do this, list the three column headings that follow on a sheet of paper (we have filled in the entries for the first variable): Identifier price years yield bondtype interest coupon args mat1 mat2 count effectiveRate first last numofyrs fracPart Data Type integer long integer double integer double double String Array integer integer integer double double double integer double Scope class scope class scope class scope local scope local scope local scope local scope local scope local scope local scope local scope local scope local scope local scope local scope

5. Draw boxes around the appropriate section of the foregoing code to enclose the scope of each variable

Page

74

A box should be drawn around each of the methods. Also, a larger box, enclosing the smaller method boxes, should be drawn representing class scope. 5c. Determine the data type of the arguments that the methods roi() and step() expect and the data type of the value returned by these methods. The method roi() expects two integer parameters and returns a double value. The step() method expects two double parameters and returns an integer value. 7. Besides speaking about the scope of a variable, we can also apply the term to a methods parameters. What is the scope of all method parameters? All method parameters have local scope.

Page

75

III. Sample Test Questions Chapter 3 1) External data is always passed to a method in the form of comma separated a) literal values b) methods c) arguments d) return values Answer: (C) 2) Which of the following method headers takes parameters in the order: two floating point values followed by a character value? a) private int getValues(char here, float there, char everywhere); b) public void getValues(char here, char there, char everywhere); c) pubic double getValues(double here, double there, char everywhere); d) public static void getValues(float here, float there, char everywhere); Answer: (D) 3) The act of invoking a method is termed a) calling the method b) executing the method c) parsing the method d) passing the method

Page

76

Answer: (A) 4) A method consists of the following two parts: a) header and footer b) footer and body c) header and body d) header and secondary statements Answer: (C)

5) When a method is called, the arguments passed must match the parameters in the methods header line with respect to which of the following properties? a) order of appearance b) number of parameters c) data types of the parameters d) all of the above Answer: (D) 6) A valid overloaded method is created when a) a method has the same parameter list as that of another method b) a method has the same name and parameter list as that of another method c) a method has the same name, but different parameter list, as that of another method

Page

77

d) none of the above Answer: (C) 7) Returning multiple values from a method in Java a) is strictly prohibited b) is achieved by specifying multiple return types c) can be achieved by a method returning a concatenated string value d) requires that the keyword ReturnMultiple be placed in a methods header line Answer: (C) 8) An algorithm a) is an intuitive solution to a problem b) is a step-by-step solution to a problem c) is developed by the Java compiler d) is similar to a logarithm Answer: (B) 9) A static variable a) is created only once for each class b) can never be changed c) is created once for every object derived from a class d) can only be changed from within the class that contains it Answer: (A)

Page

78

10) Variables with local scope a) are declared in the data declaration section of a class b) cannot be changed c) are declared within a method d) cannot be used in arithmetic operations with variables of class scope Answer: (C) 11) Which of the following statements is false? a) If an instance variable is private, outside access must be made through a public member method; otherwise, if it is public it can be accessed directly using an object's name. b) A static variable declared as private can only be accessed outside of its class as a member of an object or using a public and static class method. c) A static variable declared as public can be accessed outside of its class by prefixing the variable's name with its class name and a period. d) If an instance or static variable has the same name as a method variable, the instance or static variable effectively becomes hidden within the method, and any use of the variable's name will refer to the class variable. Answer: (D) 12) Which of the following statements is false?

Page

79

a) A class method declared as public can be accessed outside of its class. In general, such methods present the services that the class provides to the outside world. b) A class method declared as public and static is a generalpurpose method that can perform a task not related to any specific object created from the class. c) A class method declared as private can only be accessed by other methods in the same class that contains the private method. d) None of the above is false Answer: (D) 13) Which of the following header lines denotes a method that is not a constructor and returns no value? a) public static int main(String[] args) b) public String getTime() c) public void set() d) public Set() Answer: (C) 14) Which of the following header lines denotes a constructor method? a) public void Constructor() b) private void Constructor() c) int Constructor(); d) public Constructor();

Page

80

Answer: (D) 15) Which of the following method headers defines a method that could be used to return multiple items such as a name and a telephone number? e) public void getValues() f) public getValues() g) public int getValues() h) public String getValues() Answer: (D)

Page

81

I. OVERVIEW: Chapter 4 Input and Formatting Class Methods This chapter presents class methods for entering data interactively while a program is executing. Additionally, the use of class methods for creating formatting output is presented. A set of useful mathematical methods from Java's Math class is also provided. To both illustrate and isolate the class methods being introduced, we will make frequent use of QuickTest programs. Finally, to stress the importance of using existing classes, which include those provided by Java and those created by yourself as you increase your programming proficiency, the construction of a personal class library is provided. 4.1 Interactive KeyBoard Input The StringTokenizer Class A First Look at User-Input Validation 4.2 Interactive Dialog Input Exception Handling 4.3 Program Design and Development: Creating a Class Library 4.4 Formatted Output 4.5 Mathematical Methods Casts Conversion Methods 4.6 Common Programming Errors 4.7 Chapter Review 4.8 Chapter Supplement: Programming Errors

Potential Problem areas: Keyboard input has various idiosyncracies that can be confusing. Be sure to stress the importance of user input validation. Exception handling can be confusing. Students will probably enjoy learning about

Page

82

GUI input. Outpout formatting can be skimmed or postponed. The array of conversion methods may seem confusing.

Page

83

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 4.1 1. Write two statements that could be used after each of the following prompts to perform the following tasks. The first statement should read a string value from the keyboard, assuming that the string is to be accessed by the string variable named inputString. The second statement should convert inputString into a variable of the correct primitive data type. Assume that an integer value is required for a, a long value for b, a floating-point value for c, and a double-precision number for d. System.out.println(Enter a grade: ); inputString = br.readLine(); number = Integer.parseInt(inputString); System.out.println(Enter an identification number: ); inputString = br.readLine(); number = Long.parseLong(inputString); System.out.println(Enter a price: ); inputString = br.readLine(); number = Float.parseFloat(inputString); System.out.println(Enter an interest rate: ); inputString = br.readLine(); number = Double.parseDouble(inputString); 3. Enter and execute QuickTest program 4-1 but leave out the line containing the expression throws java.io.IOException after the

Page

84

main() header line. Record the error message provided by the compiler. Students should enter and compile the program as specified. 5a. Write a QuickTest program that displays the following prompt: Enter the temperature in degrees Celsius: Have your program accept a value entered from the keyboard and convert the temperature entered to degrees Fahrenheit, using the formula: Fahrenheit = (9.0 / 5.0) * Celsius + 32.0. Your program should then display the temperature in degrees Celsius, with an appropriate output message. import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { String temperatureString; double temperature; BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.print(Enter the temperature in degrees Celsius: ); temperatureString = br.readLine(); temperature = Double.parseDouble(temperatureString);

Page

85

System.out.println(Temperature in degrees Celsius: + temperature); System.out.println(); System.out.println(Temperature in degrees Fahrenheit: + ((9.0 / 5.0) * temperature + 32)); } } 5b. Compile and execute the program written for Exercise 5a. Verify your program by hand calculation and then use your program to determine the Fahrenheit equivalent of the following test data: The student should compile and execute the specified program. 0 degrees Celsius is 32 degrees Fahrenheit. 50 degrees Celsius is 122 degrees Fahrenheit. 100 degrees Celsius is 212 degrees Fahrenheit. 7a. Write, compile, and execute a QuickTest program that displays the following prompts: Enter the miles driven: Enter the gallons of gas used: After each prompt is displayed, your program should use a readLine() method to accept data from the keyboard for the displayed prompt. After the gallons of gas used number has been entered, your program should calculate and display miles per gallon obtained. This value should be included in an appropriate message

Page

86

and calculated using the equation miles per gallon = miles / gallons used. Verify your program with the following test data: Test data set 1: miles = 276, gas = 10 gallons Test data set 2: miles = 200, gas = 15.5 gallons import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { String userEntry; double miles; double gallons; double mpg; BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); ); System.out.print(Enter the miles driven: userEntry = br.readLine(); miles = Double.parseDouble(userEntry); System.out.print(Enter the gallons of gas used: ); userEntry = br.readLine(); gallons = Double.parseDouble(userEntry); mpg = miles / gallons; System.out.println(Miles per gallon is: + mpg); } }

Page

87

Miles Driven 276 250 275 312 296

Gallons Used 10 16 18 19.54 17.39

MPG 27.6 15.625 15.28 15.97 17.02

7b. For the program written in Exercise 7a, determine how many verification runs are required to ensure that the program is working correctly and give a reason supporting your answer. Because the equation being implemented is extremely simple (it involves only a single division operation), verification with only a couple of examples should be more than sufficient to ensure that the program is working correctly. 9a. Write a QuickTest program that displays the following prompts: Enter a number: Enter a second number: Enter a third number: Enter a fourth number: After each prompt is displayed, your program should use a readLine() method to accept a number from the keyboard for the displayed prompt. After the fourth number has been entered, your program should calculate and display the average of the numbers. The average should be included in an appropriate message. import java.io.*; public class QuickTest {

Page

88

public static void main(String[] args) throws java.io.IOException { double firstNumber; double secondNumber; double thirdNumber; double fourthNumber; double avg; BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.print(Enter a number: ); firstNumber Double.parseDouble(br.readLine()); ); =

System.out.print(Enter a second number: secondNumber Double.parseDouble(br.readLine()); ); =

System.out.print(Enter a third number: =

thirdNumber Double.parseDouble(br.readLine()); );

System.out.print(Enter a fourth number: fourthNumber Double.parseDouble(br.readLine()); avg = (firstNumber + thirdNumber + fourthNumber)/4.0; secondNumber = +

Page

89

System.out.print(The average of the four input values is: ); System.out.println( + avg); } } 9b. Check the average displayed for the program written in Exercise 9a by calculating the result manually. Students should calculate the result manually and compare to the output of his or her program. 9c. Repeat Exercise 9a, making sure that you use the same variable name, number, for each number input. Also use the variable sum for the sum of the numbers. (Hint: To do this, you must use the statement sum = sum + number; after each number is accepted. Review the material on accumulating presented in Section 4.1. import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { double number; double sum = 0; BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.print(Enter a number: ); number Double.parseDouble(br.readLine()); sum += number; =

Page

90

System.out.print(Enter a second number: ); Double.parseDouble(br.readLine()); sum += number; System.out.print(Enter a third number: ); Double.parseDouble(br.readLine()); sum += number; System.out.print(Enter a fourth number: ); Double.parseDouble(br.readLine()); sum += number; System.out.print(The average of the four input values is: ); System.out.println( + (avg / 4.0) ); } } 11. Repeat Exercise 12 but have your program convert the entered string to a floating-point value and store the converted value into a floating-point variable. Run the program four times. The first time enter an integer, the second time enter a decimal number, the third time enter a decimal number with an f as the last character entered, and the fourth time enter a character. Using the output display, keep track of what number your program actually accepted from the data you entered. What happened, if anything, and why? import java.io.*; public class QuickTest number = number = number =

Page

91

{ public static void main(String[] args) throws java.io.IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String userEntry; float number; System.out.print(Enter a number: ); userEntry = br.readLine(); number = Float.parseFloat(userEntry); System.out.println(The number entered was: + number); } } For the first three trials, the java program accepts the entry and converts the number to a floating point number. In the last case, the program will crash and display a number format exception error. 13a. Why do you think that successful application programs contain extensive data input validity checks? Any successful program must be able to take into consideration every type of user error imaginable. Otherwise, the result of not checking may be either a software crash or an error in the result the software was supposed to provide. Either case is unacceptable in practical purposes. Software crashes are annoying and could potentially cause extreme hazards. For example, suppose a a space shuttle navigation computer crashed or gave wrong data because the user accidentally entered in a badly formatted input. Therefore, any software that is well written will have input validity checks.

Page

92

13b. What do you think the difference between a data type check and a data reasonableness check? A data type check would be a check to see whether or not the type of data entered matches the type of data expected. A data reasonableness check is a check of whether or not the entered data is reasonable in the context of the application. For example, if the software asked the user to input his or her height, the user should enter a positive floating-point number. If the user entered a negative floating-point number, then, in this case, the user entered an unreasonable value even though the data type is correct. 13c. Assume that a program requests that a month, day, and year be entered by the user. What are some checks that could be made on the data entered? Assuming that the software wishes that three integers be specified in order to indicate the month, day, and year: Check to see if values entered are valid integers Check to see if the month is between 1 and 12 inclusive Check to see if the day is an acceptable value depending on the month entered (i.e. April 31st is invalid) Check to see if the month and day are possible depending on the year (i.e. leap year) 15. Enter and execute QuickTest program 4-2 on your computer, but make both of the following changes: i. omit the line after the main() header line that contains the expression throws java.io.IOException

Page

93

ii.

change the statement inputString = br.readLine(); to inputString = 98.5 12;

Compile and execute the program to determine what error message is provided. Discuss what occurred and why. The program will not compile. The compiler will argue that IOException must be caught or declared to be thrown. Exercises 4.2 1. Write assignment statements that store the returned value from an input dialog box in a variable named test for the following input prompts: a. prompt: Enter a grade: test = JOptionPane.showInputDialog(Enter grade:); b. prompt: Enter a temperature: test = JOptionPane.showInputDialog(Enter temperature:); c. prompt: Enter an interest rate: test = JOptionPane.showInputDialog(Enter interest rate:); d. prompt: Enter a name: test = JOptionPane.showInputDialog(Enter name:); e. prompt: Enter a price: test = JOptionPane.showInputDialog(Enter price:); a

an

Page

94

3a. Write a QuickTest program that displays the following prompt in an input dialog box: Enter the amount of the bill: After accepting a value for the amount of the bill, your program should calculate the sales tax, assuming a tax rate of 6 percent, and display the sales tax as a dollar amount in a message dialog. For testing purposes, verify your program using an initial amount of $36.00. After manually checking that the result produced by your program is correct, use your program to complete the following table: import javax.swing.*; public class QuickTest { public static void main(String[] args) { String userEntry; String message; double billAmt; userEntry = JOptionPane.showInputDialog("Enter the amount of the bill:"); billAmt = Double.parseDouble(userEntry); message = "Initial Amount: $" + billAmt + "\n"; message += "Sales Tax: $" + billAmt*0.06; JOptionPane.showMessageDialog(null,message," Sales Tax",

Page

95

JOptionPane.IN FORMATION_MESSAGE); System.exit(0); } } Amount (dollars) 36.00 40.00 52.60 87.95 125.00 182.93 Sales Tax (dollars) 2.16 2.40 3.16 5.28 7.50 10.98

5a. Write a QuickTest program that displays the following prompt in an input dialog box: Enter the temperature in degrees Celsius Have your program accept a value entered from the keyboard and convert the temperature entered to degrees Fahrenheit using the formula Fahrenheit = (9.0 / 5.0) * Celsius + 32.0. Your program should then display the temperature in degrees Celsius with an appropriate output message. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String userEntry; String message;

Page

96

userEntry JOptionPane.showInputDialog("Enter tempeature in " +

double CTemp; double FTemp;

= the "deg

rees Celsius"); CTemp = Double.parseDouble(userEntry); FTemp = (9.0 / 5.0) * CTemp + 32.0; message = "Celsius Temperature: " + CTemp + "\n"; message += "Fahrenheit Temperature: " + FTemp; JOptionPane.showMessageDialog(null,message," Temperatures", JOptionPane.IN FORMATION_MESSAGE); System.exit(0); } } 5b. Compile and execute the program written for Exercise 5a. Verify your program by hand calculation and then use your program to determine the Fahrenheit equivalent of the following test data: Celsius 0 50 100 45 50 55 60 Fahrenhei t 32 122 212 113 122 131 140

Page

97

65 70

149 158

Students should verify the program by ensuring that the above values match with the results computed by the program. 7a. Write and execute a QuickTest program that uses input dialog boxes to display the following prompts: Enter the miles driven: Enter the gallons of gas used: Your program should use the entered values to calculate and display the miles per gallon. Use the equation miles per gallon = miles / gallons used. Verify your procedure with the following test data: import javax.swing.*; public class QuickTest { public static void main(String[] args) { String userEntry; String message; double miles; double gallons; userEntry = JOptionPane.showInputDialog( "Enter the number of miles driven"); miles = Double.parseDouble(userEntry); userEntry JOptionPane.showInputDialog("Enter the of gas used"); = gallons

Page

98

gallons = Double.parseDouble(userEntry); message = "Miles Driven: " + miles + "\n"; message += "Gallons of gas used: " + gallons + "\n"; message += "Miles Per Gallon: " + (miles / gallons); JOptionPane.showMessageDialog(null, message, "Gas Mileage Information", JOptionPane.IN FORMATION_MESSAGE); System.exit(0); } } Miles Driven 276 200 250 275 312 296 Gallons Used 10 15.5 16.00 18.00 19.54 17.39 MPG 17.6 12.9032 15.6250 15.2778 15.9672 17.0213

7b. For the program written in Exercise 7a, determine how many verification runs are required to ensure the procedure is working correctly and give a reason supporting your answer. Because of the extreme simplicity of the program, with the main operation in the program being a simple division, three trial runs with non-zero numbers should be sufficient to ensure that the program is working correctly.

Page

99

9a. Write a QuickTest program that displays the following prompts in three separate input dialog boxes: Enter a number: Enter a second number: Enter a third number: After the third number has been entered, your program should calculate and display the average of the numbers. The average should be included in an appropriate message. Verify your program using the following test data: import javax.swing.*; public class QuickTest { public static void main(String[] args) { String userEntry; String message; double numberOne; double numberTwo; double numberThree; userEntry = JOptionPane.showInputDialog("Enter a number:"); numberOne = Double.parseDouble(userEntry); userEntry = JOptionPane.showInputDialog("Enter a second number:"); numberTwo = Double.parseDouble(userEntry); userEntry JOptionPane.showInputDialog("Enter a number:"); = third

Page 100

numberThree = Double.parseDouble(userEntry); message = "First Number: " + numberOne + "\n"; message += "Second Number: " + numberTwo + "\n"; message += "Third Number: " + numberThree + "\n"; message += "Average Value: " + ((numberOne + numberTwo + numberThree)/3.0); JOptionPane.showMessageDialog(null,message," Average", JOptionPane.IN FORMATION_MESSAGE); System.exit(0); } } Numbers 100,100,100 100,50,0 92,98,79 86,84,75 63,85,74 Average 100 50 89.67 81.67 74

11. Enter and execute QuickTest Program 4-4 on your computer. Record the exception message displayed when you: i. Click the OK button without entering any data Program exits with a NumberFormatException ii. Enter the characters oops and click OK Program exits with a NumberFormatException

Page 101

iii. Click the Cancel button Program exits with a NullPointerException 13. Modify QuickTest Program 4-5 so that the try block only contains the statements num1 = Double.parseDouble(s1); num2 = Double.parseDouble(s2); import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1; String s2; double num1 = 0; double num2 = 0; double average = 0; s1 = JOptionPane.showInputDialog("Enter a number:"); s2 = JOptionPane.showInputDialog("Great! Now enter another number:"); try { }

num1 = Double.parseDouble(s1); num2 = Double.parseDouble(s2);

catch(NumberFormatException n) {

Page 102

JOptionPane.showMessageDialog(null, "You must enter a number", "In put Data Error", JOp tionPane.ERROR_MESSAGE); System.exit(1); } catch(NullPointerException n) { JOptionPane.showMessageDialog(null, "You Pressed the Cancel Button", "Pr ogram Terminiation", JOp tionPane.ERROR_MESSAGE); System.exit(1); } average = (num1 + num2) / 2.0; JOptionPane.showMessageDialog(null, "The average of " + num1 + " and " + num2 + " is " + average, "QuickTest Program 4.5", JOptionPane.INFORMATION_MESSAGE); } } Exercises 4.3 1. Enter and compile Program 4-7s ID class. System.exit(0);

Page 103

Students should enter and compile the specified program. 3. Rewrite Program 4-1 so that it uses Program 4-7s readDouble() method. public class MultiplyNumbers { public static void main(String[] args) throws java.io.IOException { String s1; String s2; double num1, num2, product; System.out.print(Enter a number: ); num1 = ID.readDouble(); System.out.print(Great! Now enter another number: ); num2 = ID.readDouble(); product = num1 * num2; System.out.println(num1 + times + num2 + is + product); } } Exercises 4.4 1a. Enter and execute QuickTest Program 4-9 on your computer. The user should enter and execute the specified program. 1b. Determine the output of QuickTest Program 4-9 if the format string ### is substituted for the format string 000.

Page 104

6 18 124 --148 3. Determine the formatted string that results when a. the format string "##" is applied to the number 5 5 b. the format string "####" is applied to the number 5 5 c. the format string "####" is applied to the number 56829 56829 d. the format string "###.##" is applied to the number 5.26 5.26 e. the format string "###.##" is applied to the number 5.267 5.27 f. the format string "###.##" is applied to the number 53.264 53.26 g. the format string "###.##" is applied to the number 534.264 534.26 h. the format string "###.##" is applied to the number 534.0 534.0

Page 105

5. Write a QuickTest program to calculate and display the value of the slope of the line connecting the two points whose coordinates are (3,7) and (8,12). Use the fact that the slope between two points having coordinates (x1,y1) and (x2,y2) is slope = (y2 - y1) / (x2 - x1). The display produced by your program should be: The value of the slope is xxx.xx, where xxx.xx denotes that the calculated value should be placed in a field wide enough for three places to the left of the decimal point, and two places to the right of it. import java.text.*; public class QuickTest { public static void main(String[] args) { double slope = (7-12)/(3-8); DecimalFormat num = DecimalFormat(###.00);

new

System.out.println(The value of the slope is + num.format(slope); } } Exercises 4.5 1. Write valid Java statements to determine: a. The square root of 6.37 Math.sqrt(6.27); b. The square root of x y Math.sqrt(x-y); c. The smaller of the values -30.5 and -42.7

Page 106

Math.min(-30.5, -42.7); d. The larger of the values 109 and 101 Math.max(109, 101); e. The absolute value of a2 - b2 Math.abs(a*a b*b); f. The value of e raised to the 3rd power Math.exp(3); 3. Write Java statements for the following: ______ 2 a. c = a + b2 c = Math.sqrt(a*a + b*b); _______ b. p = |m - n| p = Math.sqrt(Math.abs(m-n)); c. sum = a(rn - 1) sum = r - 1 sum = a * (Math.pow(r,n) 1) / (r 1); 5. Write, compile, and execute a QuickTest program that calculates the distance between two points whose coordinates are (7,12) and (3,9). Use the fact that the distance between two points having coordinates (x1,y1) and (x2,y2) is distance = sqrt([x1 - x2]2 + [y1 y2]2). When you have verified that your program works correctly by calculating the distance between the two points manually, use your program to determine the distance between the points (-12,-15) and (22,5).

Page 107

public class QuickTest { public static void main(String[] args) { final int X1 = 7; final int Y1 = 12; final int X2 = 3; final int Y2 = 9; double distance; result = Math.sqrt((X1-X2)*(X1-X2) + (Y1Y2)*(Y1-Y2)); System.out.println(The computed distance is + distance); } } 7. Modify QuickTest Program 4-11 so that the displayed time always has a maximum of four digits after the decimal point. import java.text.*; public class FallTime { public static void main(String[] args) { int height; double time; DecimalFormat df = new DecimalFormat(#.####); height = 800; time = Math.sqrt(2 * height / 32.2);

Page 108

System.out.println(It will take + df.format(time) + seconds to fall + height + feet.); } } 9a. Write a general-purpose method called mult() that accepts two floating-point numbers as parameters, multiplies these two numbers, and displays the result. public static void mult(double num1, double num2) { double result = num1 * num2; System.out.println(num1 + times + num2 + is equal to + result); } b. Include the method written in Exercise 9a in a working program. Make sure your method is called from main(). Test the method by passing various data to it. public class QuickTest { public static void mult(double num1, double num2) { double result = num1 * num2; System.out.println(num1 + times + num2 + is equal to + result); }

Page 109

public static void main(String[] args) { double num1 = 5.5; double num2 = 9.3; mult(num1,num2); } }

11a. Write a general-purpose method named powfun() that raises a long integer number passed to it to a positive integer power (also passed as an argument) and displays the result. The positive integer should be the second value passed to the method. Additionally, declare the variable used to store the result as a long integer data type to ensure sufficient storage for the result. public static void powfun(long number, int power) { long result = (long)(Math.pow(number,power)); System.out.println(number raised to the power power is equal to result); + + + +

b. Include the method written in Exercise 9a in a working program. Make sure your method is called from main(). Test the method by passing various data to it.

Page 110

public class QuickTest { public static void powfun(long number, int power) { long result = (long) (Math.pow(number,power)); System.out.println(number raised to the power power is equal to result); + + + +

public static void main(String[] args) { long number = 1000L; int power = 3; } } 13. Although we have been concentrating on integer and real arithmetic, Java allows characters to be added or subtracted. This can be done because Java always converts a character to an equivalent integer value whenever a character is used in an arithmetic expression (the decimal value of each character can be found in Appendix B). Thus, characters and integers can be freely mixed in arithmetic expressions. For example, using the Unicode code, the expression 'a' + 1 equals 98, and 'z' - 1 equals 121. These values can be converted back into characters using the cast powfun(number,power);

Page 111

operator. Thus, (char) ('a' + 1) = 'b' and (char) ('z' - 1) = 'y'. Similarly, (char)('A' + 1) is 'B', and (char)('Z' - 1) is 'Y'. With this as background, determine the results of the following expressions (assume that all characters are stored using the Unicode code): a. b. c. d.
(char) ('m' - 5) = h (char) ('m' + 5) (char) ('G' + 6) (char) ('G' - 6)

e. = r f. = M g. = A

('b' - 'a') ('g' - 'a' ('G' - 'A'

= 1 + 1) = 7 + 1) = 7

15. Modify QuickTest Program 4-12 so that the following line of code is placed immediately before main()'s closing brace: Long.parseLong(numstring); Attempt to compile and run the modified program and then determine what the error is and when is it reported (at compile time or run time)? The code will compile. However, at run time, an error will be reported indicating that the argument of parseLong is not formatted correctly.

Page 112

III. Sample Test Questions Chapter 4 1) GUI stands for a) generalized user interface b) graphical user interface c) general unsigned integer d) generally useful interface Answer: (B) 2) System.in is a) the foundation object upon which data can be entered into a program while it is executing b) the object that command line arguments depend upon to execute c) the foundation object upon which data can be entered into a data file from an executing program d) none of the above Answer: (A) 3) A token is defined as a) a collection of numbers b) a small string (less than 10 characters) used to partition a larger string c) a collection of characters separated by a delimiting character d) a collection of integers separated into parts by a comma Answer: (C)

Page 113

4) The process of separating individual tokens from a string is formally called a) string separation b) string formatting c) parsing the string d) string data extraction Answer: (C)

5) What is the output of the following lines of code? String s1 = A 12 B B 1.3; StringTokenizer st = new StringTokenizer(s1); for (int i = 0; i < 2; i++) st.nextToken(); System.out.println(st.nextToken()); a) A b) 12 c) B d) 1.3 Answer: (C) 6) A NumberFormatException occurs whenever a) an attempt is made to divide by zero b) an attempt is made to access an object that does not exist

Page 114

c) an attempt is made to convert a string that does not contain the appropriate characters for the desired number type d) an attempt is made to perform an illegal arithmetic operation Answer: (C) 7) An ArithmeticException occurs whenever a) an attempt is made to convert an integer into a double value b) an attempt is made to access an object that does not exist c) an attempt is made to convert a string that doesnt not contain the appropriate characters for the desired number type d) an attempt is made to divide by zero Answer: (D) 8) A NullPointerException occurs whenever a) an attempt is made to convert an integer into a double value b) an attempt is made to access an object that does not exist c) an attempt is made to convert a string that does not contain the appropriate characters for the desired number type d) an attempt is made to perform an illegal arithmetic operation Answer: (B) 9) What is the output of the following lines of code? DecimalFormat df = new DecimalFormat(00.00); System.out.println(df.format(3.93021));

Page 115

a) 03.93021 b) 3.93 c) 03.93 d) 3.93021 Answer: (C) 10) What is the output of the following lines of code? DecimalFormat df = new DecimalFormat(#0.00); System.out.println(df.format(3.93021)); a) 03.93021 b) 3.93 c) 03.93 d) 3.93021 Answer: 3.93 11) What is the output of the following lines of code? DecimalFormat df = DecimalFormat(%##.00); System.out.println(df.format(3.93021)); a) %393.02 b) 393.02% c) %3.93 d) %03.93 Answer: (A) new

Page 116

12) Which of the following java statements will compute the result of the expression (a^2 + b^2)^0.5 a) Sqrt(a*a + b*b); b) Math.Sqrt(a*a + b*b); c) sqrt(Math.pow(a,2) + Math.pow(b,2)); d) Math.sqrt(a*a + b*b); Answer: (D) 13) A logic error is a) an unintentional result due to a flaw in the program b) an error that causes a program not to compile c) usually caught by the compiler d) always caught by a compiler Answer: (A) 14) A syntax error is a) an unintentional result due to a flaw in the program b) sometimes caught by the compiler c) usually caught by the compiler d) always caught by a compiler Answer: (D) 15) The method of detecting errors before a program is compiled is called

Page 117

a) program testing b) logic checking c) desk checking d) syntax checking Answer: (C)

Page 118

I. OVERVIEW: Chapter 5 Selection The term flow of control refers to the order in which a program's statements are executed. Unless directed otherwise, the normal flow of control for all programs is sequential. This means that each statement is executed in sequence, one after another, in the order in which they are placed within the program. Both selection and repetition statements allow the programmer to alter the normal sequential flow of control. As their names imply, selection statements provide the ability to select which statement, from a well-defined set, will be executed next, whereas repetition statements provide the ability to go back and repeat a set of statements. In this chapter, we present Java's selection statements, while repetition statements are presented in Chapter 6. Since selection requires choosing between alternatives, this chapter begins with a description of Java's selection criteria. 5.1 Relational Expressions 5.2 The if-else Statement 5.3 Nested if Statements 5.4 The switch Statement 5.5 Program Design and Development: Introduction to UML 5.6 Application: A Date Class 5.5 Common Programming Errors 5.6 Chapter Review 5.7 Chapter Supplement: Program Testing

Potential Problem areas: Overall, this is a fairly straightforward chapter. Students may have trouble with the various logic issues that are raised, e.g., DeMorgans

Page 119

Laws. The syntax of the switch statement is somewhat confusing. UML class diagrams can be confusing; plan to spend extra class time going over a variety of UML diagrams.

Page 120

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 5.1 1. Determine the value of the following expressions. Assume a = 5, b = 2, c = 4, d = 6, e = 3, and all variables are integers. a a d a d a a c b > b != b % b == c * c != d * b == c * b < a % b * c % b * a % c * a TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE

% b * b * e % b * c > c % b * a == b % c * a != a * b

3. Write relational expressions to express the following conditions (use variable names of your own choosing): a. a person's age is equal to 30 age == 30 b. a person's temperature is greater than 98.6 temp > 98.6 c. a person's height is less than 6 feet height < 6 d. the current month is 12 (December) month == 12 e. the letter input is m

Page 121

input == m f. a person's age is equal to 30 and the person is taller than 6 feet age == 30 && height > 6 g. the current day is the 15th day of the 1st month day == 15 && month == 1 h. a person is older than 50 or has been employed at the company for at least 5 years age > 50 || employedTime >= 5 i. a person's identification number is less than 500 and the person is older than 55 IDNumber < 500 && age > 55 j. a length is greater than 2 feet and less than 3 feet length > 2 && length < 3 Exercises 5.2 1. Write appropriate if statements for each of the following conditions: a. If the variable named angle is equal to 90 degrees, print the message The angle is a right angle; otherwise, print the message The angle is not a right angle. if (angle == 90) System.out.println(The angle is a right angle); else

Page 122

System.out.println(The angle is not a right angle); b. If the temperature is above 100 degrees display the message above the boiling point of water; otherwise, display the message below or equal to the boiling point of water. if (temperature > 100) System.out.println(above the boiling point of water); else System.out.println(below or equal to the boiling point of water); c. If the variable number is positive, add number to possum; otherwise, add the number to negsum if (number > 0) possum += number; else negsum += number; c. If the variable slope is less than 0.5, set the variable flag to zero; otherwise, set flag to one. if (slope < 0.5) flag = 0; else flag = 1; d. If the difference between the variables num1 and num2 is less than 0.001, set

Page 123

the variable approx to zero; otherwise, calculate approx as the quantity (num1 num2) / 2.0. if (Math.abs(num1 num2) < 0.001) approx = 0; else approx = (num1 num2) / 2.0; e. If the difference between variables temp1 and temp2 exceeds 2.3 degrees, calculate the variable error as (temp1 temp2) * factor. if (Math.abs(temp1 temp2) > 2.3) error = (temp1 temp2) * factor; f. If the variable x is greater than the variable y and the variable z is less than 20, read in a value for the variable p. if (x > y && z < 20) { s1 = br.readLine(); p = Integer.parseInt(s1); } g. If the variable distance is greater that 20 and it is less than 35, read in a value for the variable time. if (distance > 20 && distance < 35) { s1 = br.readLine(); time = Integer.parseInt(s1); }

Page 124

3. QuickTest Program 5-1 uses dialog boxes for both input and output. Rewrite QuickTest Program 5-1 to use a readLine() method for keyboard input and a println() method for display. import java.text.*; public class CalculateTaxes { public static void main(String[] args) throws java.io.IOException { double taxable, taxes; String s1; DecimalFormat df = new DecimalFormat(,###.00); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println(Please type taxable income:); s1 = br.readLine(); taxable = Double.parseDouble(s1); in a

if (taxable <= 20000.00) taxes = 0.02 * taxable; else taxes = 0.025 * (taxable 20000.0) + 400.0; System.out.println(Taxes df.format(taxes)); } } are $ +

Page 125

5. QuickTest Program 5-2 uses a readLine() for keyboard input and println() for console display. Rewrite this program to use dialog boxes for both input and output. import java.text.*; import javax.swing.*; public class ConvertTemperatures() { public static void main(String[] args) { int tempType; double temp, fahren, celsius; String s1; DecimalFormat DecimalFormat(,###.00); num = new

s1 = JOptionPane.showInputDialog( Enter the temperature converted); temp = Double.parseDouble(s1);

to

be

s1 = JOptionPane.showInputDialog( Enter a 1 if the temperature is in Fahrenheit or a 2 + if the temperature is in Celsius); tempType = Integer.parseInt(s1); if (tempType == 1) { celsius = (5.0 / 9.0) * (temp 32.0); JOptionPane.showMessageDialog(null, The equivalent Celsius temperature is + num.format(celcius),

Page 126

Temperature JOptionPane.INFORMATION_MESSAGE); }

Conversion,

else { fahren = (9.0 / 5.0) * temp + 32.0; JOptionPane.showMessageDialog(null, The equivalent Fahrenheit temperature is + num.format(fahren), Temperature Conversion, JOptionPane.INFORMATION_MESSAGE); } } } 7a. In a pass-fail course, a student passes if the grade is greater than or equal to 70 and fails if the grade is lower. Write a Java program that accepts a grade and prints the message A passing grade or A failing grade, as appropriate. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1, message; int grade; s1 = JOptionPane.showInputDialog(Enter your grade); grade = Integer.parseInt(s1); if (grade >= 70)

Page 127

message = A passing grade; else message = A failing grade; JOptionPane.showMessageDialog( null, message, Pass JOptionPane.INFORMATION_MESSAGE); } } or Fail,

7b. How many runs should you make for the program written in Exercise 7a to verify that it is operating correctly? What data should you input in each of the program runs? Three runs should be sufficient because of the programs simplicity. The test values should be: a number greater than 70, a number equal to 70, and a number less than 70. 9a. A senior salesperson is paid $400 a week and a junior salesperson receives $275 a week. Write a Java program that accepts as input a salespersons status in the character variable status. If status equals s, the senior persons salary should be displayed; otherwise, the junior persons salary should be output. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1; double salary; s1 = JOptionPane.showInputDialog(Enter your status);

Page 128

if (s1.equals(s)) salary = 400.00; else salary = 275.00; JOptionPane.showMessageDialog( null, Salary is + salary, Salary Display, JOptionPane.INFORMATION_MESSAGE); } } 9b. How many runs should you make for the program written in Exercise 9a to verify that it is operating correctly? What data should you input in each of the program runs? Two runs should be sufficient. In the first run, enter an s when prompted. On the second run, enter anything other than an s. 11a. Write a program to display the following to prompts: Enter a month: (use a 1 for Jan, etc.) Enter a day of the month: Have your program accept and store a number in the variable month in response to the first prompt and accept and store a number in the variable day in response to the second prompt. If the month entered is not between 1 and 12 inclusive, display a message informing the user that an invalid month has been entered. If the day entered is not between 1 and 31, display a message informing the user that an invalid day has been entered. import javax.swing.*;

Page 129

public QuickTest { public static void main(String[] args) { String s1; int month, day; s1 = JOptionPane.showInputDialog( Enter a month: (use a 1 for Jan, etc.)); month = Integer.parseInt(s1); s1 = JOptionPane.showInputDialog(Enter a day of the month); day = Integer.parseInt(s1); if (month < 1 || month > 12) JOptionPane.showMessageDialog( null, Invalid Month, Error, JOptionPane.ERROR_MESSAGE); if (day < 1 || day > 31) JOptionPane.showMessageDialog( null, Invalid Day, Error, JOptionPane.ERROR_MESSAGE); System.exit(0); } } 11b. What will your program do if the user types a number with a decimal point for the month? How can you ensure that your if statements check for an integer number?

Page 130

The program will exit with a NumberFormat exception. Therefore, the if statements will only receive integer numbers. 13. Enter and execute QuickTest Program 5-3. Students should enter and execute the specified program. 15. The following main() method produces the output The value of t1 is true The value of t2 is false These values are equal public static void main(String[] args) { Boolean t1,t2; t1 = true; t2 = false; System.out.println(The value of t1 is + t1); System.out.println(The value of t2 is + t2); if (t2 = t1) System.out.println(These values are equal); else System.out.println(These values are not equal); } Determine why the output indicates the two Boolean values are equal when they clearly are not and correct the error in the method that produces the erroneous output.

Page 131

Inside the if statement, the expression t2 = t1 sets the value of t2 equal to the value of t1. This means that t2 becomes true. The if statement then simplifies to if (true) and so the program indicates that the values are equal. This can be corrected by substituting the if statement in the code for the following if statement: if (t2 == t1) Exercises 5.3 1. A students letter grade is calculated according to the following schedule: greater than or equal to 90 is an A less than 90 but greater than or equal to 80 is a B less than 80 but greater than or equal to 70 is a C less than 70 but greater than or equal to 60 is a D less than 60 is an F Write a Java program that accepts a students numerical grade, converts the numerical grade to an equivalent letter grade, and displays the letter grade. import javax.swing.*; public QuickTest { public static void main(String[] args) { String s1, letterGrade; double numericalGrade; s1 = JOptionPane.showInputDialog(Enter your numerical score); numericalGrade = Double.parseDouble(s1);

Page 132

if (numericalGrade >= 90) letterGrade = A; else if (numericalGrade >= letterGrade = B; else if (numericalGrade >= letterGrade = B; else if (numericalGrade >= letterGrade = C; else if (numericalGrade >= letterGrade = D; else letterGrade = F;

80) 80) 70) 60)

JOptionPane.showMessageDialog( null, Your Letter Grade is: + letterGrade, Letter Grade, JOptionPane.INFORMATION_MESSAGE); } } 3. Each disk drive in a shipment of these devices is stamped with a code from 1 through 4, which indicated a drive manufacturer as follows: 1 is 3M Corporation 2 is Maxell Corporation 3 is Sony Corporation 4 is Verbatim Corporation Write a Java program that accepts the code number as input and, based on the value entered, displays the correct disk drive manufacturer. System.exit(0);

Page 133

import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1, message; int codeNumber; s1 = JOptionPane.showInputDialog(Enter the company code number); codeNumber = Integer.parseInt(s1); if (codeNumber == 1) message = 3M Corporation; else if (codeNumber == 2) message = Maxell Corporationi; else if (codeNumber == 3) message = Sony Corporation; else if (codeNumber == 4) message = Verbatim Corporation; JOptionPane.showMessageDialog( null, message, Manufacturer Info, JOptionPane.INFORMATION_MESSAGE); } } 5. The following program was written to produce the same result as QuickTest Program 5-5: import javax.swing.*; import java.text.*; System.exit(0);

Page 134

public class CalculateIncome { public static void main(String[] args) { String s1, outMessage; double monthlySales, income; DecimalFormat DecimalFormat(,###.00); num = new

s1 = JOptionPane.showInputDialog(Enter the value of monthly sales:); monthlySales = Double.parseDouble(s1); if (monthlySales < 10000.00) income = 200.00 + 0.03 * monthlySales; else if (monthlySales >= 10000.00) income = 250.00 + 0.05 * monthlySales; else if (monthlySales >= 20000.00) income = 300.00 + 0.09 * monthlySales; else if (monthlySales >= 30000.00) income = 325.00 + 0.12 * monthlySales; else if (monthlySales >= 40000.00) income = 350.00 + 0.14 * monthlySales; else if (monthlySales >= 50000.00) income = 375.00 + 0.15 * monthlySales; outMessage = For the monthly sales of $ + num.format(monthlySales) + \nThe income is $ + num.Format(income); JOptionPane.showMessageDialog(null,outMess age,QuickTest Program 5.5b,

Page 135

JOptionPane. INFORMATION_MESSAGE); } } a. Will this program run? The program will run. b. What does this program do? This program tries to compute a salespersons income based on their monthly sales. c. For what values of monthly sales does this program calculate the correct income? This program will compute the correct result for monthly sales less than $10,000. Exercises 5.4 1. Rewrite the following if-else chain using a switch statement: if (letterGrade == A) System.out.println(The numerical grade is between 90 and 100); else if (letterGrade == B) System.out.println(The numerical grade is between 80 and 89.9); else if (letterGrade == C) System.out.println(The numerical grade is between 70 and 79.9); System.exit(0);

Page 136

else if (letterGrade == D) System.out.println(How are you going to explain this one?); else { System.out.println(Of course I had nothing to do with my grade.); System.out.println(\nThe professor was really off the wall.); } Solution: switch (letterGrade) { case A: System.out.println(The numerical grade between 90 and 100); break; case B: System.out.println(The numerical grade between 80 and 89.9); break; case C: System.out.println(The numerical grade between 70 and 79.9); break; case D: System.out.println(How are you going explain this one); break; default: System.out.println( Of course I had nothing to do with grade. The professor +

is

is

is

to

my

Page 137

was really off the wall); } 3. Rewrite QuickTest Program 5-4 in Section 5.3 using a switch statement. import javax.swing.*; import java.text.*; public class MarriedStatus { public static void main(String[] args) { String s1, inMessage, outMessage; int marCode; inMessage = Enter a marriage code:\n + 1 = Single\n + 2 = Married\n + 3 = Divorced\n + 4 = Widowed\n; JOptionPane.showInputDialog(inMessage); marCode = Integer.parseInt(s1); switch (marCode) { case 1: outMessage = Individual is single.; break; case 2: s1 =

Page 138

outMessage = Individual is married.; break; case 3: break; case 4:

outMessage = Individual is

divorced.;

outMessage = Individual is

widowed;

break; default: outMessage = An invalid code was entered.; } JOptionPane.showMessageDialog( null, outMessage, QuickTest Program JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }

5.4,

5. Repeat Exercise 3 in section 5.3 using a switch statement instead of an if-else chain. import javax.swing.*; public class QuickTest { public static void main(String[] args) {

Page 139

String s1, message; int codeNumber; s1 = JOptionPane.showInputDialog(Enter the company code number); codeNumber = Integer.parseInt(s1); switch (codeNumber) { case 1: message = 3M Corporation; break; case 2: message = Maxell Corporation; break; case 3: message = Sony Corporation; break; case 4: message = Verbatim Corporation; } JOptionPane.showMessageDialog( null, message, Manufacturer Info, JOptionPane.INFORMATION_MESSAGE); } } 7. Write a Java method named daysInMonth() that returns the number of days in a month. The month should be passed into the method as an integer argument (that is January = 1, February = 2, System.exit(0);

Page 140

and so on). The header line for the method is: public static int daysInMonth(int month) In developing the body of the method use a switch statement to implement the following algorithm. If the month integer is 1,3,5,7,8,10, or 12 return 31 ElseIf the month is 2 return 28 Else return 30 EndIf public static int daysInMonth(int month) { int numDays; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 28; break; case 2: numDays = 2; break; default: numDays = 30; } return numDays; } Exercises 5.5

Page 141

1. Define the following terms: attribute A characteristic that each object in the class must have is an attribute..
a.

aggregation Aggregation is a particular type of an association where one class or object, referred to as the whole element, consists of or, alternatively, is composed of, another class or object, which is referred to as a part..
b.

association Classes signified by phrases is related to, is associated with, has a, is employed by, and works for are related by association.
c.

class A class is a blueprint from which many specific objects can be created.
d.

class diagram A class diagram is used to describe classes and their relationships.
e.

generalization Generalization characterizes a relationship between a class and a refined version of the class.
f.

multiplicity An indication of the number of one type of object that can be associated with another type of object is its multiplicity.
g.

program model A program model is the design for an application.


h.

object An object refers to a specific, single item created from a class.


i.

Page 142

object diagram A diagram used to describe specific objects and their relationships is an object diagram.
j.

operation An operation is a transformation that can be applied to attributes.


k.

3a. Construct a class diagram for a single gas tank that is connected to one or more gas pumps. The attributes of interest for the tank are its capacity, current level, and grade of gas. Additionally, the pump responds to being enabled or disabled.

3b. Modify the class diagram constructed in Exercise 3a to account for the fact that a gas pump may be associated with more than one gas tank

5a. Construct a class diagram for a computer that consists of a monitor, keyboard, mouse, printer, and system box.

Page 143

5b. Modify the class diagram constructed in Exercise 5a to account for the fact that one or more monitors and keyboards may be attached to the system box and that the system may have no mouse or may have multiple mice.

5c. Extend the class diagram constructed for Exercise 5b to denote that the system box is composed of a CPU chip, a memory board containing zero or more RAM chips, and one case.

Page 144

7. Construct a class diagram for a collection of cards that consists of zero or more individual cards. The collection of cards forms a base class for both a deck of cards and an individual hand of cards.

Page 145

9. Have the team as a whole determine a cars major subsystems, such as brakes, steering, etc. Then, considering these subsystems as classes, construct a class diagram for a Car class that simply shows the associations between classes (no attributes or operations). Assign each subsystem to individual team members. Have them determine a set of attributes and operations appropriate to their assigned subsystem. When each member has completed their task, modify the original class diagram to include the additional information. Answers will vary. Exercises 5.6 1. List any additional operations that you think could be included in Figure 5-22. yearDifference() isWeekEnd() nextWeek() nextMonth() etc.

3. Enter and execute Program 5-7 Students should enter and execute the specified program. 5. Rewrite Program 5-7 to include user-entered input for the day, month, and year. For this program use the readInt() method contained with the ID class. public class UseDate { public static void main(String[] args) throws java.io.IOException

Page 146

{ Date firstDate; Date secondDate; String s1; int day, month, year; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print(Enter the first day:); s1 = br.readLine(); day = Integer.parseInt(s1); month:); s1 = br.readLine(); month = Integer.parseInt(s1); System.out.print(Enter the first

System.out.print(Enter the first year:); s1 = br.readLine(); year = Integer.parseInt(s1); firstDate = new Date(month, day, year); System.out.print(Enter the second day:); s1 = br.readLine(); day = Integer.parseInt(s1); System.out.print(Enter month:); s1 = br.readLine(); month = Integer.parseInt(s1); year:); System.out.print(Enter the second the second

Page 147

s1 = br.readLine(); year = Integer.parseInt(s1); secondDate = new Date(month, day, year); firstDate.showDate(); secondDate.showDate(); } }

7. Add a method named isWeekday() that returns a Boolean true value if the date is a weekday; otherwise it should return a Boolean false value. The method should call dayOfWeek() and then use the returned integer value to determine if the day is a weekday. A weekday is any day between 2 and 6, inclusive, which corresponds to the days Monday through Friday. public Boolean isWeekday() { int day = this.dayOfWeek(); if (day >=2 && day <= 6) return true; else return false; } 9. Modify Program 5-6 so that the only instance variable of the class is a long interger named yyyymmdd. Do this by substituting the declaration private long yyyymmdd; for the existing declarations

Page 148

private int month; private int day; private int year; Once this is done, rewrite each class method to correctly initialize the single class data member. public class Date { private long yyyymmdd; public Date() { yyyymmdd = 2005*10000 + 7*100 + 4; System.out.println(From the default constructor: + \n Created a new Date object with data values + \n month = month + day = + day + year = + year + \n); } public Date(int mm, int dd, int yyyy) { yyyymmdd = yyyy*10000 + mm*100 + dd; System.out.println(From the overloaded constructor: + \n Created a new Date object with data values + \n month = month + day = + day + year = + year + \n); }

Page 149

public void setDate(int mm, int dd, int yyyy) { yyyymmdd = yyyy*10000 + mm*100 + dd; } public void showDate() { DecimalFormat DecimalFormat(00); long month, day, year;

df

new

year = yyyymmdd / 10000L; month = (yyyymmdd year*10000L) / 100; day = yyyymmdd year*10000L month*100L; System.out.println(The date df.format(month) + / + df.format(day) + / + df.format(year % 100)); } } is

11. Modify Program 5-6s Date class to include an isEqual() method. This method should compare two Date objects and return a Boolean value of true if the two dates are equal. The header for this method should be public Boolean isEqual(Date second). public Boolean isEqual(Date second) { if (second.year == year && second.month == month && second.day == day) return true;

Page 150

else return false;

13. Modify Program 5-6s Date class to include a priorDay() method that decrements a date by one day. Test your method to ensure that it correctly decrements days into a prior month and into a prior year. public void priorDay() { if (day > 1) day--; else { if (month > 1) { month--; day = getNumDays(month); } else { month = 12; day = 31; year--; } } }

private int getNumDays(int month) { int numDays;

Page 151

if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) numDays = 31; else if (month == 2) numDays = 28; else numDays = 30; return numDays; }

15. Construct a class named Light that will be used to simulate a traffic light. The class should contain a single instance variable having a data type of String. When a new Light object is created its initial color should be red. Additionally, there should be a method that can be used to change the state of a Light object and an accessor method that returns the color currently stored in a Light objects instance variable. public class Light { String color; public Light() {color = red;} public void changeColor(String {this.color = color;} color)

public String getColor() {return color;}

Page 152

Page 153

III. Sample Test Questions Chapter 5 For problems 1 - 4, assume a = 5, b = 2, c = 4, d = 6, and e = 5 1) What is the value of a > b? a) 1 b) false c) 0 d) true Answer: (D) 2) What is the value of d % b == c % b ? a) 0 b) true c) 1 d) false Answer: (B) 3) What is the value of !(a % b * c > e) ? a) true b) false c) 0 d) 1 Answer: (A)

Page 154

4) What is the value of e % b * c > 5 || c % b * d < 7 ? a) 0 b) true c) false d) 1 Answer: (B)

5) Convert the following statement to Java: If the number is positive, add it to posSum, otherwise add it to negSum. a) if (n is positive) posSum += n; else negSum += n; b) if (n == 0) posSum += n; else negSum += n; c) if (n > 0) posSum += n; else negSum += n; c) if (n = 0) posSum += n; else negSum += n; Answer: (C) 6) Convert the following statement to Java: If the number is even, add it to evenSum, otherwise add it to oddSum. a) if (n is even) evenSum += n;

Page 155

else oddSum += n; b) if (n == 0) evenSum += n; else oddSum += n; c) if (!n is odd) evenSum += n; else oddSum += n; d) if (n %2 == 0) evenSum += n; else oddSum += n; Answer: (D) 7) Convert the following statement to Java: If the absolute value of the difference between voltage1 and voltage2 exceeds x, calculate the error as (voltage1 - voltage2) * errorFactor. a) if (abs(v1-v2) > x) error = abs(v1-v2) * errorFactor; b) if ((v1-v2) > x) error = (v1-v2) * errorFactor; c) if (abs(v1-v2) >= x) error = abs(v1-v2) * errorFactor; d) if (abs(v1-v2) <= x) error = abs(v1-v2) * errorFactor; Answer: (A)

Page 156

8) Convert the following statement to Java: The commission on fewer than 10 sales is $10/sale. The commission on 10 sales is $15/sale. The commission on more than 10 sales is $20/sale. a) if ( sales < 10 ) commission = 10; else if ( sales == 10 ) commission = 15; else commission = 20; b) if ( sales < 10 ) commission = 10 * sales; else if ( sales = 10 ) commission = 15 * sales; else commission = 20 * sales; c) if ( sales < 10 ) commission == 10 * sales; else if ( sales = 10 ) commission == 15 * sales; else commission == 20 * sales; d) if ( sales < 10 ) commission = 10 * sales; else if ( sales == 10 ) commission = 15 * sales; else commission = 20 * sales; Answer: (D)

Page 157

9) Convert the following statements to Java: If the semester grade is less than 60, the letter is F. If the grade is between 60 and 90, the letter is C. If the grade is over 90, the letter is A. a) if ( grade < 60 ) letter = F; else if ( grade >= 60 && grade <= 90 ) letter = C; else letter = A; b) if ( grade < 60 ) letter = F; else if ( grade >= 60 && grade <= 90 ) letter = C; else letter = A; c) if ( grade <= 60 ) letter = F; else if ( grade > 60 && grade < 90 ) letter = C; else letter = A; d) if ( grade <= 60 ) letter = F; else if ( grade >= 60 && grade <= 90 ) letter = C; else letter = A;

Page 158

Answer: (B) 10) Convert the following statement to Java: If the input code letter is R, compute the area of a rectangle. If the code letter is C, compute the area of a circle. If the code letter is S, compute the area of a square a) if ( code = R ) area = length * width; else if ( code = C ) area = PI * sqr(radius); else area = sqr(side); b) if ( code == R ) area = length * width; else if ( code == C ) area = PI * sqr(radius); else area = sqr(side); c) if ( code == R ) area = length * width; else if ( code == C ) area = PI * sqr(radius); else area = sqr(side); d) if ( code = R ) area == length * width; else if ( code = C ) area == PI * sqr(radius);

Page 159

else area == sqr(side); Answer: (C) 11) In a switch statement, the keyword break a) is accessed if none of the other case values match the expression b) causes the program to exit the switch statement completely c) causes the program to move to the default case d) causes the program to terminate Answer: (B) 12) In a switch statement, the keyword default a) is accessed if none of the other case values match the expression b) causes the program to exit the switch statement completely c) causes the program to move to the default case d) causes the program to terminate Answer: (A) 13) The switch expression must evaluate to a) any numerical value b) one of the case values c) one or more of the case values d) an integer value Answer: (D)

Page 160

14) What is the best kind of statement to express the following: if the grade is less than 60, the letter is F; if the grade is between 60 and 90, the letter is C; if the grade is above 90, the letter is A. a) switch statement b) One-way if statement c) If chain d) Two-way if Answer: (C) 15) What is the best kind of statement to express the following: if the input code is V, compute the volume; if the input code is A, compute the area; if the input code is P, compute the perimeter. a) switch statement b) One-way if statement c) If chain d) Two-way if Answer: (A)

Page 161

I. OVERVIEW: Chapter 6 Repetition This chapter presents Java statements for constructing repeating sections of code. More commonly, a section of code that is repeated is referred to as a loop, because after the last statement in the code is executed the program branches, or loops back to the first statement and starts another repetition through the code. Each repetition is also referred to as an iteration or pass through the loop. Examples of situations requiring a repetition capability that will be presented in this chapter include continual checking of user data entries until an acceptable entry, such as a valid password, is entered, counting and accumulating running totals, and acceptance of input data and recalculation of output values that only stops upon entry of a predetermined sentinel value. 6.1 Introduction 6.2 The while Statement 6.3 Interactive while Loops 6.4 The for Statement 6.5 The do-while Statement 6.6 Recursion 6.7 Program Design and Development: State and Sequence Diagrams 6.8 Applications: Random Numbers Simulations 6.9 Common Programming Errors 6.10 Chapter Review

Potential Problem areas: The while loop can be confusing. Make sure students learn to recognize when a particular loop structure is appropriate.

Page 162

Recursion is always confusing to students; plan to spend extra time with it or postpone.

Page 163 I.

II. ANSWERS TO ODD-NUMBERED EXERCISES

Exercises 6.2 1. Rewrite QuickTest program 6.1 to print the numbers 2 to 10 in increments of 2. The output of your program should be: 2 4 6 8 10 public class ShowWhile { public static void main(String[] args) { int count = 2; while (count <= 10) { System.out.print(count + ); count += 2; }

} }

3a. For the following main() method determine the total number of items displayed. Also determine the first and last numbers printed. public static void main(String[] args) { int num = 0; while (num <= 20) { num++; System.out.print(num + );

Page 164

} } Solution: Twenty one items are displayed with the first and last numbers being 1 and 21 respectively. 3b. Enter and run the program from Exercise 3a on a computer to verify your answers to the exercise. Students should enter and run the specified program. 3c. How is the output affected if the two statements within the computed statement were reversed that is, if the print() call were made before the num++ statement. The beginning of the output would be the number 0 and the end would be the number 20. 5. Write a Java program that converts feet to meters. The program should display feet from 3 to 30 in 3-foot increments and the corresponding meter equivalents. Use the relationships that there are 3.28 feet to 1 meter. public class FeetToMeter { public static void main(String[] args) { double feet = 3.0; DecimalFormat df = DecimalFormat(0.00); while (feet <= 30)

new

Page 165

{ System.out.println( df.format(feet) + feet is equal to + df.format((1.0/3.28)*feet) + meters.); } } 7. An automobile travels at an average speed of 55 miles per hour for 4 hours. Write a Java program that displays the distance driven, in miles, that the car has traveled after 0.5, 1.0, 1.5, etc., hours until the end of the trip. public class QuickTest { public static void main(String[] args) { double speed = 55.0; double totalTime = 4.0; double time = 0.5; while (time <= totalTime) { System.out.println(Distance Traveled in + time + hours is + (speed*time) + .); time += 0.5; } } feet += 3.0;

Page 166

9. Using the approximate Celsius conversion formula provided in Exercise 8, write a Java program that produces a table of Fahrenheit temperatures, exact Celsius equivalent temperatures, approximate Celsius equivalent temperatures, and the difference between the exact and approximate Celsius values. The table should begin at 30 degrees Fahrenheit, use 5 degree Fahrenheit increments, and terminate when the difference between exact and approximate values differs by more than 4 degrees. import java.text.*; public class QuickTest { public static void main(String[] args) { double fahren = 30.0; double exactCelsius = 0; double estimateCelsius = 0; DecimalFormat DecimalFormat(###.00); df = new

exactCelsius = (5.0 / 9.0)*(fahren-32); estimateCelsius = (fahren 30.0) / 2.0; while (Math.abs(exactCelsius estimateCelsius) < 4) { System.out.println(Fahrenheit: df.format(fahren) + Exact Celsius: df.format(exactCelsius) + Estimated Celsius: df.format(estimateCelsius)); fahren += 5; + + +

Page 167

} } }

exactCelsius = (5.0/9.0)*(fahren-32); estimateCelsius = (fahren-30.0)/2;

Exercises 6.3 1. Rewrite QuickTest Program 6.6 to compute the total of eight numbers. import javax.swing.*; public class AddNumbers { public static void main(String[] args) { String s1, outMessage; final int MAXNUMS = 8; int count; double num, total; outMessage = This program will ask you to enter + MAXNUMS + numbers.; JOptionPane.showMessageDialog(null, outMessage, QuickTestProgram 6.6, JOptionPane.INFORMATION_MESSAGE); count = 1; total = 0; while (count <= MAXNUMS) {

Page 168

s1 = JOptionPane.showInputDialog(Enter number + count + :); num = Double.parseDouble(s1); total = total + num; JOptionPane.showMessageDialog(null, The total is now + total, QuickTest Program 6.6, JOptionPane.INFORMATION_MESSAGE); count++; } JOptionPane.showMessageDialog(null, The final total is + total, Program 6.6, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }

3a. Write a Java program to convert Celsius degrees to Fahrenheit. The program should request the starting Celsius value, the number of conversions to be made, and the increment between Celsius values. The display should have appropriate headings and list the Celsius value and the corresponding Fahrenheit value. Use the relationship Fahrenheit = (9.0 / 5.0) * Celsius + 32.0. import javax.swing.*; import java.text.*; public class QuickTest { public static void main(String[] args) {

Page 169

String s1; String message = ""; double fahren, celsius, increment; int numConversions; DecimalFormat df = DecimalFormat("##0.0");

new

s1 = JOptionPane.showInputDialog("Enter starting Celsius value:"); celsius = Double.parseDouble(s1); s1 = JOptionPane.showInputDialog("Enter the number of conversions:"); numConversions = Integer.parseInt(s1); s1 = JOptionPane.showInputDialog( "Enter increment between Celsius values:"); increment = Double.parseDouble(s1); while (numConversions > 0) { fahren = (9.0/5.0)*celsius + 32.0; message += df.format(celsius)+ " degrees Celsius is equal to " + df.format(fahren) + " degrees Fahrenheit.\n"; celsius += increment; numConversions--; } JOptionPane.showMessageDialog(null,message ,"QuickTest", JOptionPane.INFORMATION_MESSAGE);

Page 170

System.exit(0); } } 3b. Run the program written in Exercise 3a on a computer. Verify that your program begins at the correct starting Celsius value and contains the exact number of conversions specified in your input data. Students should run and verify their program. 5. Rewrite QuickTest Program 6.7 to compute the average of 10 numbers. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1, info; String outMessage = ""; final int MAXNUMS = 10; int count; double num, total, average; " info = "This program will ask you to enter

+ MAXNUMS + " numbers."; JOptionPane.showMessageDialog(null, info, "QuickTest Program 6.7", JOptionPane.INFORMATION_MESSAGE); count = 1;

Page 171

total = 0; while (count <= MAXNUMS) { s1 = JOptionPane.showInputDialog("Enter number " + count + ":"); num = Double.parseDouble(s1); total = total + num; outMessage = outMessage + num + " "; count++; } average = total / MAXNUMS; JOptionPane.showMessageDialog(null, "The average of " + outMessage + "\nis " + average, "QuickTest Program 6.7", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }

7. By mistake, a programmer put the statement average = total / count; within the while loop immediately after the statement total = total + num; in QuickTest Program 6.7. Thus, the while loop becomes: while (count <= MAXNUMS) { s1 = JOptionPane.showInputDialog(Enter number + count + :); num = Double.parseDouble(s1);

Page 172

total = total + num; average = total / count; count++; } Will the program yield the correct result with this while loop? From a programming perspective, which while loop is better? Why? This code will not yield the correct result as the total is being divided by a different number at each iteration instead of being divided by MAXNUMS. The correct while loop is obviously better. 9a. An arithmetic series is defined by a + (a + d) + (a + 2d) + (a + 3d) + + (a + (n-1)d) where a is the first term, d is the common difference, and n is the number of terms to be added. With this information, write a Java program that uses a while loop both to display each term and to determine the sum of the arithmetic series having a = 1, d = 3, and n = 100. Make sure that your program displays the value it has calculated. public class QuickTest { public static void main(String[] args) { int a = 1; int d = 3; int n = 100; int total = 0; int count = 0; while (count < n) {

Page 173

total += (a+count*d); System.out.println(Term number + (i+1) is + (a+count*d)); count++; } System.out.println("The arithmetic series is: " + total); } } total of the

9b. Modify the program written for Exercise 9a to permit the user to enter the starting number, common difference, and number of terms to be added. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1; int a; int d; int n; int total = 0; int count = 0; s1 = JOptionPane.showInputDialog("Enter the starting number:"); a = Integer.parseInt(s1); s1 = JOptionPane.showInputDialog("Enter the common difference:"); d = Integer.parseInt(s1);

Page 174

s1 = JOptionPane.showInputDialog("Enter the number of terms to add:"); n = Integer.parseInt(s1); while (count < n) { total += (a + count*d); System.out.println(Term number + (i+1) is + (a+count*d)); count++; } System.out.println("The arithmetic series is: " + total); } } Exercises 6.4 1. Determine the output of the following methods: a. public static void main(String[] args) { int i; for (i = 0; i <= 20; i = i + 4) System.out.print(i + ); } 0 4 8 12 16 20 total of the

Page 175

b. public static void main(String[] args) { int i; for (i = 1; i < 21; i = i + 3) System.out.print(i + ); } 1 4 7 10 13 15 18 c. public static void main(String[] args) { int i; for (i = 20; i >=0; i = i 4) System.out.print(i + ); } 20 16 12 8 4 0 3. Modify Program 6-10 to produce a table of numbers from 10 to 1, instead of 1 to 10 as it currently does. import java.text.*; public class ForTable { public static void main(String[] args) {

Page 176

int num; DecimalFormat df = new DecimalFormat("0000"); System.out.println("NUMBER CUBE"); System.out.println("---------");

SQUARE ------

for (num = 10; num > 0; num--) { System.out.print(" " + df.format(num)); System.out.print(" " + df.format(num * num)); System.out.println(" " + df.format(num * num * num)); } } } 5. Modify the program written for Exercise 4 to initially request the number of conversions to be displayed. import javax.swing.*; import java.text.*; public class QuickTest { public static void main(String[] args) { String s1; String message = ""; double fahren = 20; double celsius; int count;

Page 177

DecimalFormat DecimalFormat("##0.00");

df

new

s1 = JOptionPane.showInputDialog("Enter the number of conversions:"); count = Integer.parseInt(s1); for (; count > 0; count--) { celsius = (5.0 / 9.0) * (fahren -

32.0);

message += "Fahrenheit: " + fahren + " Celsius: " + df.format(celsius) + "\n"; fahren += 5.0; } JOptionPane.showMessageDialog(null, message, "Problem 5", JOptionPane.INFORMATION_MESSAGE); } } 7. Write and run a Java program that accepts six Fahrenheit temperatures, one at a time, and converts each value entered to its Celsius equivalent before the next value is requested. Use a for loop in your program. The conversion required is Celsius = (5.0 / 9.0) * (Fahrenheit 32.0). import javax.swing.*; import java.text.*; public class QuickTest { System.exit(0);

Page 178

public static void main(String[] args) { String s1; String message = ""; double fahren, celsius; DecimalFormat df = DecimalFormat("##0.00");

new

for (int count = 0; count < 6; count++) { s1 = JOptionPane.showInputDialog("Enter Fahrenheit temperature " + (count+1) + ":"); fahren = Double.parseDouble(s1); celsius = (5.0 / 9.0) * (fahren 32.0); message += df.format(fahren) + " degrees Fahrenheit is equal to " + df.format(celsius) + " degrees Celsius." + "\n"; } JOptionPane.showMessageDialog(null, message, "QuickTest", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } 9. Modify the program written for Exercise 8 to initially request the number of data items that will be entered and converted. import javax.swing.*;

Page 179

import java.text.*; public class QuickTest { public static void main(String[] args) { String s1; String message = ""; double liters, gallons; int count; DecimalFormat df = DecimalFormat("##0.00");

new

s1 = JOptionPane.showInputDialog( "Enter the number of data items to request"); count = Integer.parseInt(s1); for (; count > 0; count--) { s1 = JOptionPane.showInputDialog("Enter the next gallon amount:"); gallons = Double.parseDouble(s1); liters = gallons * 3.785; message += df.format(gallons) + " gallons is equal to " + df.format(liters) + " liters.\n"; } JOptionPane.showMessageDialog(null, message, "QuickTest", JOptionPane.INFORMATION_MESSAGE); System.exit(0);

Page 180

11. Write and run a Java program that calculates and display the amount of money available in a bank account that has an initial deposit of $1000 and earns 8 percent interest a year. Your program should display the amount available at the end of each year for a period of 10 years. Use the relationship that the money available at the end of each year equals the amount of money in the account at the start of the year plus 0.08 times the amount available at the start of the year. import java.text.*; public class QuickTest { public static void main(String[] args) { double amt = 1000.00; double interest = 0.08; DecimalFormat df = DecimalFormat("$,###.00");

new

for (int i = 0; i < 10; i++) { amt += amt*interest; System.out.println("Balance at end of year " + (i+1) + " is " + df.format(amt)); } } } 13. A machine purchased for $28,000 is depreciated at a rate of $4000 a year for seven years. Using a for loop, write and run a Java

Page 181

program that computes and displays a depreciation table for seven years. import java.text.*; public class QuickTest { public static void main(String[] args) { double machineValue = 28000.00; double depRate = 4000.00; DecimalFormat df = DecimalFormat("$00000");

new

System.out.println("Depreciation Schedule"); System.out.println("---------------------" ); System.out.println(""); System.out.println("Year Depreciation Rate Value Total Depreciation"); System.out.println("-------------------- ----- ------------------"); for (int i = 0; i < 7; i++) { machineValue -= depRate; System.out.print(" " + (i+1) + " System.out.print(depRate + " "); System.out.print(df.format(machineValue "); System.out.println(df.format(depRate*(i

"); ) + "

+1))+""); } }

Page 182

} 15. Four experiments are performed, each consisting of six tests with the following results. Write a Java program using a nested loop to compute and display the average of the test results for each experiment. Experiment 1 results: 23.2 31.5 16.9 27.5 25.4 28.6 Experiment 2 results: 34.8 45.2 27.9 36.8 33.4 39.4 Experiment 3 results: 19.4 16.8 10.2 20.8 18.9 13.4 Experiment 4 results: 36.9 39.5 49.2 45.1 42.7 50.6 import javax.swing.*; import java.text.*; public class QuickTest { public static void main(String[] args) { String s1; String message = ; double total, average; DecimalFormat df = DecimalFormat(###.00);

new

for (int i = 0; i < 4; i++) { total = 0; for (int j = 0; j < 6; j++) { s1 = JOptionPane.showInputDialog( Enter Result number + (j+1) + for experiment number + (i+1));

Page 183

total += Double.parseDouble(s1); } message += Experiment Number + (i+1) + averaged to: + df.format(total/6) + \n; } JOptionPane.showMessageDialog(null, message, QuickTest, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } 17a. A bowling team consists of five players. Each player bowls three games. Write a Java program that uses a nested loop to enter each players individual scores and then computes and displays the average score for each bowler. Assume that each bowler has the following scores: Bowler 1: 286 252 265 Bowler 2: 212 186 215 Bowler 3: 252 232 216 Bowler 4: 192 201 235 Bowler 5: 186 236 272 import javax.swing.*; import java.text.*; public class QuickTest { public static void main(String[] args) {

Page 184

String s1; String message = ; double total, average; DecimalFormat DecimalFormat(###.00);

df

new

for (int i = 0; i < 5; i++) { total = 0; for (int j = 0; j < 3; j++) { s1 = JOptionPane.showInputDialog( Enter score number + (j+1) + for bowler number + (i+1)); total += Double.parseDouble(s1); } message += Bowler Number + (i+1) + averaged: + df.format(total/3) + \n; } JOptionPane.showMessageDialog(null, message, QuickTest, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } 17b. Modify the program written in Exercise 17a to calculate and display the average team score.

Page 185

import javax.swing.*; import java.text.*; public class QuickTest { public static void main(String[] args) { String s1, message; double total, average; DecimalFormat df = DecimalFormat(###.00);

new

total = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { s1 = JOptionPane.showInputDialog( Enter score number + (j+1) + for bowler number + (i+1)); total += Double.parseDouble(s1); } } message (total / (5*3)); = Average Team Score: +

JOptionPane.showMessageDialog(null, message, QuickTest, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }

Page 186

19. Write a Java program that calculates and displays the yearly amount available if $1,000 is invested in a bank account for 10 years. Your program should display the amounts available for interest rates from 6 percent to 12 percents inclusively, at 1 percent increments. Use a nested loop, with the outer loop having a fixed count of 7 and the inner loop having a fixed count of 10. The first iteration of the outer loop should use an interest rate of 6 percent and display the amount of money available at the end of the first 10 years. In each subsequent pass through the outer loop, the interest rate should be increased by 1 percent. Use the relationship that the money available at the end of each year equals the amount of money in the account at the start of the year plus the interest rate times the amount available at the start of the year. import java.text.*; public class QuickTest { public static void main(String[] args) { double balance; DecimalFormat df = DecimalFormat($,###.00); for (int i = 6; i < 13; i ++) { balance = 1000.00; for (int j = 0; j < 10; j++) balance *= (1.0+(i)/100.0); System.out.println(Balance for Interest Rate + i + %: + df.format(balance)); } }

new

Page 187

Exercises 6.5 1a. Using a do-while statement, write a Java program to accept a grade. The program should request a grade continuously as long as an invalid grade is entered. An invalid grade is any grade less than 0 or greater than 100. After a valid grade has been entered, your program should display the value of that grade. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1; double grade; do { s1 = JOptionPane.showInputDialog(Enter a grade); grade = Double.parseDouble(s1); } while (grade < 0 || grade > 100); JOptionPane.showMessageDialog(null, The grade entered was: + grade , QuickTest, JOptionPane.INFORMATION_MESSAGE); } System.exit(0);

Page 188

} 1b. Modify the program written for Exercise 1a so that the user is alerted when an invalid grade has been entered. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1; double grade; do { s1 = JOptionPane.showInputDialog(Enter a grade); grade = Double.parseDouble(s1); if (grade < 0 || grade > 100) JOptionPane.showMessageDialog(null, Invalid Grade Entered, ERROR, JOptionPane.ERROR_MESSAGE); } while (grade < 0 || grade > 100); JOptionPane.showMessageDialog(null, The grade entered was: + grade , QuickTest, JOptionPane.INFORMATION_MESSAGE); } System.exit(0);

Page 189

} 1c. Modify the program written for Exercise 1b so that it allows the user to exit the program by entering the number 999. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1; double grade; do { s1 = JOptionPane.showInputDialog(Enter a grade (999 to exit)); grade = Double.parseDouble(s1); if (grade == 999) System.exit(0); if (grade < 0 || grade > 100) JOptionPane.showMessageDialog(null, Invalid Grade Entered, ERROR, JOptionPane.ERROR_MESSAGE); } while (grade < 0 || grade > 100); JOptionPane.showMessageDialog(null, The grade entered was: + grade

Page 190

, JOptionPane.INFORMATION_MESSAGE); } } System.exit(0);

QuickTest,

1d. Modify the program written for Exercise 1b so that it automatically terminates after five invalid grades are entered. import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1; double grade; int count = 0; do { s1 = JOptionPane.showInputDialog(Enter a grade); grade = Double.parseDouble(s1); if (grade < 0 || grade > 100) { JOptionPane.showMessageDialog(null, Invalid Grade Entered, ERROR, JOptionPane.ERROR_MESSAGE); count++; }

Page 191

if (count == 5) System.exit(0); } while (grade < 0 || grade > 100); JOptionPane.showMessageDialog(null, The grade entered was: + grade , QuickTest, JOptionPane.INFORMATION_MESSAGE); } } 3a. Write a Java program to reverse the digits of a positive integer number. For example, if the numbers 8735 is entered, the number displayed should be 5378. (Hint: Use a do-while statement that continuously strips off and displays the units digits of a number. If the variable num initially contains the number entered, the units digit is obtained as (num % 10). After a units digit is displayed, dividing the number by 10 sets up the number for the next iteration. Thus, (8735 % 10) is 5 and (8735 / 10) is 873. The do-while statement should continue as long as the remaining number is not zero.) import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1, message; int number; s1 = JOptionPane.showInputDialog(Enter a positive integer:); System.exit(0);

Page 192

number = Integer.parseInt(s1); message = ; do { }

message += (number % 10); number = number / 10; while (number != 0);

JOptionPane.showMessageDialog(null, message, QuickTest, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } 3b. Run the program written in Exercise 3a on a computer and verify the program using appropriate test data. Students should enter and verify the program. Exercises 6.6 1. The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13, such that the first two terms are 0 and 1, and each term thereafter is defined recursively as the sum of the two preceding terms; that is, Fib(n) = Fib(n-1) + Fib(n-2). a. Write a recursive method that returns the nth number in a Fibonacci sequence when n is passed to the method as an

Page 193

argument. For example, when n = 8, the method returns the 8 th number in the sequence, which is 13. public static int fibonacci(int n) { if (n==1) return 0; if (n==2) return 1; else return fibonacci(n-1) + fibonacci(n2); }

b. Write a Java program that calculates the nth number in a Fibonacci sequence using a for loop., where n is interactively entered into the program by the user. For example, if n = 6, the program should display the value 5. public static int fibonacci(int n) { int result = 0; int prevResult = 1; int prevPrevResult = 0; if (n == 1) return 0; if (n == 2) return 1; for (int i = 3; i<=n; i++) { result = prevResult prevPrevResult;

Page 194

prevPrevResult = prevResult; prevResult = result;

return result; } 3a. The value of x^n can be defined recursively as: x^0 = 1; x^n = x * x^(n-1) Write a recursive method that computed and returns the value of x^n. public static double power(double x, int n) { if (n == 0) return 1; else return x*power(x,n-1); } 3b. Rewrite the method written for Exercise 3a so that it uses a repetitive algorithm for calculating the value of x^n. public static double power(double x, int n) { double result = 1; for (int i = 1; i <= n; i++) result = result*x; return result;

Page 195

} 5a. Write a method that recursively determines the value of the nth term of an arithmetic sequence defined by the terms: a, a + d, a + 2d, a + 3d, a + (n-1)d The argument to the method should be the first term, a, the common difference, d, and the value of n. public static double getTerm(double a, double d, int n) { if (n == 1) return a; else return d + getTerm(a,d,n-1);

5b. Modify the method written for Exercise 5a so that the sum of the first n terms of the sequence is returned (Note: this is a more general form of Exercise 2). public static double getSum(double a, double d, int n) { if (n == 1) return a; else return a + (n-1)*d + getSum(a,d,n-1); }

Page 196

Exercises 6.7 1. Describe the difference between a class and state diagram. A class diagram is a static diagram while a state diagram is dynamic in that it depicts how an objects attributes change over time. 3. Construct a state diagram for a game of checkers. A state diagram could be constructed using the following states and events. States: Initial Board Setup Board in Playing State Board in Winning State Events: Player one moves a number of times. Player two moves a number of times. One of the player captures the last piece. 5. Construct a state diagram for shifting a cars transmission. Assume that there are six gears; Park, Reverse, Neutral, Drive, Drive-1, Drive-2. A state diagram can be constructed using the following states and events: States: Park Reverse

Page 197

Neutral Drive Drive-1 Drive-2

Events: Shift to Park Shift to Reverse Shift to Neutral Shift to Drive Shift to Drive-1 Shift to Drive-2 Note that the events and states should be chained together in a linear fashion (i.e. One cannot change from Drive to Park without first shifting through Reverse). 7. Draw a state diagram for a traffic light that can be in one of three states: green, yellow, or red. A state diagram can be constructed using the following states and events: States: Red Green Yellow Events: Change from Red to Green Change from Green to Yellow Change from Yellow to Red

Page 198

9. List the sequence of events that occur in the using an ATM machine. The sequence should start when the customer inserts their card and ends when the card is returned. From this list complete the sequence diagram shown in 6-25. One possible example is listed below for an ATM withdrawal. Events: Customer inserts card Customer enters PIN number Customer selects withdraw Customer enters amount of money to withdraw Customer retrieves money Customer retrieves receipt Customer retrieves card Exercises 6.8 1. Enter and execute Program 6.17 on your computer. Students should enter and execute the specified program. 3. Enter and execute Program 6.19 on your computer. Students should enter and execute the specified program. 5. Modify the main() method in program 6.19 to use a while loop that calls the Elevators request method with a random number between 1 and 15. If the random number is the same as the elevators current floor, generate another request. The while loop should terminate after 5 valid requests have been made and satisfied by movement of the elevator.

Page 199

public class TestElevator { public static void main(String[] args) { Elevator a = new Elevator(1); int count = 0; int currentFloor = 1; int nextFloor = 1; a.setMaxFloor(15); while (count < 5) { nextFloor = 1 (Math.random()*15); if (nextFloor != currentFloor) { a.request(nextFloor); currentFloor = nextFloor; count++; } } } }

(int)

7. Construct a class named Light that simulates a traffic light. The color attribute of the class should change from Green to Yellow to Red and then back to Green by the class change() method. When a new Light object is created its initial color should be Red. public class Light { String color; public Light() { color = red;

Page 200

} public String getColor() { return color; } public void change() { if (color.equals(red)) color = green; else if (color.equals(green)) color = yellow; else color = red; } }

Page 201

III. Sample Test Questions Chapter 6 1) A while loop is also called a(n) a) post-test loop b) iterative loop c) pretest loop d) conditional Answer: (C) 2) A do-while loop is also called a(n) a) post-test loop b) iterative loop c) pre-test loop d) conditional Answer: (A) 3) A for loop is also called a(n) a) post-test loop b) iterative loop c) pre-test loop d) conditional Answer: (B) 4) What is the output from the following loop:

Page 202

i = 10; while ( i <= 10 ) System.out.println ( i ); a) no output b) the number 10 will be output infinitely c) the nubmer 10 will be output exactly one time d) the numbers 0 through 10 will be output Answer: (B) 5) What is the output from the following loop? i = 10; while ( i >= 0 ) System.out.println ( i ); i--; a) no output b) the number 10 will be output infinitely c) the number 10 will be output exactly one time d) the numbers 0 through 10 will be output Answer: (B) 6) Which while loop outputs the even numbers from 0 through 100? a) i = 0; while ( i < 100 ) { System.out.println ( i ); i += 2;

Page 203

} b) i = 100; while ( i >= 0 ) { System.out.println ( i ); i -= 2; } c) i = 0; while ( i <= 100 ) { System.out.println ( i ); i ++; } d) i = 0; while ( i <= 100 ) { System.out.println ( i ); i += 2; } Answer: (D) 7) When placed in a while loop, the continue statement a) causes the loop to terminate b) causes the program to terminate c) skips to the next iteration of the loop d) does nothing in a while loop Answer: (C) 8) When placed in a while loop, the break statement

Page 204

a) causes the loop to terminate b) causes the program to terminate c) skips to the next iteration of the loop d) does nothing in a while loop Answer: (A) 9) The general form of a for loop contains which three components? a) expression; increment; decrement b) initializing list; expression; altering list c) altering list; expression; initializing list d) start value; end value; increment value Answer: (B) 10) A for loop to output the odd integers from 100 to 0 is a) for ( i = 99; i > 0; i -2) System.out.print ( i ); b) for ( i = 100; i > 0; i -= 2) System.out.println ( i ); c) for ( i = 1; i < 100; i -= 2) System.out.println ( i ); d) for ( i = 99; i > 0; i -= 2) System.out.println ( i ); Answer: (D)

Page 205

11) The for loop: for ( ; count < 20 ; ) a) is syntactically incorrect b) is an infinite loop c) is equivalent to a while loop that continues as long as count is less than 20 d) is equivalent to a do-while loop that continues as long as count is less than Answer: (C) 12) What is the output? total = 50; for ( i = 1; i<= 10; i++) total -= i; System.out.println ( total ); a) 40 b) No output - this is an infinite loop c) 50 d) -5 Answer: (D) 13) What is the output? k = 0; for ( i = 1; i <= 30; i++ ) for ( j = 1; j <= 20; j++ ) if ( j%3 == 0 ) k++;

Page 206

System.out.println ( k ); a) 600 b) 180 c) 6 d) 200 Answer: (B)

14) What is the output? for ( x = 0; x <= -1; x++ ) System.out.println ( x ); a) there is no output b) infinite loop c) the positive integers starting from 0 d) the negative integers starting from 0 Answer: (A) 15) Which loop computes n factorial, defined as follows: N! = n * n-1 * n-2 * ...* 2 * 1 a) nFactorial = n; for ( i = n; i > 0; i--) nFactorial *= i; b) nFactorial = 1; for ( i = 1; i > n; i--) nFactorial *= i;

Page 207

c) nFactorial = 1; for ( i = n; i > 0; i--) nFactorial *= i; d) nFactorial = 0; for ( i = n; i > 0; i--) nFactorial *= i; Answer: (C)

Page 208

I. OVERVIEW: Chapter 7 Strings and Characters Each computer language has its own method of handling strings of characters. Some languages, such as Java, have an extremely rich set of string manipulation methods and capabilities. Other languages, such as FORTRAN, which are predominantly used for numerical calculations, added string handling capabilities with later versions of the compiler. Languages such as LISP, which are targeted for list handling applications, provide an exceptional string processing capability. In this chapter, we learn how strings are created and manipulated using Java's object-oriented approach. Thus, this chapter can also be used as an introduction to the general topic of object-oriented programming, which is formally presented in the next chapter, and more precisely to the construction and manipulation of objects using a predefined class. Specifically, a string in Java is an object that is created from either the String or StringBuffer class. Each class has its own set of methods for both initially creating and manipulating strings. The main difference between these two classes is that a string created from the String class cannot be changed; if a modification is desired, such as adding or changing characters in the original string, a new String object must be created. This is not the case for a string created from the StringBuffer class. Strings created from this class can be altered, either by adding, changing, or deleting characters within the string, and the string will dynamically expand or contract as necessary. In general, the String class is more commonly used for constructing strings for input and output purposes, such as for prompts and displayed messages. In addition, because of the provided capabilities, this class is used when strings need to be compared, searched, or individual characters in a string need to be examined or extracted as a substring. The StringBuffer class is used in more advanced situations when characters within a string need to be replaced, inserted, or deleted on a relatively regular basis.

Page 209

7.1 The String Class 7.2 String Processing 7.3 The StringBuffer Class 7.4 Program Design and Development: Program Performance Measures and Object-Oriented Technology (OOT) 7.5 Common Programming Errors 7.6 Chapter Summary

Potential Problem areas: Students may be confused by the various String classes and the associated assortment of methods.

Page 210

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 7.2 1. Enter and execute QuickTest Program 7-2 on your computer. Students should enter and execute the specified program. 3. Determine the value of the text.charAt(0), text.charAt(3), and text.charAt(10), assuming that text is the following string of characters: a. now is the time n <space> <space> b. rocky raccoon welcomes you rko c. Happy Holidays Hpd d. The good ship T <space> h 5. Enter and execute QuickTest Program 7.3 on your computer Students should enter and execute the specified program. 7. Modify QuickTest Program 7.3 to display the number of vowels in a user entered string. import java.io.*; public class CountVowels {

Page 211

public static void main (String[] args) throws java.io.IOException { String str; int i, numChars; int vowelCount = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print(Enter the string to count vowels on: ); str = br.readLine(); numChars = str.length(); for (i = 0; i < numChars; i++) { switch(str.charAt(i)) // here is where a character is retrieved { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': vowelCount++; } } System.out.println("The string: " + str);

Page 212

System.out.println("has " + vowelCount + " vowels."); } } 9. Write and execute a Java program that retrieves each character in a string, converts the character to uppercase form, and displays the character. public class QuickTest { public static void main(String[] args) { String str = "test string"; char character; for (int i = 0; i < str.length(); i++) { character = str.charAt(i); character Character.toUpperCase(character); System.out.print(character); } System.out.println(""); } }

11. Assuming that the String variable str references the string 1234, write two different statements that can be used to convert this string into a long number that is stored in the long variable named longnum. longnum = Long.parseLong(str); longnum = Long.valueOf(str).longValue();

Page 213

13. Write and execute a Java program that counts the number of words in a string. A word is encountered whenever a transition from a blank space to a nonblank character is encountered. Assume that the string contains only words separated by blank spaces. public class QuickTest { public static void main(String[] args) { String testString = "Test string"; int numWords = 0; i++) for (int i = 0; i < testString.length()-1; {

if (testString.charAt(i) != ' ' && testString.charAt(i+1) == ' ') numWords++; } if (testString.charAt(testString.length()1) != ' ') numWords++; System.out.println("The testString + "\nhas " + numWords + " words."); } } string: " +

15a. Write a general-purpose method named countlets() that returns the number of letters in a string passed as an argument. Digits,

Page 214

spaces, punctuation, tabs, and newline characters should not be included in the returned count. public static int countlets(String s1) { int numLetters = 0; for (int i = 0; i < s1.length(); i ++) if (Character.isLetter(s1.charAt(i))) numLetters++; return numLetters; } 15b. Include the countlets() method written for Exercise 15a in an executable Java program and use the program to test the method. public class QuickTest { public static int countlets(String s1) { int numLetters = 0; for (int i = 0; i < s1.length(); i ++) if (Char.isLetter(s1.charAt(i)) numLetters++; } return numLetters;

public static void main(String[] args) { int numLetters = countlets(count this);

Page 215

System.out.println(The number of letters in the test phrase is: + numLetters); } }

Exercises 7.3 1. Enter and execute QuickTest Program 7.6 on your computer Students should enter and execute the specified program. 3. Write a program that accepts a string of characters from a terminal and displays the hexadecimal equivalent of each character. import java.io.*; public class QuickTest { public static void main(String[] args) throws IOException { StringBuffer sb; int num; BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); char character; String outString = ""; System.out.print("Enter a string convert: "); sb = new StringBuffer(br.readLine()); to

Page 216

for (int i = 0; i < sb.length(); i++) { character = sb.charAt(i); while (character > 0) { num = character % 16; if (num < 10) outString = num + outString; else outString = (char)('a'+num-10) + outString; character = (char)(character / 16); } outString = "0x" + outString; System.out.println(outString); outString = ""; } } 5. Write a method that reverses the characters in a string. public static String reverseString(String s1) { StringBuffer sb = new StringBuffer(s1); sb.reverse(); return sb.toString(); } }

Page 217

7a. Write a general-purpose Java method named toUpper() that converts all lowercase letters in a string into uppercase letters. The original string should be passed as an argument to the method, and the uppercase equivalent string should be returned. public static String toUpper(String s1) { StringBuffer temp = new StringBuffer(s1); for (int i = 0; i < temp.length(); i++) { if (temp.charAt(i) > a && temp.charAt(i) < z) temp.setCharAt(i,(char)(temp.charAt(i) - ('a'-'A'))); } return temp.toString(); } 7b. Add a data input check to the method written in Exercise 7a to verify that a valid lowercase letter is passed to the method. A character in Unicode is lowercase if it is greater than or equal to a and less than or equal to z. If the character is not a valid lowercase letter, have the method toUpper() return the passed character unaltered. See the program in 7a. Any character that is not a lowercase letter is left alone in the conversion process. 9. Write a Java program that counts the number of words in a StringBuffer. A word occurs whenever a transition from a blank space to a nonblank character is encountered. Assume the string contains only words separated by blank spaces.

Page 218

public class QuickTest { public static int countWords(StringBuffer in) { int count = 0; for (int i = 0; i < in.length()-1; i++) { if ( (in.charAt(i) != ' ' in.charAt(i+1) == ' ')) count++; } if ( in.charAt(in.length()-1) != ' ') count++; return count; } 11. Write a general-purpose method named trimrear() that deletes all trailing blanks from a StringBuffer and returns a String. public static String trimRear(String s1) { StringBuffer temp = new StringBuffer(s1); while(temp.charAt(temp.length()-1) == ' ') temp.deleteCharAt(temp.length()-1); return temp.toString(); } 13. Write a general-purpose method named extract() that accepts a string, referenced as s1, and two integer numbers, n1 and n2, as

&&

Page 219

arguments. The method should extract n2 characters from the string referenced by s1, starting at position n1, and return the extracted characters as a string. Fro example, if string s2 contains the characters 05/18/95 D169254 Rotech Systems, the method call extract(s1,18,6) should return the string Rotech in s2. public static String extract(String s1, int n1, int n2) { StringBuffer temp = new StringBuffer(s1); return temp.substring(n1-1, n1+n2-1); } Exercises 7.4 1. Define the terms: a. Clarity From a programmers viewpoint, clarity means that another programmer can read and understand your code and that you can read and understand your own code months after you have written it. From a users viewpoint it means that the program clearly identifies what inputs are required and what outputs are being produced. b. Correct Correctness is the minimum property that any program should have. A correct program is a program that functions correctly. c. Efficiency Efficiency means that a program or function produces its results in the most time efficient manner. d. Robustness

Page 220

Robustness means that a program or function will not fail even if it receives improper data. e. Extensibility Extensibility means that a program can easily be modified and extended to handle cases and situations that the original designers did not expect. f. Reusability Reusability means that existing code can be reused, both within an existing project and for new projects. g. Programming-in-the-large Programmable-in-the-Large means that large, complex programs can be written using teams of programmers. 3a. In reviewing how you respond to assignments, have you ever done an assignment just to hand it in on time rather than doing the assignment right? Answers will vary. 3b. In general, do you do assignments to just get then in on time or do you spend the time on them to do them right? What does right mean? Do you think your answer to this question is the same answer that an amateur or professional programmer would give when referring to programming projects? Answers will vary. 3c. Have you ever been so concerned with doing an assignment perfectly that you either fail to start it or fail to complete it? Do you

Page 221

think your answer to this question is the same answer that an amateur or professional programmer would give when referring to programming projects. Answers will vary.

Page 222

III. Sample Test Questions Chapter 7 1) A string literal is a) rarely used in Java b) a single character surrounded by single quotes c) a collection of characters surrounded by double quotes d) a collection of characters surrounded by single quotes Answer: (C) 2) A string variable a) stores a string object b) provides a reference to a string object c) stores a string literal d) can hold up to 80 characters Answer: (B) 3) The read() method is generally used to input a a) single character from the keyboard b) string from the keyboard c) single character from a file d) string from a file Answer: (A) 4) The read() method returns a(n)

Page 223

a) String object b) StringBuffer object c) character d) integer Answer: (D)

5) The result of calling s1.compareTo(s2) will be negative if a) s1 is shorter than s2 b) s1 is longer than s2 c) s1 is greater than s2 d) s1 is less than s2 Answer: (D) 6) After executing the statement s2 = s1.toLowerCase(); a) Character s2 stores the lowercase version of character s1 b) Character s2 is a reference to the lowercase version of character s1 c) String s2 stores the lowercase version of String s1 d) String s2 is a reference to the lowercase version of String s1 Answer: (C) 7) The best way to compare the contents of two strings

Page 224

is to use the a) use the == operator b) use the > operator c) use the < operator d) none of the above Answer: (D) 8) The easiest way to make a deep copy of two strings is to a) use the assignment operator, = b) use the == operator c) use the new operator d) use the copy() function Answer: (C) 9) Which method permits you to retrieve individual characters in a string? a) getChar() b) toString() c) copyValueOf() d) charAt() Answer: (D) 10) Which method permits you to convert from a float to a string type?

Page 225

a) valueOf() b) convert() c) charToFloat() d) convertToFloat() Answer: (A) 11) What is returned by the following lines of code? String s1 = new String(test); String s2 = new String(test); if (s1 == s2) return true; else return false a) true b) false c) program will crash at the == operator d) These lines contain a syntax error and will not compile Answer: (B) 12) The following line of code requires dvalue to be of the data type dvalue = Double.valueOf(str).doubleValue() a) double b) String c) Double d) char[] Answer: a

Page 226

13) The following line of code requires dvalue to be of the data type dvalue = Double.parseDouble(str); a) double b) Double c) String d) charp[] Answer: (A) 14) The difference between a String and a StringBuffer is a) a String contains character data while a StringBuffer does not b) a String can be initialized dynamically while a StringBuffer is not c) a String will not let you extract individual characters while a StringBuffer will d) a String is immutable while a StringBuffer is not Answer: (D) 15) Robustness refers to the ability of software to a) operate on machines that the programmer didnt initially intend b) continue to operate effectively even in the presence of hardware failures c) continue to function even though a user has entered invalid data d) continue to function even in the case of memory errors Answer: (C)

Page 227

I. OVERVIEW: Chapter 8 Arrays The primitive data type variables that we have used so far have all had one common characteristic: Each variable can only be used to store a single value at a time. For example, although the variables key, count, and grade declared in the statements char key; int count; double grade; are of different data types, each variable can only store one value of the declared built-in data type These types of variables are called scalar variables. A scalar variable is a variable whose value is a single built-in data type value, such as a single integer, character, or double. Frequently we may have a set of values, all of the same data type, that forms a logical group. For example, the data below illustrates three groups of items. The first group is a list of five integer grades, the second is a list of four character codes, and the last is a list of six floating-point prices. Grades Codes Prices 98 x 10.96 87 a 6.43 92 m 2.58 79 n .86 85 12.27 6.39 In Java, lists are created and processed using a group of classes referred to as Collection classes. This name is derived from the fact that the data consists of a number of times that can be processed collectively, as a group. One such collection is an array type, which is created from the Array class. Unlike other collection classes that are described in this and

Page 228

the next chapter, an array is the only collection class that can directly hold Java primitive types and is built into the Java language. A simple list containing individual items of the same data type is called a one-dimensional array. This chapter describes how onedimensional arrays are declared, initialized, stored, and used. In addition, it explores the use of one-dimensional arrays with example programs and present the procedures for declaring and using multidimensional arrays. Additionally, the Arrays class (note the addition of the s) is used to provide a number of useful methods for sorting and searching arrays. Finally, because arrays are reference data types, they are also declared differently from the built-in data types used. 8.1 One-Dimensional Arrays 8.2 Array Initialization 8.3 The Arrays Class: Searching and Sorting 8.4 Arrays as Arguments 8.5 The Collection Framework: ArrayLists 8.6 Two-Dimensional Arrays 8.7 Common Programming Errors 8.8 Chapter Summary 8.9 Chapters Supplement: Searching and Sorting Algorithms Potential Problem areas: Array indexing is confusing the first time it is encountered. Deep and shallow copies are confusing. The Collection Framework will no doubt baffle many students. Multidimensional arrays are tricky.

Page 229

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 8.1 1. Write array declarations and allocation statements for the following: 1a. a list of 100 integer grades int grades[] = new int[100]; 1b. a list of 50 floating-point temperatures float temperatures[] = new float[50]; 1c. a list of 30 characters, each representing a code char codes[] = new char[30]; 1d. a list of 100 integer years int years[] = new int[100]; 1e. a list of 32 floating-point velocities float velocities[] = new float[32]; 1f. a list of 1000 floating-point distances float distances[] = new float[1000]; 1g. a list of 6 integer code numbers int codes[] = new int[6]; 3a. Using a showInputDialog() method and a suitable parse method, write statements that can be used to enter values into the first, third, and seventh elements of each of the arrays declared in Exercises 2a through 2f.

Page 230

grade[0] = Integer.parseInteger(showInputDialog(Enter grade one)); prices[0] = Double.parseDouble(showInputDialog(Enter price one)); amps[0] = Double.parseDouble(showInputDialog(Enter amp one)); dist[0] = Integer.parseInt(showInputDialog(Enter distance one)); In order to enter values into the third and seventh elements in each of the arrays above, merely change the index to two and six respectively. Remember that the first element in an array starts at index zero. b. Write a for loop that can be used to enter values for the complete array declared in Exercise 2a. for (int i = 0; i < 20; i ++) { grade[i] = Integer.parseInt(showInputDialog(Enter grade + i)); }

Page 231

5. List the elements that will be displayed by the following sections of code: 5a. for (m = 1; m <= 5; m++) System.out.print(a[m] + " ");

a[1] a[2] a[3] a[5] a[5] 5b. for (k = 1; k <= 5; k = k + 2) System.out.print(a[k] + " ");

a[1] a[3] a[5] 5c. for (j = 3; j <= 10; j++) System.out.print(b[j] + " ");

b[3] b[4] b[5] b[6] b[7] b[8] b[9] b[10] 5d. for (k = 3; k <= 12; k = k + 3) System.out.print(b[k] + " ");

b[3] b[6] b[9] b[12] 5e. for (i = 2; i < 11; i = i + 2) System.out.print(c[i] + " ");

c[2] c[4] c[6] c[8] c[10] 7. Write a Java program to input eight integer numbers into an array named grade. As each number is input, add the number to a total. After all numbers are input, display the numbers and their average.

Page 232

public class QuickTest { public static void main(String[] args) { int grade[] = new int[8]; int total = 0; String message = ; for (int i = 0; i < 8; i++) { grade[i] = Integer.parseInt(showInputDialog(Enter grade + i); message += Number + i + : + grade[i] + \n; total += grade[i]; } 8)); message += Average: + ((double)(total /

showMessageDialog(null, message, Summary, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } 9a. Write a Java program to input the following integer number into an array named grades: 89, 95, 72, 83, 99, 54, 86, 75, 92, 73, 79, 75, 82, 73. As each number is input, add the numbers to a total. After all numbers are input and the total is obtained, calculate the average of the numbers and use the average to determine the deviation of each value from the average. Store each deviation in an array named deviation. Each deviation is obtained as the element value

Page 233

less the average of all the data. Have your program display each deviation alongside its corresponding element from the grades array. import javax.swing.*; import java.io.*; public class QuickTest { public static void main(String[] args) { final int NUM_GRADES = 14; DecimalFormat decimal DecimalFormat(##0.00); int grade[] = new int[NUM_GRADES]; double deviations[] double[NUM_GRADES]; int total = 0; double avg; String message = ; for (int i = 0; i < NUM_GRADES; i++) { grade[i] Integer.parseInt(showInputDialog(Enter grade + i); total += grade[i]; } avg = total/ 14; for (int i = 0; i < NUM_GRADES; i++) = new

new

Page 234

{ deviations[i] = grade[i] avg; message += Deviation for grade + i + : + decimal.format(deviations[i]) + \n; } showMessageDialog(null, message, Summary, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }

Page 235

9b. Calculate the variance of the data used in Exercise 9a. The variance is obtained by squaring each individual deviation and dividing the sum of the squared deviations by the number of deviations. import javax.swing.*; import java.io.*; public class QuickTest { public static void main(String[] args) { final int NUM_GRADES = 14; DecimalFormat decimal DecimalFormat(##0.00); int grade[] = new int[NUM_GRADES]; double deviations[] double[NUM_GRADES]; double squareTotal = 0; double avg; String message = ; for (int i = 0; i < NUM_GRADES; i++) { grade[i] Integer.parseInt(showInputDialog(Enter grade + i); total += grade[i]; } avg = total/ 14; = new

new

Page 236

for (int i = 0; i < NUM_GRADES; i++) { deviations[i] = grade[i] avg; sqrTotal += deviations[i] * deviations[i]; message += Deviation for grade + i + : + decimal.format(deviations[i]) + \n; } variance = sqrTotal / NUM_GRADES; message += Variance: number.format(variance); showMessageDialog(null, Summary, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }

message,

Page 237

11a. Write a program that inputs 10 floating-point numbers into an array named raw. After 10 user-input numbers are entered into the array, your program should cycle through raw 10 times. During each pass through the array, your program should select the lowest value in raw and place the selected value in the next available slot in an array named sorted. Thus, when your program is complete, the sorted array should contain the numbers in raw in sorted order from lowest to highest. (Hint: Make sure to reset the lowest value selected during each pass to a very high number so that it is not selected again. You will need a second for loop within the first for loop to locate the minimum value for each pass.) import javax.swing.*; public class QuickTest { public static void main(String[] args) { float raw[] = new float[10]; float sorted[] = new float[10]; int index; String message = ""; // Get ten user values for (int i = 0; i < 10; i++) { raw[i] = Float.parseFloat(JOptionPane.showInputDialog( "Enter number " + i)); } // Sort the numbers for (int i = 0; i < 10; i++) { index = 0;

Page 238

for (int j = 1; j < 10; j++) { if (raw[j] < raw[index]) { index = j; } } sorted[i] = raw[index]; raw[index] = 1000000; } // Display the result message = "Sorted List\n"; for (int i = 0; i < 10; i++) { message = message += "Element " + i + ": " + sorted[i] + "\n"; } JOptionPane.showMessageDialog(null,message,"Quic k Test", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } 11b. The method in Exercise 11a to sort the values in the array is very inefficient. Can you determine why? What might be a better method of sorting the numbers in an array?

Page 239

There are many different ways of sorting an array. Many of these algorithms are very complex and optimized for efficiency. This method is inefficient because it requires 10*10 passes to sort the array (it looks at values already sorted). One better method would be to find the smallest value in the array, and swap the first value in the array with this value. Then, find the smallest number in the remaining portion of the array and swap the second number with this value, etc. This technique would require 10 + 9 + 8 + 7 + 6 + 5 +4 +3 +2 +1 = 55 passes which is much less than 10 * 10 = 100 passes. 13. QuickTest Program 8-4 uses a single statement both to declare and allocate space for the grade array. Many programmers prefer to place all declarations at the top of a method to make them immediately visible to anyone reading the program. To accomplish this, modify QuickTest Program 8-4 by placing the declaration statement int grade[]; with the other declarations at the top of the program and change the statement int grade[] = new int[numgrades]; so that it only allocates space for the grade array. Compile and execute your program to ensure that it operates correctly. import javax.swing.*; public class QuickTest { public static void main(String[] args) { int i, numgrades; String s1; int grade[]; s1 = JOptionPane.showInputDialog( "Enter the number of grades to be processed: "); numgrades = Integer.parseInt(s1);

Page 240

grade = new int[numgrades]; // allocate the array System.out.println("An array was created for " + numgrades + " integers."); System.out.println( " The values stored in the array have been initialized to:"); for (i = 0; i < numgrades; i++) { System.out.println("grade[" + i + "] is " + grade[i]); } System.exit(0); } }

Exercises 8.2 1. Write array declarations, including initializations, for the following: 1a. a list of the ten integer grades: 89, 75, 82, 93, 78, 95, 81, 88, 77, 82 int grades[] = {89,75,82,93,78,95,81,88,77,82}; 1b. a list of the five double-precision amounts: 10.62, 13.98, 18.45, 12.68, 14.76 double amounts[] = {10.62,13.98,18.45,12.68,14.76};

Page 241

1c. a list of the six double-precision interest rates" 6.29, 6.95, 7.25, 7.35, 7.40, 7.42 double interestRates = {6.29,6.957.25,7.35,7.40,7.42}; 1d. a list of the ten floating-point temperatures: 78.2, 69.6, 68.5, 83.9, 55.4, 67.0, 49.8, 58.3, 62.5, 71.6 float temperatures = {.2F, 69.6F, 68.5F, 83.9F, 55.4F, 67.0F, 49.8F, 58.3F, 62.5F, 71.6F}; 1e. a list of the seven character codes: f, j, m, q, t, w, z char codes = {f,j,m,q,t,w,z}; 3. Write a program that uses an array declaration statement to initialize the following numbers in an array named slopes: 17.24, 25.63, 5.94, 33.92, 3.71, 32.84, 35.93, 18.24, 6.92. Your program should locate and display both the maximum and minimum values in the array. import javax.swing.*; public class QuickTest { public static void main(String[] args) { double slopes[] = {17.24, 25.63, 5.94, 33.92, 3.71, 32.84, 35.93, 18.24, 6.92}; double min = -1; double max = -1; int indexSmall = 0;

Page 242

int indexLarge = 0; for (int i = 0; i < slopes.length; i++) { if (slopes[i] < slopes[indexSmall]) indexSmall = i; if (slopes[i] > slopes[indexLarge]) indexLarge = i; } JOptionPane.showMessageDialog(null, "Maximum: " + slopes[indexLarge] + "\nMinimum: " + slopes[indexSmall], "QuickTest",JOptionPane.INFORMATION_MESSAGE); } } 5. Enter and execute QuickTest Program 8-6 on your computer. Students should enter and execute the specified program. 7. Enter and execute QuickTest Program 8-7 on your computer. Students should enter and execute the specified program. 9. Change the declaration statement for newnums in both Programs 8-7 and 8-8 to int newnums[];. Explain why this modification results in a run-time error for QuickTest Program 8-7 but does not affect the execution of QuickTest Program 8-8. In program 8-7, Java will complain because newnums will not be initialized before its use. However, in program 8-8, Java will not complain because newnums is initialized before its use by the statement:

Page 243

newnums = nums; Exercises 8.3 1. Enter and run QuickTest Program 8-9 on your computer. Students should enter and execute the specified program. 3. Modify QuickTest Program 8-9 to enter and sort an array of last names. import java.io.*; input stream classes import java.util.Arrays; and binarySearch() public class QuickTest { // needed to access // needed for sort()

public static void main (String[] args) throws java.io.IOException { String s1; int i, numels; String lastNames[]; String item; int location; // set up the basic input stream BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter the number of array values: ");

Page 244

s1 = br.readLine(); numels = Integer.parseInt(s1); // allocate the array lastNames = new String[numels]; // read the array values for (i = 0; i < numels; i++) { System.out.print("Enter element " + (i+1) + ": "); lastNames[i] = br.readLine(); } // sort the array Arrays.sort(lastNames); // display the sorted array System.out.print("The values in sorted order are:"); for (i = 0; i < numels; i++) System.out.print(" " + lastNames[i]); // now locate a desired element System.out.print("\n\nEnter the item you are searching for: "); item = br.readLine(); location = Arrays.binarySearch((Object[])lastNames, (Object)item); if (location > 0) System.out.println("This item is at location "

Page 245

+ (location + 1) + " in the sorted array."); else System.out.println("This item is not in the list."); } } Exercises 8.4 1. The following declarations were used to create an array referenced by the variable grades: final int NUMGRADES = 500; double grades[] = new double[NUMGRADES]; Write a method header line for a method named sortArray() that accepts grades as a parameter named inArray and returns no value. public void sortArray(double[] inArray) 3. The following declaration was used to create an array referenced by the variable rates: final int NUMRATES = 256; double rates[][ = new double[NUMRATES]; Write a method header line for a method named prime() that accepts rates as a parameter named rates and returns a floatingpoint number. public float prime(double[] rates) 5. Write a program that has a declaration in main() to store the following numbers into an array referenced by a variable

Page 246

named rates: 6.5, 7.2, 7.5, 8.3, 8.6, 9.4, 9.6, 9.8, 10.0. There should be a call to show(). The show() method should accept rates as a parameter named rates and then display the numbers in the array. public class QuickTest { public static void main(String[] args) { double rates[] = {6.5, 7.2, 7.5, 8.3, 8.6, 9.4, 9.6, 9.8, 10.0}; show(rates); } public static void show(double[] inArray) { for (int i = 0; i < inArray.length; i++) System.out.println("Element " + (i+1) + ": " + inArray[i]); } } 7. Write a program that includes two methods named calcAverage()and variance(). The calcAverage() method should calculate and return the average of the values stored in an array named testvals. The array should be declared in main() and include the values 89, 95, 72, 83, 99, 54, 86, 75, 92, 73, 79, 75, 82, 73. The variance() method should calculate and return the variance of the data. The variance is obtained by subtracting the average from each value in testvals, squaring the differences obtained, adding their squares, and dividing by the number of elements in testvals. The values returned from calcAverage() and variance() should be displayed from within main(). public class QuickTest

Page 247

{ public static void main(String[] args) { int testvals[] = {89, 95, 72, 83, 99, 54, 86, 75, 92, 73, 79, 75, 82, 73}; double average = calcAverage(testvals); double variance = variance(testvals); System.out.println("The average of the data is: " + average); System.out.println("The variance of the data is: " + variance); } public static double calcAverage(int[] inArray) { double total = 0; for (int i = 0; i < inArray.length; i++) total += inArray[i]; } return total / inArray.length;

public static double variance(int[] inArray) { double average = calcAverage(inArray); double sqrTotal = 0; for (int i = 0; i < inArray.length; i++) sqrTotal += (inArray[i] average)*(inArray[i]-average); } return sqrTotal / inArray.length;

Page 248

Exercises 8.5 1. Define the terms container and Collection Framework. The Collection Framework, which is frequently referred to as the Framework, is a set of classes that currently provides seven different types of generic data structures, each of which is referred to as a container. 3. What container types can be created from the Set class? HashSet, TreeSet, LinkedHashSet 5. Enter and execute QuickTest Program 8-12. Students should enter and execute the specified program. 7. Enter and execute QuickTest Program 8-13. Students should enter and execute the specified program. 9. Enter and execute Program 8-15. To do this successfully, you will also have to compile Program 8-14. Students should enter and execute the specified program 11. Enter and execute Program 8-16. Students should enter and execute the specified program. 13. Define an ArrayList of objects for factory employees, in which each object contains the for name, age, social security number, hourly wage, and years that an employee is with the company. Write the following:

Page 249

a. Statements that display the name and number of years with the company for the 25th employee in the array class Employess { String name; int age; int ss; double hourlyWage; int yearsEmployed; public String getName(){return name;} public int getYears(){return yearsEmployed;} public void addYear(){yearsEmployed++;} public void giveRaise(double amt){hourlyWage += amt;} } Employees employeeList[] = new EmployeeList[100]; String name = employeeList[24].getName(); int years = employeeList[24].getYear(); b. A loop that, for every employee, adds 1 to the number of years with the company and that adds 50 cents to the hourly wage for (int i = 0; i < employeeList.length; i++) { employeeList[i].addYear(); employeeList[i].giveRaise(0.50); }

Page 250

Exercises 8.6 1. Write a single declaration and allocation statement for: 1a. an array of integers with 6 rows and 10 columns int integerArray[][] = new int[6][10]; 1b. an array of integers with 2 rows and 5 columns int integerArray[][] = new int[2][5]; 1c. an array of characters with 7 rows and 12 columns char charArray[][] = new char[7][12]; 1d. an array of characters with 15 rows and 7 columns char charArray[][] = new char[15][7]; 1e. an array of double-precision numbers with 10 rows and 25 columns double doubleArray[][] = new double[10][25]; 1f. an array of double-precision numbers with 16 rows and 8 columns double doubleArray[][] = new double[16][8]; 3. a. Write a Java program that adds the values of all elements in the val array used in Exercise 2 and displays the total. public class QuickTest { public static void main(String[] args) { int val[][] = {{8,16,9,52},{3,15,27,6}, {7,25,2,10}}; int total = 0;

Page 251

for (int i = 0; i < val.length; i++) for (int j = 0; j < val[i].length; j++) total += val[i][j]; System.out.println("Sum of values in array is: " + total); } } b. Modify the program written for Exercise 3a to display the total of each row separately. public class QuickTest { public static void main(String[] args) { int val[][] = {{8,16,9,52},{3,15,27,6}, {7,25,2,10}}; int total; for (int i = 0; i < val.length; i++) { total = 0; for (int j = 0; j < val[i].length; j++) total += val[i][j]; System.out.println("Total of Row " + i + ": " + total); } } } 5. a. Write a Java program that finds and displays the maximum value in a two-dimensional array of integers. The array should be declared as a four-by-five array of integers and initialized with these

Page 252

data: 16, 22, 99, 4, 18, 258, 4, 101, 5, 98, 105, 6, 15, 2, 45, 33, 88, 72, 16, 3. public class QuickTest { public static void main(String[] args) { int val[][] = {{16,22,99,4,18},{258,4,101,5,98},{105, 6, 15, 2, 45}, {33, 88, 72, 16, 3}}; int maxValue = -1000000; for (int i = 0; i < val.length; i++) for (int j = 0; j < val[i].length; j++) if (val[i][j] > maxValue) maxValue = val[i][j]; System.out.println("Maximum value is: " + maxValue); } } b. Modify the program written in Exercise 5a so that it also displays the maximum value's row and column subscript values. public class QuickTest { public static void main(String[] args) { int val[][] = {{16,22,99,4,18},{258,4,101,5,98},{105, 6, 15, 2, 45}, {33, 88, 72, 16, 3}}; int maxValue = -1000000, maxRow = -1, maxCol = -1;

Page 253

for (int i = 0; i < val.length; i++) for (int j = 0; j < val[i].length; j++) if (val[i][j] > maxValue) { maxValue = val[i][j]; maxRow = i; maxCol = j; } System.out.println("Maximum value is: " + maxValue); System.out.println( "Maximum occurs at row " + (maxRow+1) + " column " + (maxCol+1)); } } 7. a. A professor has constructed a two-dimensional array of double numbers having three rows and five columns. This array currently contains the test grades of the students in the professor's advanced compiler design class. Write a Java program that reads 15 array values and then determine the total number of grades in the ranges less than 60, greater than or equal to 60 and less than 70, greater than or equal to 70 and less than 80, greater than or equal to 80 and less than 90, and greater than or equal to 90. public class QuickTest { public static void main(String[] args) { double grades[][] = {{16,22,99,4,18},{95,4,75,5,98},{83, 66, 80, 2, 45}};

Page 254

int numA = 0, numB = 0, numC = 0, numD = 0, numF = 0; for (int i = 0; i < grades.length; i++) for (int j = 0; j < grades[i].length; j++) { if (grades[i][j] >= 90) numA++; else if (grades[i][j] >= 80) numB++; else if (grades[i][j] >= 70) numC++; else if (grades[i][j] >= 60) numD++; else numF++; } System.out.println("Number of As: " + numA); numB); numC); numD); numF); } } b. It is cumbersome to enter 15 grades each time the program written for Exercise 7a is run. What method is appropriate for initializing the array during the testing phase? System.out.println("Number of Bs: " + System.out.println("Number of Cs: " + System.out.println("Number of Ds: " + System.out.println("Number of Fs: " +

Page 255

The method used to solve part a is the appropriate method for testing the code. Instead of manually entering in all the required values for every test run, one should just define the array contents using literal values. within the source program .c. How might the program you wrote for Exercise 7a be modified to include the case of no grade being present? That is, what grade could be used to indicate an invalid grade and how does your program have to be modified to exclude counting such a grade? A negative value would be a good choice for an invalid grade as negative scores are typically not allowed in this application. The program merely needs to check that the grade is nonnegative before processing. If the grade is negative, it just needs to skip over that grade when counting. 9. Write a method that can be used to sort the elements of a 10-by-20 two-dimensional array of integers. (Hint: You will need to develop a method to exchange two array elements.) public static void sort2D(int[][] inArray) { // Sort one element at a time for (int i = 0; i < inArray.length; i++) for (int j = 0; j < inArray[i].length; j++) // Find the smallest element for (int k = i; k < inArray.length; k++) if (k == i) { for (int m = (j + 1); m < inArray[k].length; m++) if (inArray[k][m] < inArray[i][j]) swap(inArray, k, m, i, j);

Page 256

} else { for (int m = 0; m < inArray[k].length; m++) if (inArray[k][m] < inArray[i][j]) swap(inArray, k, m, i, j); } }

public static void swap(int[][] inArray, int x1, int y1, int x2, int y2) { int temp = inArray[x1][y1]; inArray[x1][y1] = inArray[x2][y2]; inArray[x2][y2] = temp; }

Page 257

III. Sample Test Questions Chapter 8 1) A scalar variable is a(n) a) type that can hold at most one built-in data at-a-time b) type whose values can be decomposed into atomic elements, and an accessing scheme c) object type d) external file type Answer: (A) 2) A one-dimensional array is a list of related values, with a) different types and different names b) different types and the same name c) the same type and different names d) the same type and the same name Answer: (D) 3) Given an array declared as: int grades[] = new int [NUM_STUDENTS]; the index of the last element is a) NUM_STUDENTS b) 0 c) NUM_STUDENTS-1 d) Cant be determined from the information given

Page 258

Answer: (C) 4) To output values from the grade array, use the following code segment a) for ( i = 0; i < NUM_STUDENTS; i++) System.out.print ( grades[i] ); b) for ( i = 1; i <= NUM_STUDENTS; i++) System.out.print ( grades[i] ); c) for ( i = 0; i <= NUM_STUDENTS; i--) System.out.print ( grades[i] ); d) System.out.println ( grades ); Answer: (A) 5) Given a ten-element array, x, the statement x[10] = 15; a) generates a syntax error b) generates a run-time error c) is legal, but will overwrite the memory just beyond the end of the array d) sets the last element to 15 Answer: (B) 6) To pass a single element of an array to a method a) include the array name and the element number, enclosed in brackets b) just include the array name c) include the data type, the array name, and the element number, enclosed

Page 259

in brackets d) just mention the element number, enclosed in brackets Answer: (A) 7) When passing an array to a method, the method receives a) a copy of the original array b) the starting address of the original array c) the number of bytes in the original array d) the number of elements in the original array Answer: (B) 8) If a method changes the data in a passed-in array, the a) changes are reflected in the original array b) original array is left unchanged c) changes are copied back to the original array when the method returns d) changes are reflected in the original array, as long as the programmer passes in the size of the array as well Answer: (A) 9) In a two-dimensional array, the elements are stored in a) column, row order b) row, column order c) whichever order the programmer decides d) a compiler-determined order (varies with the compiler) Answer: (B)

Page 260

10) In a typical two-dimensional array processing application a) nested while loops are used, the outer to control the row index, the inner to control the column index b) nested while loops are used, the outer to control the column index, the inner to control the row index c) nested for loops are used, the outer to control the column index, the inner to control the row index d) nested for loops are used, the outer to control the row index, the inner to control the column index Answer: (D) 11) Which statement displays the last element of an array declared as x[100][50]; a) System.out.println ( x[100][50] ); b) System.out.println ( x[50][100] ); c) System.out.println ( x[49][99] ); d) System.out.println ( x[99][49] ); Answer: (D) 12) In passing a two-dimensional array to a method a) the column size must be given, but not the row size b) the row size must be given, but not the column size

Page 261

c) both the row size and the column size must be given d) neither the row size or the column size need to be given Answer: (A)

13) The index of the first element in a 100 element array is a) -1 b) 0 c) 1 d) 100 Answer: (B) 14) The size of an array in Java a) must be kept track of separately by the programmer b) is kept track of by the array class in Java c) must be known at compile time or computed using a for loop d) must be known at compile time of computed using any kind of iterative means Answer: (B) 15) An array can be allocated a) dynamically b) statically c) dynamically or statically d) none of the above

Page 262

Answer: (C)

Page 263

I. OVERVIEW: Chapter 9 Visual Programming Basics This chapter describes the fundamentals of event-based programming required in using a graphical user interface (GUI). This is followed by a very simple GUI using the Java-provided Swing package of classes. Initially, a simple window with no internal components is constructed from a single GUI class. Although a full understanding of this class requires the information on class construction provided in Part Two, this class can still be used as a basic model without this understanding. This GUI class is then expanded to include a window closing event, which forms the model structure for all subsequent component event handlers. Finally, the GUI is provided with an internal Command button component and an associated event handler that responds to the button being clicked. 9.1 Event-based Programming The Event-based Model Containment Hierarchy 9.2 Creating a Swing-Based Window Look and Feel 9.3 Adding a WindowClosing Event Handler The Delegation Model Adapter and Inner Classes Anonymous Classes 9.4 Adding a Button Component\ Adding ToolTips and Accelerator Keys Ading an Event Handler 9.5 Common Programming Errors and Problems 9.6 Chapter Summary

Potential Problem areas:

Page 264

Event-based programming will be new and confusing to most students. Using the Swing package will seem overwhelming to many. The difficulties will be balanced to some extent by the interesting visual displays their programs will create.

Page 265

III ANSWERS TO ODD-NUMBERED EXERCISES Exercises 9.1 1. What is the purpose of a GUI and what elements does a user see in a GUI? The GUI is a dialog intended either to present information or to request specific input items as dictated by program code. The user will see various components, or controls that are used to acquire input data and to signal the application to perform a requested task. There are many variations to the content that a user can see in a GUI. 3. List the three ways that an event can be triggered by a user. Placing the mouse pointer over a button and clicking the left mouse button Using the tab key until the desired button is highlighted with a dotted line and then pushing the Enter key. Pressing an accelerator key 5. What top-level container type is used, almost exclusively, to create stand-alone Java application GUIs? JFrame 7. What is the internal component provided by each top-level container to which all visible GUI components must be added? content pane Exercises 9.2

Page 266

1. Describe the two main approaches to constructing GUIs using Swing-based components. 1. Construct the GUI as a separate class using Swing components. Then use a main() method to instantiate (that is, create) an object of

the class. When a specific GUI object is instantiated, the GUI will appear on the screen. 2. Construct a GUI object using Swing components from within a main() method without first creating a separate GUI class. 3.a. Enter and execute Program 9-2 on your computer. Students should enter and execute the specified program. b. What is a major problem with Program 9-2? Closing the window does not close the Java application. c. After closing the window constructed by Program 9-2, how can the underlying Java program be halted and return provided to the operating system? Press the CTRL and C keys at the same time. d. How would Program 9-2 be named and stored on your computer? It would be named and stored as FirstWindow.java.

Page 267

5. Modify Program 9-2 so that the size of the displayed GUI is 400 pixels wide by 200 pixels high. import javax.Swing.*; public class FirstWindow extends JFrame { private JFrame mainFrame; public FirstWindow() // a constructor { mainFrame = new JFrame("First GUI Window"); mainFrame.setSize(400,200); mainFrame.show(); } public static void main(String[] args) { new FirstWindow(); } } 7. Modify Program 9-2 so that the main() method is contained within a class named TestFirstWindow. The program should be stored under the name TestFirstWindow.java. import javax.Swing.*; public class TestFirstWindow extends JFrame { private JFrame mainFrame; public TestFirstWindow() // a constructor { mainFrame = new JFrame("First GUI Window");

Page 268

mainFrame.setSize(400,200); mainFrame.show();

public static void main(String[] args) { new TestFirstWindow(); }

9. List the four look and feel types provided by Java's Swing package. Java, Mac, Windows, UNIX.

Exercises 9.3 1a. Compile, execute, and run Program 9-3 on your computer. Students should enter and execute the specified program. b. Repeat Exercise 1a, but remove the registration statement mainFrame.addWindowListener(handler); With this statement removed, determine what happens when you now close down the displayed window using the window's Close (X) button. The Java application does not terminate upon pressing the close button. 3a. Compile, execute, and run Program 9-4 on your computer.

Page 269

Students should enter and compile the specified program. b. Make sure to first compile Program 9-3, then change Program94's single main() method's statement from new FourthWindow(); to new ThirdWindow();. Now compile, execute, and run the modified Program 9-4. Determine what happened and why. An instance of ThirdWindow is created and executed instead of FourthWindow. 5a. Describe the purpose of an adapter class. Java provides a special set of classes, referred to as adapter classes, that declare empty event handling methods for a given interface type. Because an adapter class provides all of the method declarations for an interface, it can be used as the parent class for a listener class. b. Must an adapter class always be used as an inner class? No. 7. Why do you think the TextListener and ItemListener classes have no equivalent adapter classes? (Hint: See Table 9-7.) There is only one method that needs to be implemented for these classes. Exercises 9.4 1a. To what top-level pane must all GUI components be added? content pane b. What method is used to obtain the internal component referred to in Exercise 1a?

Page 270

getContentPane() c. What method is used to add a component to the internal frame referred to in Exercise 1a? add() 3. Create a Java program that has a single JButton object with the caption Message. public QuickTest() { mainFrame = new JFrame("Example of a Gui with a Button"); firstButton = new JButton("Message"); Container c = mainFrame.getContentPane(); c.add(firstButton); mainFrame.setSize(300,150); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); } mainFrame.show();

public static void main(String[] args) { new QuickTest(); }

Page 271

5. Enter, compile, and execute Program 9-8 on your computer. Students should enter and execute the specified program. 7. Modify Program 9-9 to display the message Hello World! when the button is clicked. Change the following line of code: JOptionPane.showMessageDialog(null, "Button was Pressed", "Event Handler Message",JOptionPane.INFORMATION_MESSAGE); to: JOptionPane.showMessageDialog(null, "Hello World", "Event Handler Message",JOptionPane.INFORMATION_MESSAGE);

9. Modify Program 9-9 so that the button's listener class is coded as an anonymous class. import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls public class QuickTest extends JFrame { private JFrame mainFrame; private JButton firstButton;

Page 272

public QuickTest() // a constructor { mainFrame = new JFrame("Example of a Gui with a Button"); firstButton = new JButton("Press me"); Container c = mainFrame.getContentPane(); c.add(firstButton); firstButton.setToolTipText("This is a button"); firstButton.setMnemonic('P'); mainFrame.setSize(300,150); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); firstButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Button was Pressed", "Event Handler Message", JOptionPane.INFORMATION_MESSAGE); } });

Page 273

mainFrame.show();

public static void main(String[] args) { new QuickTest(); } }

Page 274

III. Sample Test Questions Chapter 9 1) An accelerator key is also called a(n) a) enter key b) mnemonic key c) fast-track key d) focus key Answer: (B) 2) The javax.swing package is a newer version of the a) java.io package b) java.lang package c) java.swing package d) java.awt package Answer: (D) 3) A ____ is a top-level Container a) JFrame b) JPanel c) JButton d) JListBox Answer: (A)

274

Page 275

4) Atomic components are inserted using the a) insert() method b) atomic() method c) add() method d) put() method Answer: (C)

5) The protocol for component placement is referred to as a(n) a) containment hierarchy b) placement scheme c) hierarchy chart d) nesting scheme Answer: (A) 6) The default layout manager for a JFrame is a) FlowLayout b) BorderLayout c) GridLayout d) CardLayout Answer: (B)

275

Page 276

7) A component that triggers an event when clicked is a a) JLabel b) JTextArea c) JTextField d) JButton Answer: (D) 8) To display a JFrame, use the a) show() method b) display() method c) setShow() method d) makeVisible() method Answer: (A)

9) An ____ is a object that responds appropriately when an event occurs. a) event handler b) event processor c) event parser d) event controller Answer: (B)
276

Page 277

10) Another name for an event handler is a(n) a) delegate object b) listener object c) component d) heavyweight object Answer: (B) 11) Calling an add() method is known as a(n) a) certification statement b) addition statement c) insertion statement d) registration statement Answer: (D) 12) A class from which objects cannot be instantiated is called a(n) a) handler class b) event class c) abstract class d) inner class Answer: (C) 13) An anonymous class has no
277

Page 278

a) variables b) name c) code d) methods Answer: (B) 14) A containers ___________ holds all of its visible components. a) buttons b) component hierarchy c) content pane d) registration pane Answer: (C) 15) A ToolTip is a(n) a) online help file b) offline help file c) line of text that appears when a user positions the cursor over a component d) Windows message system Answer: (C)

278

Page 279

I. OVERVIEW: Chapter 10 Additional Components and Event Handlers This chapter shows how additional GUI components can be added to the basic JFrame GUI presented in Chapter 9. The procedure presented for adding components is illustrated using text fields, Radio buttons, and Check boxes. Providing a GUI with these components produces a rather complete graphical user interface that is more than adequate for the majority of Java programs you will write. It also provides you with the ability to add other components as you need them. In addition, layout managers are discussed that permit you to position the additional components in various configurations. Listener classes are provided for each of the new components presented. A new type of listener class, referred to as a focus listener, is presented for detecting and appropriately responding to focus events. Specifically, the focus events considered are when a component gains or loses focus. Finally, procedures are given for validating user input on a keystroke-by-keystroke basis, as each key is pressed. 10.1 Adding Multiple Components Layout Managers Keyboard Focus and Tab Control 10.2 Text Components for Display Adding a JTextField Component Setting Font and Color JTextArea Components 10.3 Text Fields Components for Data Entry Constructing Focus Listeners Input Validation Revisited 10.4 Check Box, Radio button, and Group Components
279

Page 280

Check Boxes The Radio button Component 10.5 Keystroke Input Validation 10.6 Common Programming Errors and Problems 10.7 Chapter Summary

Potential Problem areas: This is probably the most challenging chapter in the book. Many students will feel completely lost at this point. Focus can be a tricky concept. The programming exercises are very long and involved, with many opportunities for syntax and logic errors. Be careful when assigning the homework problems; they are quite involved and time-consuming.

280

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 10.1 1. Enter, compile, and execute Program 10-1 on your computer. Students should enter and execute the specified program. 3. Modify Program 10-1 to include the single listener class presented in this section. Compile and execute your program to verify that it operates correctly. import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton messageButton; private JButton clearButton; private JButton exitButton; public QuickTest() // a constructor { mainFrame = new JFrame("The Hello Application Ver. 1.0"); // create the button objects messageButton = new JButton("Message");

clearButton = new JButton("Clear"); exitButton = new JButton("Exit"); // get the content pane & specify layout manager Container c = mainFrame.getContentPane(); c.setLayout(new FlowLayout()); // add the button to the ContentPane c.add(messageButton); c.add(clearButton); c.add(exitButton); ButtonsHandler bhandler = new ButtonsHandler(); // instantiate a handler messageButton.addActionListener(bhandler); register the handler //

clearButton.addActionListener(bhandler); // register the handler exitButton.addActionListener(bhandler); // register the handler // create accelerator keys messageButton.setMnemonic('M'); clearButton.setMnemonic('C'); exitButton.setMnemonic('x'); mainFrame.setSize(300,100); // define and register window event handler

mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); } mainFrame.show();

public static void main(String args[]) { QuickTest app; // declare a MultiButtons variable app = new QuickTest(); // instantiate a GUI object } class ButtonsHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == messageButton) JOptionPane.showMessageDialog(null, "Message Button was Clicked", "Event Handler Message", JOptionPane.INFORMATION_MESSAGE); else if (e.getSource() == clearButton) JOptionPane.showMessageDialog(null, "Clear Button was Clicked",

"Event Handler Message", JOptionPane.INFORMATION_MESSAGE); else if (e.getSource() == exitButton) System.exit(0); } } // end of inner class } // end of class 5. What are the four ways that an atomic component can receive focus? 1. A user clicks the mouse directly on the object. 2. A user presses the Tab key until the object gets the focus 3. A user presses the accessor key for the object. 4. The code activates the focus. .

7. Write a Java application having three buttons. Clicking the first button should produce the message See no evil, clicking the second button should produce the message Hear no evil, and clicking the third button should produce the message Speak no evil in the text box. import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame

{ private private private private JFrame mainFrame; JButton seeButton; JButton hearButton; JButton speakButton;

public QuickTest() // a constructor { mainFrame = new JFrame("The Button Application Ver. 1.0"); // create the button objects seeButton = new JButton("See"); hearButton = new JButton("Hear"); speakButton = new JButton("Speak"); // get the content pane & specify layout manager Container c = mainFrame.getContentPane(); c.setLayout(new FlowLayout()); // add the button to the ContentPane c.add(hearButton); c.add(seeButton); c.add(speakButton); ButtonsHandler bhandler = new ButtonsHandler(); // instantiate a handler seeButton.addActionListener(bhandler); // register the handler hearButton.addActionListener(bhandler); register the handler //

speakButton.addActionListener(bhandler); register the handler // create accelerator keys seeButton.setMnemonic('S'); hearButton.setMnemonic('H'); speakButton.setMnemonic('K'); mainFrame.setSize(300,100);

//

// define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); } mainFrame.show();

public static void main(String args[]) { QuickTest app; // declare a MultiButtons variable app = new QuickTest(); // instantiate a GUI object } class ButtonsHandler implements ActionListener { public void actionPerformed(ActionEvent e) {

if (e.getSource() == speakButton) JOptionPane.showMessageDialog(null,"Speak no Evil","", JOptionPane.INFORMATION_MESSAGE); else if (e.getSource() == seeButton) JOptionPane.showMessageDialog(null,"See no Evil","", JOptionPane.INFORMATION_MESSAGE); else if (e.getSource() == hearButton) { JOptionPane.showMessageDialog(null,"Hear no Evil","", JOptionPane.INFORMATION_MESSAGE); } } } // end of inner class } // end of class Exercises 10.2 1. Compile and execute Program 10-3 on your computer. Students should enter and compile the specified program. 3a. Write a Java program that creates a GUI having the following properties table: Object Property Setting

JFrame Layout JButton

Name mainFrame Caption Messages FlowLayout Name Caption Mnemonic Name Caption Mnemonic cmdGood Good G cmdBad Bad B txtMessage

JButton

JTextField Name Text (none)

import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton cmdGood; private JButton cmdBad; private JTextField txtMessage; public QuickTest() // a constructor { mainFrame = new JFrame("Messages");

// create all components cmdGood = new JButton("Good"); cmdGood.setMnemonic('G'); cmdBad = new JButton("Bad"); cmdBad.setMnemonic('B'); txtMessage = new JTextField(""); // get the content pane Container c = mainFrame.getContentPane(); c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(txtMessage); c.add(cmdGood); c.add(cmdBad); mainFrame.setSize(300,150); mainFrame.show(); handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); } public static void main(String args[]) { // define and register window event

new QuickTest(); object } } // end of class

// instantiate a GUI

b. Add individual event handlers to the program written for Exercise 3a so that when a user clicks the Good button, the message Today is a good day! appears in the text field, and when the Bad button is clicked, the message Im having a bad day today! is displayed in the text field. import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton cmdGood; private JButton cmdBad; private JTextField txtMessage; public QuickTest() // a constructor { mainFrame = new JFrame("Messages"); // create all components txtMessage = new JTextField("",25); cmdGood = new JButton("Good");

cmdGood.setMnemonic('G'); cmdGood.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { txtMessage.setText("Today is a good day!"); } }); cmdBad = new JButton("Bad"); cmdBad.setMnemonic('B'); cmdBad.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { txtMessage.setText("I'm having a bad day today!"); } }); // get the content pane Container c = mainFrame.getContentPane(); c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(txtMessage); c.add(cmdGood); c.add(cmdBad); mainFrame.setSize(300,150); mainFrame.show();

handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); } public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } } // end of class

// define and register window event

5a. Create a text field component that has a red foreground color and a blue background color. The initial text displayed in the field should be Welcome to Java. The lines of code important to this question are: JTextField redOnBlue; redOnBlue = new JTextField(Welcome to Java); redOnBlue.setForeground(Color.red); redOnBlue.setBackground(Color.blue);

b. Add a text field component to the GUI created for Exercise 5a that has a white foreground color and a red background color. The initial text displayed in the field should be Object-oriented language. The lines of code important to this question are JTextField whiteOnRed; whiteOnRed = new JTextField(Object-oriented language); whiteOnRed.setForeground(Color.white); whiteOnRed.setBackground(Color.red); 7a. Write a Java program that creates a GUI having the following properties table: Object JFrame Property Setting

Name mainFrame Caption TypeFace Example Layout FlowLayout JButton Name cmdBold Caption Bold Mnemonic B JButton Name cmdItalic Caption Italic Mnemonic I JTextField Name txtMessage Text This is a test By clicking the text field, the user should be able to enter any desired text in nonboldface and nonitalic font. When the user clicks the Bold button, the text in the text field should change to boldface, and when the user clicks the Italic button, the text should change to italic.

import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton cmdBold; private JButton cmdItalic; private JTextField txtMessage; public QuickTest() // a constructor { mainFrame = new JFrame("Typeface Example"); // create all components txtMessage = new JTextField("test",25); cmdBold = new JButton("Bold"); cmdBold.setMnemonic('B'); cmdBold.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { txtMessage.setFont(new Font("Arial",Font.BOLD,12)); } }); cmdItalic = new JButton("Italic");

cmdItalic.setMnemonic('I'); cmdItalic.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { txtMessage.setFont(new Font("Arial",Font.ITALIC,12)); } }); // get the content pane Container c = mainFrame.getContentPane(); c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(txtMessage); c.add(cmdItalic); c.add(cmdBold); mainFrame.setSize(300,150); mainFrame.show(); handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); } // define and register window event

public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } } // end of class

b. From a user's viewpoint, what is the problem with the program as it is written? One cannot activate both the bold and italic attributes at the same time or mix font attributes at different sections in the line of text. 9. Compile and execute Program 10-4 on your computer. Students should enter and execute the specified program. 11. Add three command buttons to Program 10-4. Clicking the first button should produce the table shown in Figure 10-7, clicking the second button should clear the text area, and clicking the third button should cause the program to close. (Hint: Move the code in the current createTable() to the first button's event handler class.) package test; import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager

import java.text.*; // need this for formatting public class QuickTest extends JFrame { private JFrame mainFrame; private JTextArea outArea; private JButton cmdTable; private JButton cmdClear; private JButton cmdExit; public QuickTest() // a constructor { mainFrame = new JFrame("Example of a Text Area for Output"); // create all components outArea = new JTextArea(10, 28); cmdTable = new JButton("Create Table"); cmdTable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int num; DecimalFormat df = new DecimalFormat("0000"); outArea.setFont(new Font("Courier", Font.BOLD, 10)); outArea.append(" NUMBER SQUARE CUBE\n"); outArea.append(" \n");

outArea.setFont(new Font("Courier", Font.PLAIN, 10)); for (num = 1; num < 11; num++) { outArea.append(" " + df.format(num)); outArea.append(" " + df.format(num*num)); outArea.append(" " + df.format(num * num * num) +'\n'); } } }); cmdClear = new JButton("Clear Table"); cmdClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { outArea.setText(""); } }); cmdExit = new JButton("Exit"); cmdExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } });

// get the content pane Container c = mainFrame.getContentPane(); c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(outArea); c.add(cmdTable); c.add(cmdClear); c.add(cmdExit); mainFrame.setSize(300,250); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); mainFrame.show(); } public static void main(String args[]) { QuickTest app; // declare an object of type ShowTextArea app = new QuickTest(); // instantiate a GUI object }

// end of class

Exercises 10.3 1. Enter and execute Program 10-2 on your computer. Students should enter and execute the specified program. 3. Modify Program 10-3 so that the user cannot enter any text into the text field component (Hint: Use a setEditable(false) method.) import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton messageButton; private JButton clearButton; private JButton exitButton; private JTextField tField; public QuickTest() // a constructor { mainFrame = new JFrame("The Hello Application Ver. 3.0"); // create all components messageButton = new JButton("Message"); clearButton = new JButton("Clear");

exitButton = new JButton("Exit"); tField = new JTextField("Hello World!"); tField.setEditable(false); // get the content pane Container c = mainFrame.getContentPane(); // add the components to the ContentPane c.add(tField,BorderLayout.NORTH); c.add(messageButton,BorderLayout.WEST); c.add(clearButton,BorderLayout.CENTER); c.add(exitButton,BorderLayout.EAST); // create accelerator keys messageButton.setMnemonic('M'); clearButton.setMnemonic('C'); exitButton.setMnemonic('x'); mainFrame.setSize(300,150); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the button event handlers MessageButtonHandler mhandler = new MessageButtonHandler(); // instantiate a // handler

messageButton.addActionListener(mhandler); register the handler

//

ClearButtonHandler chandler = new ClearButtonHandler(); // instantiate a handler clearButton.addActionListener(chandler); // register the handler ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler mainFrame.show(); } // inner classes for the button event handlers class MessageButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { } } // end of inner class tField.setText("Hello World Once Again!");

class ClearButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) {

tField.setText(""); } } // end of inner class class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of inner class public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } } // end of class

5. Modify Program 10-5 to include the ConvertTempOne Class' FocusListener developed in this section. import java.text.*; // need this for formatting import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame

{ private private private private private private private private JFrame mainFrame; FocusHandler fhandler; JButton convertButton; JButton exitButton; JTextField fahrField; JTextField celsField; JLabel fahrLabel; JLabel celsLabel;

public QuickTest() // a constructor { mainFrame = new JFrame("Temperature Conversion"); // create all components convertButton = new JButton("Convert to Celsius"); exitButton = new JButton("Exit"); fahrLabel = new JLabel("Enter a Fahrenheit temperature:"); celsLabel = new JLabel("The corresponding Celsius value is:"); fahrField = new JTextField(5); celsField = new JTextField(5); fhandler = new FocusHandler(); fahrField.addFocusListener(fhandler); celsField.addFocusListener(fhandler); // get the content pane Container c = mainFrame.getContentPane(); // set the layout manager

c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(fahrLabel); c.add(fahrField); c.add(celsLabel); c.add(celsField); c.add(convertButton); c.add(exitButton); // create accelerator keys convertButton.setMnemonic('C'); exitButton.setMnemonic('x'); mainFrame.setSize(350,150); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the button event handlers ConvertButtonHandler chandler = new ConvertButtonHandler(); // instantiate a // handler convertButton.addActionListener(chandler); register the handler //

ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler } mainFrame.show();

// inner classes for the button event handlers class ConvertButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { DecimalFormat num = new DecimalFormat(",###.##"); String instring; double invalue, outvalue; instring = fahrField.getText(); // read the input value invalue = Double.parseDouble(instring); // convert to a double outvalue = 5.0/9.0 * (invalue - 32.0); celsField.setText(num.format(outvalue)); } } // end of inner class class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e)

{ } } // end of inner class public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } class FocusHandler implements FocusListener { public void focusGained(FocusEvent e) { if(e.getSource() == fahrField) { fahrField.setText(""); // blank input textfield celsField.setText(""); // blank Celsius textfield } else if(e.getSource() == celsField) { celsField.setNextFocusableComponent(fahrField); fahrField.grabFocus(); } } public void focusLost(FocusEvent e) { if(e.getSource() == fahrField) System.exit(0);

{ fahrField.setNextFocusableComponent(convertButto n); } } } // end of focus listener class } // end of class

7a. What statements are needed to instantiate listener objects for the classes written for Exercise 6 and to have these objects correctly registered. Assume the listener object for the FahrFocusListener class is named fahrhandler and the listener object for the CelsFocusListener class is named celshanlder. FahrFocusListener fahrhandler = new FahrFocusListener(); CelsFocusListener celshandler = new CelsFocusListener(); fahrField.addFocusListener(fahrhandler); celsField.addFocusListener(celshandler); b. Enter and execute Program 10-5 using the focus handler classes written for Exercise 6 and the instantiation and registration statements written for Exercise 7a. Students should enter and execute the two parts. 9a. Write a Java program that converts Celsius temperatures to their equivalent Fahrenheit values. Use a label to display the following prompt:

Enter the temperature in degrees Celsius: After accepting a value entered from the keyboard into an text field, the program should convert the entered temperature to degrees Fahrenheit using the equation Fahrenheit = (9.0 / 5.0) * Celsius + 32.0. The program should then display the temperature in degrees Fahrenheit in a clearly labeled test field. A JButton button should be provided to terminate the application. import java.text.*; // need this for formatting import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private FocusHandler fhandler; private JButton convertButton; private JButton exitButton; private JTextField fahrField; private JTextField celsField; private JLabel fahrLabel; private JLabel celsLabel; public QuickTest() // a constructor { mainFrame = new JFrame("Temperature Conversion");

// create all components convertButton = new JButton("Convert to Celsius"); exitButton = new JButton("Exit"); celsLabel = new JLabel("Enter the temperature in degrees Celsius:"); fahrLabel = new JLabel("The corresponding Fahrenheit value is:"); fahrField = new JTextField(5); celsField = new JTextField(5); fhandler = new FocusHandler(); fahrField.addFocusListener(fhandler); celsField.addFocusListener(fhandler); // get the content pane Container c = mainFrame.getContentPane(); // set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(celsLabel); c.add(celsField); c.add(fahrLabel); c.add(fahrField); c.add(convertButton); c.add(exitButton); // create accelerator keys convertButton.setMnemonic('C'); exitButton.setMnemonic('x'); mainFrame.setSize(350,150);

// define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the button event handlers ConvertButtonHandler chandler = new ConvertButtonHandler(); // instantiate a // handler convertButton.addActionListener(chandler); register the handler //

ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler mainFrame.show(); } // inner classes for the button event handlers class ConvertButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { DecimalFormat num = new DecimalFormat(",###.##");

String instring; double invalue, outvalue; instring = celsField.getText(); // read the input value invalue = Double.parseDouble(instring); // convert to a double outvalue = 9.0/5.0 * invalue + 32.0; fahrField.setText(num.format(outvalue)); } } // end of inner class class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of inner class public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } class FocusHandler implements FocusListener { public void focusGained(FocusEvent e) { if(e.getSource() == celsField)

{ fahrField.setText(""); celsField.setText(""); } else if(e.getSource() == fahrField) { fahrField.setNextFocusableComponent(celsField); celsField.grabFocus(); } } public void focusLost(FocusEvent e) { if(e.getSource() == fahrField) { fahrField.setNextFocusableComponent(convertButto n); } } } // end of focus listener class } // end of class

b. Verify the program written for Exercise 9a by first calculating the Fahrenheit equivalent of the following test data by hand and then using your program to see if it produces the correct results. Test data set 1: 0 degrees Celsius Test data set 2: 50 degrees Celsius Test data set 3: 100 degrees Celsius When you are sure your procedure is working correctly, use it to complete the following table:

Celsius 45 50 55 60 65 70 Test value Solutions: F C -------------0 32 50 122 100 212 45 113 50 122 60 140 65 149 70 158

Fahrenheit

11a. Write and execute a Java program that displays the following prompts and uses two text fields to receive the input data: Enter the miles driven: Enter the gallons of gas used: Your program should calculate and display the miles per gallon in a text field when a button is clicked. Use the equation miles per gallon = miles / gallons used. The display should be cleared whenever one of the text fields gets the focus. A second button should be provided to terminate the application. Verify your procedure using the following test data:

Test data set 1: miles = 276, gas = 10 gallons Test data set 2: miles = 200, gas = 15.5 gallons When you have completed your verification, use your procedure to complete the following table: Miles Driven Gallons Used MPG 250 16.00 275 18.00 312 19.54 296 17.39 package test; import java.text.*; // need this for formatting import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private FocusHandler fhandler; private JButton calculateButton; private JButton exitButton; private JTextField milesField; private JTextField gallonsField; private JTextField mpgField; private JLabel milesLabel; private JLabel gallonsLabel; private JLabel mpgLabel;

public QuickTest() // a constructor { mainFrame = new JFrame("Temperature Conversion"); // create all components calculateButton = new JButton("Calculate"); exitButton = new JButton("Exit"); milesLabel = new JLabel("Enter the miles driven"); gallonsLabel = new JLabel("Enter the gallons of gas used"); mpgLabel = new JLabel("Miles per Gallon"); milesField = new JTextField(5); gallonsField = new JTextField(5); mpgField = new JTextField(5); fhandler = new FocusHandler(); milesField.addFocusListener(fhandler); gallonsField.addFocusListener(fhandler); mpgField.addFocusListener(fhandler); // get the content pane Container c = mainFrame.getContentPane(); // set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(milesLabel); c.add(milesField); c.add(gallonsLabel); c.add(gallonsField); c.add(mpgLabel);

c.add(mpgField); c.add(calculateButton); c.add(exitButton); // create accelerator keys calculateButton.setMnemonic('C'); exitButton.setMnemonic('x'); mainFrame.setSize(20,250); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the button event handlers ConvertButtonHandler chandler = new ConvertButtonHandler(); // instantiate a // handler calculateButton.addActionListener(chandler); // register the handler ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler } mainFrame.show();

// inner classes for the button event handlers class ConvertButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { DecimalFormat num = new DecimalFormat(",###.##"); String instring; double invalue1, invalue2, outvalue; instring = milesField.getText(); // read the input value invalue1 = Double.parseDouble(instring); // convert to a double instring = gallonsField.getText(); invalue2 = Double.parseDouble(instring); outvalue = invalue1/invalue2; mpgField.setText(num.format(outvalue)); } } // end of inner class class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of inner class

public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } class FocusHandler implements FocusListener { public void focusGained(FocusEvent e) { if(e.getSource() == milesField) { milesField.setNextFocusableComponent(gallonsFiel d); mpgField.setText(""); } else if (e.getSource() == gallonsField) { gallonsField.setNextFocusableComponent(calculate Button); mpgField.setText(""); } else if(e.getSource() == mpgField) { milesField.grabFocus(); } } public void focusLost(FocusEvent e) { }

} }

// end of focus listener class

// end of class

b. For the procedure written for Exercise 11a, determine how many verification runs are required to ensure the procedure is working correctly and give a reason supporting your answer. Because of the simplicity of the program, only a few verification runs will be required to test its functionality. 13. Write and execute a Java program that provides three text fields for the input of three user-input numbers. There should be a single label prompt that tells the user to enter three numbers in the text fields. When the user clicks a button, the program should calculate the average of the numbers and then display the average in a clearly labeled fourth text field. The displayed value should be cleared whenever one of the text fields receives the focus. A second button should be provided to terminate the application. Verify your procedure with the following test data: Test data set 1: 100, 100, 100 Test data set 2: 100, 50, 0 When you have completed your verification, use your program to complete the following table: Numbers Average 92, 98, 79 86, 84, 75 63, 85, 74

import java.text.*; // need this for formatting import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private FocusHandler fhandler; private JButton calculateButton; private JButton exitButton; private JTextField field1; private JTextField field2; private JTextField field3; private JTextField result; private JLabel genericLabel; public QuickTest() // a constructor { mainFrame = new JFrame("Temperature Conversion"); // create all components calculateButton = new JButton("Calculate"); exitButton = new JButton("Exit"); genericLabel = new JLabel("Enter three numbers"); field1 = new JTextField(5); field2 = new JTextField(5); field3 = new JTextField(5); result = new JTextField(5);

fhandler = new FocusHandler(); field1.addFocusListener(fhandler); field2.addFocusListener(fhandler); field3.addFocusListener(fhandler); result.addFocusListener(fhandler); // get the content pane Container c = mainFrame.getContentPane(); // set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(genericLabel); c.add(field1); c.add(field2); c.add(field3); c.add(result); c.add(calculateButton); c.add(exitButton); // create accelerator keys calculateButton.setMnemonic('C'); exitButton.setMnemonic('x'); mainFrame.setSize(320,90); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} });

// create and register the button event handlers ConvertButtonHandler chandler = new ConvertButtonHandler(); // instantiate a // handler calculateButton.addActionListener(chandler); // register the handler ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler mainFrame.show(); } // inner classes for the button event handlers class ConvertButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { DecimalFormat num = new DecimalFormat(",###.##"); String instring; double invalue1, invalue2, invalue3, outvalue; instring = field1.getText(); input value // read the

invalue1 = Double.parseDouble(instring); double

// convert to a

instring = field2.getText(); invalue2 = Double.parseDouble(instring); instring = field3.getText(); invalue3 = Double.parseDouble(instring); outvalue = (invalue1 + invalue2 + invalue3)/3; result.setText(num.format(outvalue)); } } // end of inner class class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of inner class public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } class FocusHandler implements FocusListener {

public void focusGained(FocusEvent e) { if(e.getSource() != result) { result.setText(""); } } public void focusLost(FocusEvent e) { } } // end of focus listener class } // end of class

Exercises 10.4 1. Determine whether the following choices should be presented on a GUI with check boxes or with radio buttons: a. The choice of air conditioning or not on a new automobile order form. check box b. The choice of automatic or manual transmission on a new automobile order form. check box c. The choice of AM/FM, AM/FM tape, or AM/FM CD radio on a new automobile order form.

radio button d. The choice of tape backup system or no tape backup system on a new computer order form. check box e. The choice of a 17-, 19-, or 21-inch color monitor on a new computer order form. radio button f. The choice of CD-ROM drive or not on a new computer order form. check box g. The choice of a 4-, 6-, or 8-speed CD-ROM drive on a new computer order form. radio button h. The choice of a 800-, 900-, or 1000-MHz Pentium processor on a new computer order form. radio button 3. Add the appropriate listener class provided in this section to Program 10-6. Compile and execute your program to verify that it operates correctly. import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame {

private private private private private private

JFrame mainFrame; JButton exitButton; JLabel inLabel; JTextField tinField; JCheckBox boxItalic; JCheckBox boxBold;

public QuickTest() // a constructor { mainFrame = new JFrame("Check Box Example"); // create all components exitButton = new JButton("Exit"); inLabel = new JLabel("Enter Some Text:"); tinField = new JTextField(20); boxItalic = new JCheckBox("Italic"); boxBold = new JCheckBox("Bold"); ChkBoxHandler chandler = new ChkBoxHandler(); boxItalic.addItemListener(chandler); boxBold.addItemListener(chandler); // get the content pane Container c = mainFrame.getContentPane(); // set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(inLabel); c.add(tinField);

c.add(boxItalic); c.add(boxBold); c.add(exitButton); // create accelerator keys boxItalic.setMnemonic('I'); boxBold.setMnemonic('B'); exitButton.setMnemonic('x'); mainFrame.setSize(250,150); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the exit button event handler ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler } mainFrame.show();

// inner class for the Exit button event handler private class ExitButtonHandler implements ActionListener

{ public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of inner class public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } class ChkBoxHandler implements ItemListener { private int italicFont; private int boldFont; public void itemStateChanged(ItemEvent e) { if (e.getSource() == boxBold) if (e.getStateChange() == e.SELECTED) boldFont = Font.BOLD; else boldFont = Font.PLAIN; else if (e.getStateChange() == e.SELECTED) italicFont = Font.ITALIC; else italicFont = Font.PLAIN;

tinField.setFont( new Font( "Courier", italicFont + boldFont, 14)); tinField.repaint(); } } // end of Check box listener class } // end of class

5. Enter and run Program 10-7 on your computer to verify that it correctly produces the GUI shown in Figure 10-13. Students should enter and execute the specified program. 7a. Modify Program 10-6 so that the choices presented by the check boxes are replaced by radio buttons. import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton exitButton; private JLabel inLabel; private JTextField tinField; private JRadioButton radItalic; private JRadioButton radBold; public QuickTest() // a constructor

{ mainFrame = new JFrame("Check Box Example"); // create all components exitButton = new JButton("Exit"); inLabel = new JLabel("Enter Some Text:"); tinField = new JTextField(20); radItalic = new JRadioButton("Italic"); radBold = new JRadioButton("Bold"); ButtonGroup radButtonGroup = new ButtonGroup(); radButtonGroup.add(radItalic); radButtonGroup.add(radBold); // get the content pane Container c = mainFrame.getContentPane(); // set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(inLabel); c.add(tinField); c.add(radItalic); c.add(radBold); c.add(exitButton); // create accelerator keys radItalic.setMnemonic('I'); radBold.setMnemonic('B'); exitButton.setMnemonic('x'); mainFrame.setSize(250,150);

handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the exit button event handler ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler mainFrame.show(); } // inner class for the Exit button event handler private class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { } } // end of inner class System.exit(0);

// define and register window event

public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } } // end of class

b. Based on your experience with Exercise 7a, determine what type of input choice is best presented using a check box rather than a radio button. One should use a checkbox for making choices among items that are not mutually exclusive. For example, check boxes would be used to select font properties like color, style, etc. Also, check boxes are useful when a toggle choice is necessary. An example is choosing whether or not you want pepperoni on a pizza. 9. Modify Program 10-7 so that rather than selecting font type, a user can select whether to make the displayed text uppercase or lowercase using a radio button group consisting of two buttons. Make sure to include event code so that the displayed text corresponds to a user's selection. ( Hint: Use the String class' toUpperCase() and toLowerCase() methods. For example, the expression "abcd".toUpperCase() creates the string "ABCD".) import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame

{ private private private private private private JFrame mainFrame; JButton exitButton; JLabel inLabel; JTextField tinField; JRadioButton rdbutUppercase; JRadioButton rdbutLowercase;

public QuickTest() // a constructor { mainFrame = new JFrame("Radio Button Example"); // create all components exitButton = new JButton("Exit"); inLabel = new JLabel("Enter Some Text:"); tinField = new JTextField(20); rdbutUppercase = new JRadioButton("Uppercase"); rdbutLowercase = new JRadioButton("Lowercase"); // put the buttons into a single group ButtonGroup rgroup = new ButtonGroup(); rgroup.add(rdbutUppercase); rgroup.add(rdbutLowercase); RButHandler rhandler = new RButHandler(); rdbutUppercase.addItemListener(rhandler); rdbutLowercase.addItemListener(rhandler); // get the content pane Container c = mainFrame.getContentPane();

// set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(inLabel); c.add(tinField); c.add(rdbutUppercase); c.add(rdbutLowercase); c.add(exitButton); // create accelerator keys rdbutUppercase.setMnemonic('U'); rdbutLowercase.setMnemonic('L'); exitButton.setMnemonic('x'); mainFrame.setSize(300,150); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the event handlers ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler mainFrame.show(); }

// inner class for the Exit button event handler class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of inner class private class RButHandler implements ItemListener { public void itemStateChanged(ItemEvent e) { if (e.getSource() == rdbutUppercase) tinField.setText((tinField.getText()).toUpperCas e()); else if (e.getSource() == rdbutLowercase) tinField.setText((tinField.getText()).toLowerCas e()); tinField.repaint(); } } // end of inner class

public static void main(String args[]) {

new QuickTest(); object } } // end of class

// instantiate a GUI

Exercises 10.5 1. Enter, compile, and execute Program 10-8 on your computer. Students should enter and execute the specified program. 3a. Modify the program written for Exercise 2 so that the error message text field is disabled whenever the field is cleared of any message. import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton exitButton; private JTextField inputField; private JTextField messageField; private JLabel inputLabel;

public QuickTest() // a constructor { mainFrame = new JFrame("Input Validation"); // create all components exitButton = new JButton("Exit"); inputLabel = new JLabel("Enter an integer number:"); inputField = new JTextField(5); messageField = new JTextField(20); messageField.setEditable(false); InputFieldKeyHandler khandler = new InputFieldKeyHandler(); inputField.addKeyListener(khandler); // get the content pane Container c = mainFrame.getContentPane(); // set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(inputLabel); c.add(inputField); c.add(exitButton); c.add(messageField); // create accelerator keys exitButton.setMnemonic('x'); mainFrame.setSize(250,125); // define and register window event handler

mainFrame.addWindowListener(new WindowAdapter() public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the button event handler ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler } mainFrame.show(); {

// inner class for the exit button event handler class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of button listener class class InputFieldKeyHandler extends KeyAdapter { public void keyReleased(KeyEvent e) { int keyCode, length;

char keyChar = e.getKeyChar(); String inputGood; keyCode = e.getKeyCode(); keyChar = e.getKeyChar(); messageField.setText(""); error message // clear last

inputGood = inputField.getText(); // get the current string length = inputGood.length(); if (length > 0) messageField.setEditable(true); else messageField.setEditable(false); // process the last key pressed if (keyCode == KeyEvent.VK_ENTER) // shift focus { System.out.println("Enter key was pressed"); exitButton.grabFocus(); } else if (keyCode == KeyEvent.VK_BACK_SPACE) // erase last character { System.out.println("Backspace key was pressed"); length = inputGood.length(); inputGood = inputGood.substring(0, length);

System.out.println("length = " + length + " input = " + inputGood); } else if (keyChar < '0' || keyChar > '9') { messageField.setText(" Invalid Character Not Accepted"); inputGood = inputGood.substring(0, length-1); System.out.println( "length = " + (length-1) + " input = " + inputGood); } // display the validated string inputField.setText(inputGood); } } // end of key listener class public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } } // end of class

b. Modify the program written for Exercise 3a so that the error message field has a red background and a white foreground whenever an error message is written to it. import javax.swing.*;

import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton exitButton; private JTextField inputField; private JTextField messageField; private JLabel inputLabel; private Color defaultColor; public QuickTest() // a constructor { mainFrame = new JFrame("Input Validation"); // create all components exitButton = new JButton("Exit"); inputLabel = new JLabel("Enter an integer number:"); inputField = new JTextField(5); messageField = new JTextField(20); messageField.setEditable(false); defaultColor = messageField.getBackground(); InputFieldKeyHandler khandler = new InputFieldKeyHandler(); inputField.addKeyListener(khandler);

// get the content pane Container c = mainFrame.getContentPane(); // set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(inputLabel); c.add(inputField); c.add(exitButton); c.add(messageField); // create accelerator keys exitButton.setMnemonic('x'); mainFrame.setSize(250,125); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the button event handler ExitButtonHandler ehandler = new ExitButtonHandler(); exitButton.addActionListener(ehandler); register the handler mainFrame.show(); }

//

// inner class for the exit button event handler class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of button listener class class InputFieldKeyHandler extends KeyAdapter { public void keyReleased(KeyEvent e) { int keyCode, length; char keyChar = e.getKeyChar(); String inputGood; keyCode = e.getKeyCode(); keyChar = e.getKeyChar(); inputGood = inputField.getText(); // get the current string length = inputGood.length(); messageField.setBackground(defaultColor); messageField.setForeground(Color.black); messageField.setText(""); if (length > 0) messageField.setEnabled(true); else

messageField.setEnabled(false); // process the last key pressed if (keyCode == KeyEvent.VK_ENTER) // shift focus { System.out.println("Enter key was pressed"); exitButton.grabFocus(); } else if (keyCode == KeyEvent.VK_BACK_SPACE) // erase last character { System.out.println("Backspace key was pressed"); length = inputGood.length(); inputGood = inputGood.substring(0, length); System.out.println("length = " + length + " input = " + inputGood); } else if (keyChar < '0' || keyChar > '9') { messageField.setText(" Invalid Character Not Accepted"); inputGood = inputGood.substring(0, length-1); System.out.println( "length = " + (length-1) + " input = " + inputGood); messageField.setBackground(Color.red); messageField.setForeground(Color.white); }

// display the validated string inputField.setText(inputGood); } } // end of key listener class public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } } // end of class

5. Modify the KeyListener class developed in this section to verify that a valid real number is being input. Such a number consists of the digits 0 through 9 and at most a single decimal point. import javax.swing.*; import java.awt.event.*; import java.awt.Container; // need this to add controls import java.awt.*; // need this for layout manager public class QuickTest extends JFrame { private JFrame mainFrame; private JButton exitButton; private JTextField inputField; private JTextField messageField; private JLabel inputLabel;

private Color defaultColor; public QuickTest() // a constructor { mainFrame = new JFrame("Input Validation"); // create all components exitButton = new JButton("Exit"); inputLabel = new JLabel("Enter an integer number:"); inputField = new JTextField(5); messageField = new JTextField(20); messageField.setEditable(false); defaultColor = messageField.getBackground(); InputFieldKeyHandler khandler = new InputFieldKeyHandler(); inputField.addKeyListener(khandler); // get the content pane Container c = mainFrame.getContentPane(); // set the layout manager c.setLayout(new FlowLayout()); // add the components to the ContentPane c.add(inputLabel); c.add(inputField); c.add(exitButton); c.add(messageField); // create accelerator keys exitButton.setMnemonic('x');

mainFrame.setSize(250,125); // define and register window event handler mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create and register the button event handler ExitButtonHandler ehandler = new ExitButtonHandler(); // instantiate a handler exitButton.addActionListener(ehandler); // register the handler mainFrame.show(); } // inner class for the exit button event handler class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } // end of button listener class class InputFieldKeyHandler extends KeyAdapter {

public void keyReleased(KeyEvent e) { int keyCode, length; char keyChar = e.getKeyChar(); String inputGood; keyCode = e.getKeyCode(); keyChar = e.getKeyChar(); inputGood = inputField.getText(); // get the current string length = inputGood.length(); messageField.setBackground(defaultColor); messageField.setForeground(Color.black); messageField.setText(""); if (length > 0) messageField.setEnabled(true); else messageField.setEnabled(false); // process the last key pressed if (keyCode == KeyEvent.VK_ENTER) // shift focus { System.out.println("Enter key was pressed"); exitButton.grabFocus(); } else if (keyCode == KeyEvent.VK_BACK_SPACE) // erase last character {

System.out.println("Backspace key was pressed"); length = inputGood.length(); inputGood = inputGood.substring(0, length); System.out.println("length = " + length + " input = " + inputGood); } else if ( (keyChar < '0' || keyChar > '9') && keyChar != '.') { messageField.setText(" Invalid Character Not Accepted"); inputGood = inputGood.substring(0, length-1); System.out.println( "length = " + (length-1) + " input = " + inputGood); messageField.setBackground(Color.red); messageField.setForeground(Color.white); } else if (keyChar == '.') { if ( (inputField.getText()).substring(0,length1).indexOf(".") != -1) { messageField.setText(" Invalid Character Not Accepted"); inputGood = inputGood.substring(0, length-1); System.out.println("length = " + (length-1) + " input = " + inputGood);

messageField.setBackground(Color.red); messageField.setForeground(Color.white); } } // display the validated string inputField.setText(inputGood); } } // end of key listener class public static void main(String args[]) { new QuickTest(); // instantiate a GUI object } } // end of class

III. Sample Test Questions Chapter 10 1) The simplest layout manager that allows equal-sized components in a specific number of rows and columns is called _______ a) FlowLayout b) GridLayout c) BorderLayout d) CardLayout Answer: (B) 2) The layout manager that arranges up to 5 components in positions denoted, east, west, north, south and center is __________ a) FlowLayout b) GridLayout c) BorderLayout d) CardLayout Answer: (C) 3) What measurement units are used by the methods that affect component size? a) points b) dots c ) rectangles d) pixels

Answer: (D) 4) A table that contains all the relevant data about the components you will be adding to an interface is called a(n) ______________ a) properties table b) component table c) database d) interface table Answer: (A) 5) If you need to handle a series of buttons, you can either write individual handlers or a single, generic handler. If you use the second technique, you must call the _____ method to determine which button was pressed. a) checkButton() b) whichButton() c) getSource() d) getComponent() Answer: (C) 6) The object with ________ is the one that will be affected by pressing a key or clicking a mouse. a) priority b) focus

c) control d) status Answer: (B) 7) A(n) ________ can be used for both entering data and displaying results on a single line. a) field b) inField c) text field d) display field Answer: (C) 8) To change a font to bold, use the constant a) Font.BOLD b) font.bold c) FONTBOLD d) fontBold Answer: (A) 9) To set a component to black, use the color values: a) (255, 255, 255) b) (0, 0, 0) c) (128,128, 128) d) (192, 192, 192)

Answer: (B) 10) A JTextArea component can specify a) the total number of pixels for the text b) the total number of rows only c) the total number of columns only d) both the total number of rows and the total number of columns Answer: (D) 11) A FocusHandler class must provide methods called a) focusGained() only b) focusLost() only c) both a and b d) either a or b Answer: (C) 12) A yes or no option is best implemented using a a) check box b) radio buttons c) button d) label Answer: (A)

13) A group of mutually exclusive choices is best implemented using a a) check box group b) radio button group c) button group d) label group Answer: (B) 14) A properties table a) is a table that lists all of the components in a GUI and their associated listeners b) is a table of component attributes c) is a table of container attributes d) is a table of listeners Answer: (A) 15) In a BoxLayout a) components are added to the container from left to right and top to bottom b) all components are created equal in size and displayed in the requested number of rows and columns c) there can only be five components d) components are placed into either a single row or column Answer: (D)

I. OVERVIEW: Chapter 11 Additional Class Capabilities All of the classes that have been created provide the capability to declare, initialize, assign, manipulate, and display data members. In this chapter, we add to this basic set of capabilities. First, the this reference, introduced in Section 2.3 is expanded upon. Specifically, it is shown how to use the this reference to permit one class method to internally call another class method. This capability will permit us to add a number of useful methods to our Date class. Copy constructors are then introduced that have the ability to correctly deal with reference variables. Additionally, we will also see how to extend existing classes using Java's inheritance features. Finally, abstract classes are introduced; these are classes for which objects cannot be instantiated but that can be used as the basis for other classes. 11.1 Additional Class Features The this Reference Memberwise Assignment 11.2 Additional Applications Application 1: A Single-Class Gas Pump Simulation Application 2: A Multi-Class Gas Pump Simulation 11.3 Class Inheritance Polymorphism 11.4 Reference Variables as Class Members Shallow and Deep Copies Revisited 11.5 Common Programming Errors 11.6 Chapter Review

Potential Problem areas:

The this reference is confusing. Lots of OOD issues. Polymorphism takes a while to sink in. The section on reference variables can probably be postponed.

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 11.1 1. Enter and execute Program 11-1 on your computer. Students should enter and execute the specified program. 3. Write a program to test Program 11-1's dayOfWeek() method. In testing this method select at least seven different dates, where each date corresponds to a different day of the week. 12/30/03 is a Tuesday, and 12/31/03 is a Wednesday. public class QuickTest { public static void main(String[] args) { Date testDate = new Date(); testDate.setDate(1,1,2003); if (testDate.dayOfWeek() != 4) System.out.println(Failed Wednesday Test); testDate.setDate(2,1,2003); if (testDate.dayOfWeek() != 0) System.out.println(Failed Saturday Test); testDate.setDate(4,1,2003); if (testDate.dayOfWeek() != 3) System.out.println(Failed Tuesday Test);

testDate.setDate(5,1,2003); if (testDate.dayOfWeek() != 5) System.out.println(Failed Thursday Test); testDate.setDate(6,1,2003); if (testDate.dayOfWeek() != 1) System.out.println(Failed Sunday Test); testDate.setDate(8,1,2003); if (testDate.dayOfWeek() != 6) System.out.println(Failed Friday Test); testDate.setDate(9,1,2003); if (testDate.dayOfWeek() != 2) System.out.println(Failed Monday Test); } } 5. Construct a Date class method named isWeekEnd() that returns a boolean value of true if the Date object corresponds to a Saturday or Sunday, and a boolean value of false for all week days. You method should call the isWeekDay() method presented in this section. public boolean isWeekEnd() { if (this.dayOfWeek() == 0 || this.dayOfWeek() == 1) return true;

else return false;

7. Enter and execute Program 11-3 on your computer. Students should enter and execute the specified program. 9. Enter and run Program 11-5 on your computer.. Students should enter and execute the specified program. Exercises 11.2 1. Compile the Pump class provided in this section. Students should enter and compile the specified program 3. Enter and execute Program 11-7 on your computer. Students should enter and execute the specified program. 5. Using the Elevator class defined in Section 6.8 and defining a new class named Person, construct a simulation whereby a Person randomly arrives at any time from 1 to 10 minutes on any floor and calls the elevator. If the elevator is not on the floor that the person is on, it must move to that floor. Once inside the elevator the person can select any floor except the current one. Run the simulation for three randomly arriving people and have the simulation display the movement of the elevator. public class Person {

public Person() {} public int arrive() { return (1 + (int)(Math.random() * 10)); } public int startingFloor() { return (1 + (int)(Math.random() * 35)); } public int destinationFloor() { return (1 + (int)(Math.random() * 35)); }

public class ElevatorTest { public static void main(String[] args) { Elevator testElevator = new Elevator(); testElevator.setMaxFloor(35); int time = 0; int arrivalTime; int currentFloor; int destinationFloor; for (int i = 0; i < 3; i++) { arrivalTime = Person.arrive(); time += arrivalTime; System.out.println(

Person + i + arrives at + arrivalTime + minutes.); currentFloor = Person.startingFloor(); System.out.println(Person + i + is at floor + currentFloor); testElevator.request(currentFloor); do {

destinationFloor = Person.destinationFloor(); } while (destinationFloor == arrivalFloor); testElevator.request(destinationFloor); System.out.println(Person + i + requests floor + destinationFloor); } } }

Exercises 11.3 1. Define the following terms: a. inheritance Inheritance is the capability of deriving one class from another class. b. base class

The initial class that forms the basis for the derived class is referred to as either the base class. c. derived class A derived class is a completely new class that incorporates all of the variables and methods of its base class. d. simple inheritance In simple inheritance, each derived type has only one immediate base type. e. multiple inheritance In multiple inheritance, a derived type has two or more base types. f. class hierarchy Class hierarchies illustrate the hierarchy, or order, in which one class is derived from another. g. polymorphism Polymorphism permits the same method name to invoke one response in objects of a base class and another response in objects of a derived class. h. late binding The determination of which overloaded method is actually called is made at run time, when the call statement is encountered, and is based on the object making the call. i. dynamic binding This is ther same as late binding. j. early binding In contrast to late binding is early binding, in which the method that will actually be called is set at compile time.

3a. Describe the two methods Java provides for implementing polymorphism. Polymorhism is implemented through dynamic and static binding. The definitions of these two methids of polymorphism were given in problem 1. b. Which of the two methods listed in Exercise 3a. qualifies a language to be a true object-oriented language and why is this the case? Dynmic binding means that the object being operated on ultimately determines the appropriate method to be called, and is required for a language to implement true polymorphic behavior 5a. Rewrite Program 11-8 to create a derived class named Sphere from the base Circle class. The only additional class members of Sphere should be a constructor and a calcval() method that returns the volume of the sphere. (Note: volume = 4/3 radius3) public class Sphere extends Circle { // class method definition section public Sphere(double r) { super(r); } public double calcval() { return (4.0/3.0*3.14159*r*r*r;} public static void main(String[] args) {

Circle circleOne = new Circle(1); // create two Circle objects Circle circleTwo = new Circle(2); Sphere sphereOne = new Sphere(3); // create one Cylinder object System.out.println("The area of circleOne is " + circleOne.calcval()); System.out.println("The area of circletwo is " + circleTwo.calcval()); System.out.println("The volume of sphereOne is " + sphereOne.calcval()); } }

b. Include the class constructed for Exercise 5a in a working Java program. Have your program call all of the member methods in the Sphere class. See part a. 7a. Using the classes constructed for Exercise 6a, derive a class named Cylinder from the derived Circle class. The Cylinder class should have a constructor and a member method named area() that determines the surface area of the Cylinder. For this method, use the algorithm surface area = 2 r (l + r) , where r is the radius of the cylinder and l is the length. Assume Point has data members x and y. Assume Circle has data members radius and inherits x and y. Cylinder has data members length and inherits radius, x, and y. public class Cylinder extends Circle

{ double length; public Cylinder(double r, double l, double x, double y) { super(x,y,r); length = l; } public double Area() { return 2*3.14159*radius*(length+radius); } public static void main(String[] args) { Cylinder testCylinder = new Cylinder(10,15,0,0); System.out.println( The surface area of the test cylinder is: + testCylinder.Area()); } } b. Include the classes constructed for Exercise 7a in a working Java program. Have your program call all of the member methods in the Cylinder class. See part a. c. What do you think might be the result if the base class distance() method was called using two Cylinder objects?

A compiler error would result as the method does not exist for Cylinder input arguments. Exercises 11.4 1. Compile and execute Program 11-9 and run the program to verify its operation. Students should enter and execute the specified program. 3.a. Construct a class named Car that contains the following four data members: a double-precision variable named engineSize, a character variable named bodyStyle, an integer variable named colorCode, and a string named vinNum for a vehicle identification code. The method members should include a constructor and a display method that prints the engine size, body style, color code, and vehicle identification code. public class Car { double engineSize; char bodyStyle; int colorCode; String vinNum; vn) public car(double es, char bs, int cc, String { engineSize = es; bodyStyle = bs; colorCode = cc; vinNum = vn;

public void showAttributes() { System.out.println(Engine Size: + engineSize); System.out.println(Body Style: + bodyStyle); System.out.println(Color Code: + colorCode); System.out.println(Vehicle Identification Number: + vinNum); } } b. Include the class written for Exercise 3a in a working Java program that creates two Car objects and displays the object's values. public class QuickTest { public static void main(String[] args) { Car car0 = new Car(123,A,10,A3223); Car car1 = new Car(222,B,30,KJ323); System.out.println(Attributes for Car 0); car0.showAttributes(); System.out.println(); System.out.println(Attributes for Car car1.showAttributes();

1); } }

5. Using Program 11-9 as a start, write a program that creates five Book objects. The program should allow the user to enter the five book titles interactively and then display the entered titles. import javax.swing.*; public class Book { // class variable declaration section private String title; // class method definition section public Book(String booktitle) // constructor { title = booktitle; } public void showTitle() { System.out.println("The title is " + title); } public static void main(String[] args) { Book multiBooks[] = new Book[5]; String s1; for (int i = 0; i < 5; i++) { s1 = JOptionPane.showInputDialog(Enter Book Title + (i+1)); multiBooks[i] = new Book(s1); }

for (int i = 0; i < 5; i++) multiBooks[i].showTitle(); System.exit(0); } }

III. Sample Test Questions Chapter 11 1) For every object created from a class a) only one copy of each member method is created and used for every object b) a copy of each member method is created for each object c) a copy of a method is created for an object only after the first call to that method d) a copy of all methods is created for an object only after the first call to any method Answer: (A) 2) The keyword this refers to a) the object that is calling a method b) an object passed as a parameter to a method c) the Object class d) the Java virtual machine Answer: (A) 3) A shallow copy occurs when a) two reference variables locate distinct objects and both contain the same information b) two references refer to the same object c) one object inherits attributes from another object d) polymorphism occurs

Answer: (B) 4) A shallow copy occurs when a) two references variables locate distinct objects and both contain the same information b) two references refer to the same object c) one object inherits attributes from another object d) polymorphism occurs Answer: (A) 5) All of the following are synonymous except a) base b) parent c) super-class d) derived Answer: (D) 6) All of the following are synonymous except a) base b) child c) sub-class d) derived Answer: (A)

7) A class hierarchy describes a) the order that classes are used in a program b) the relative locations of objects using within source code c) the relative importance of objects in a program d) the order in which one class is derived from another Answer: (D) 8) In simple inheritance a) the Java code is always simple b) its implementation of a class with simple inheritance is always simple c) each derived type has only one base type d) each derived type has at least one base type Answer: (C) 9) In simple inheritance a) the Java code is always simple b) its implementation of a class with simple inheritance is always simple c) each derived type has only one base type d) a derived type has more than one base type Answer: (D) 10) By default, Java uses ____ binding in all method calls

a) run-time b) late c) dynamic d) all of the above Answer: (D) 11) ____ is the default binding behavior for all languages that do not support true polymorphic behavior a) late b) dynamic c) compile-time d) all of the above Answer: (C) 12) Which of the following would show a logical inheritance structure? a) cylinder inherits circle inherits point b) circle inherits cylinder inherits point c) point inherits circle inherits cylinder d) sphere inherits cylinder inherits circle inherits point Answer: (A) 13) Which of the following shows a logical inheritance structure? a) colored-sphere inherits sphere inherits point inherits circle

b) sphere inherits colored-sphere inherits circle inherits point c) colored-sphere inherits sphere inherits circle inherits point d) none of the above Answer: (C) 14) A true polymorphic language implements a) static-binding b) dynamic-binding c) compile time binding d) none of the above Answer: (B) 15) A class can be declared abstract using the following statement a) abstract public class Test b) class abstract public Test c) either a or b d) none of the above Answer: (A)

I. OVERVIEW: Chapter 12 File I/O The data for the programs discussed so far have either been assigned internally within the programs or entered interactively during program execution. This type of data entry is fine for small amounts of data. This chapter shows how to store data outside a program using Java's object-oriented capabilities. This external data storage permits a program to use the data without the user having to re-create them interactively each time the program is executed. This also provides the basis for sharing data between programs so that the data output by one program can be input directly to another program. 12.1 Files and Streams 12.2 Writing and Reading Character-Based Files 12.3 Writing and Reading Byte-Based Files 12.4 Application: Creating and Using a Holiday Table 12.5 Random Access Files 12.6 The File Class 12.7 Common Programming Errors 12.8 Chapter Review 12.9 Chapter Supplement: Character and Byte File Storage

Potential Problem areas: This chapter should not pose any serious problems for the students, other than the concept of buffering.

II. ANSWERS TO ODD-NUMBERED EXERCISES Exercises 12.1 1. Using the reference manuals provided with your computer's operating system, determine the maximum number of characters that can be used to name a file for storage by your computer system. The answer to this question will depend upon the users operating system. 3a. What are the basic input and output stream classes used for constructing input and output stream objects for use with a character-based file? FileReader and FileWriter classes 3b. What are the basic input and output stream classes used for constructing input and output stream objects for use with a bytebased file? FileInputStream class and FileOutputStream classes 5. Write suitable Java statements to create individual output streams named fw for each of the following character-based files: outData.txt, prices.txt, coupons.dat, and results.mem. FileWriter FileWriter FileWriter FileWriter fw fw fw fw = = = = new new new new FileWriter("outData.txt"); FileWriter("prices.txt"); FileWriter("coupons.dat"); FileWriter("results.mem");

7. Write suitable Java statements to create individual output streams named for for each of the following byte-based files: outData, distance, rates.dat, and coupons.dat. FileOutputStream fos = new FileOutputStream(outData); FileOutputStream fos = new FileOutputStream(distance); FileOutputStream fos = new FileOutputStream(rates.dat); FileOutputStream fos = new FileOutputStream(coupons.dat); 9. Write close() statements for each of the file stream object created in Exercise 8. memo.close(); letter.close(); coups.close(); yield.close(); inFile.close(); outFile.close();

Exercises 12.2 1. Enter and execute Program 12-1 on your computer. Students should enter and execute the specified program. 3. Modify Program 12-2 to permit the user to interactively enter the name of a file.

import java.io.*; import javax.swing.*; public class WriteTextPrices2 { public static void main(String[] args) throws java.io.IOException { String fileName = JOptionPane.showInputDialog(Enter filename); // set up the basic output stream FileWriter fw = new FileWriter(fileName); // buffer it for faster output BufferedWriter bw = new BufferedWriter(fw); // this provides a set of useful methods PrintWriter pw = new PrintWriter(bw); pw.println("Mats 39.95"); pw.println("Bulbs 3.22"); pw.println("Fuses 1.08"); } } 5. Enter and execute Program 12-4 on your computer. Students should enter and execute the specified program. 7. Enter and execute Program 12-6 on your computer. Students should enter and execute the specified program. pw.close();

7b. Verify that the catch block in Program 12-6 is correctly executed when the info.txt file has been deleted and is not available for input. Students should verify the program. 9a. Write a Java program that accepts five lines of text from the keyboard and writes each line to a file named text.dat. import java.io.*; import javax.swing.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String filename = "text.dat"; // set up the basic output stream FileWriter fw = new FileWriter(filename); // buffer it for faster output BufferedWriter bw = new BufferedWriter(fw); // this provides a set of useful methods PrintWriter pw = new PrintWriter(bw); for (int i = 0; i < 5; i++) { System.out.print("Enter line " + (i+1) + ": "); pw.println(in.readLine()); } pw.close();

} } 9b. Modify Program 12-3 to read and display the data stored in the text.dat file created in Exercise 9a. import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { String fileName = "text.dat"; int i; String inLine; // set up the basic input stream FileReader fr = new FileReader(fileName); // buffer the input stream BufferedReader br = new BufferedReader(fr); // read and display five lines for(i = 0; i < 5; i++) { inLine = br.readLine(); // read a // display

line

System.out.println(inLine); the line }

br.close(); } 11. Write, compile, and run a Java program that writes the four real numbers 92.65, 88.72, 77.46, and 82.93 to a text file named results.txt. After writing the data to the file your program should read the data from the file, determine the average of the four numbers read, and display the average. Verify the output produced by your program by manually calculating the average of the four input numbers. public class QuickTest { public static void main(String[] args) throws java.io.IOException { // Write Data to File // FileWriter fw = new FileWriter("results.txt"); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); double numberList[] = {92.65,88.72,77.46,82.93}; double numberList2[] = new double[4]; for (int i = 0; i < 4; i++) pw.println(String.valueOf(numberList[i])); pw.close();

// Read Data Back // FileReader fr = new FileReader("results.txt"); BufferedReader br = new BufferedReader(fr); double total = 0; for (int i = 0; i < 4; i++) { numberList2[i] = Double.parseDouble(br.readLine()); total += numberList2[i]; } br.close(); System.out.println("The average of the numbers is: " + total/4); } } 13a. Write, compile, and run a Java program that creates a text file named grades.txt and writes the following five lines of data to the file: 90.3 85.3 93.2 82.4 93.5 92.7 90.5 88.4 95.6 80.2 90.3 87.3 93.8 78.2 92.9 99.8 90.8 75.6 90.0 94.4

import java.io.*; public class QuickTest {

public static void main(String[] args) throws java.io.IOException { FileWriter fw = new FileWriter("grades.txt"); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); String message = ""; double numberList[][] = {{90.3, 90.3, 99.8}, {85.3, 87.3, 90.8}, {93.2, 93.8, 75.6}, {82.4, 78.2, 90.0}, {93.5, 92.9, 94.4}}; +) 92.7, 90.5, 88.4, 95.6, 80.2,

for (int i = 0; i < numberList.length; i+ { for (int j = 0; j < numberList[i].length; j++) pw.print(numberList[i][j] + ); pw.println(); } } } pw.close();

b. Using the data in the grades.txt file created in Exercise 13a, write, compile, and run a Java program that reads each line in the file, computes the average for each line, and displays the average. import java.io.*; import java.util.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { FileReader fr = new FileReader("grades.txt"); BufferedReader br = new BufferedReader(fr); StringTokenizer st; double numberList[][] = new double[5][4]; double total; for (int i = 0; i < 5; i++) { total = 0; st = new StringTokenizer(br.readLine()); for (int j = 0; j < 4; j++) { numberList[i][j] = Double.parseDouble(st.nextToken()); total += numberList[i][j]; }

System.out.println("Average of Row " + i + ": " + total/4); } br.close(); } }

15a. A file named polar.txt contains the polar coordinates needed in a graphics program. Currently this file contains the following data: Distance Angle (inches) (degrees) ----------------2.0 45.0 6.0 30.0 10.0 45.0 4.0 60.0 13.0 55.0 8.0 15.0 Write a Java program to create the data in this file on your computer system (without the header lines). import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { FileWriter fw = new FileWriter("polar.txt");

BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); String message = ""; double numberList[][] = {{ 2.0, { 6.0, {10.0, { 4.0, {13.0, { 8.0, +) 45.0}, 30.0}, 45.0}, 60.0}, 55.0}, 15.0}};

for (int i = 0; i < numberList.length; i+ {

for (int j = 0; j < numberList[i].length; j++) pw.print(numberList[i][j] + ); pw.println(); } pw.close(); } }

b. Using the polar.txt file created in Exercise 15a, write a Java program that reads this file and creates a second file named xycord.dat. The entries in the new file should contain the rectangular coordinates corresponding to the polar coordinates in the polar.txt file. Polar coordinates are converted to rectangular coordinates using the equations

x = r cos y = r sin where r is the distance coordinate and is the radian equivalent of the angle coordinate in the polar.txt file. import java.io.*; import java.util.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { FileReader fr = new FileReader("polar.txt"); BufferedReader br = new BufferedReader(fr); StringTokenizer st; PrintWriter pw = new PrintWriter( new BufferedWriter(new FileWriter("xycoord.dat"))); double r, theta; for (int i = 0; i < 3; i++) { st = new StringToken(br.readLine()); r = Double.parseDouble(st.nextToken()); theta = Double.parseDouble(st.nextToken()); pw.print(Xcoord: + r*Math.cos(theta*Math.PI/180) + " "); pw.println(Ycoord: + r*Math.sin(theta*Math.PI/180) + "");

} br.close(); pw.close();

} }

17. Enter the data shown in Figure 12-5 into a character-based file named info.txt. Students should enter the data as specified. 19. Rewrite Program 12-6 so that it uses buffered input and output stream in place of the unbuffered FileReader and FileWriter streams. import java.io.*; public class QuickTest { static final int EOF = 1; public static void main(String[] args) throws java.io.IOException { try //this block tries to open the files and create appropriate stream { // open a basic input stream BufferedReader br = new BufferedReader(new FileReader("info.txt")); // open a basic output stream BufferedWriter bw = new BufferedWriter(new FileWriter("backup.txt"));

int c; while ((c = br.read()) != EOF) bw.write(c); br.close(); bw.close(); } catch (FileNotFoundException e) { System.out.println("One of the required files, \ninfo.txt or " + "backup.txt, was not successfully opened."); System.exit(0); } } } 21. Modify Program 12-6 so that the input file is read using a readLine() method and the output file is written using a println() method. (Hint: You will have to add processing streams to the existing FileReader and FileWriter streams. See Exercise 19.) import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { try //this block tries to open the files and create appropriate stream {

// open a basic input stream BufferedReader br = new BufferedReader(new FileReader("info.txt")); // open a basic output stream PrintWriter pw = new PrintWriter( new BufferedWriter(new FileWriter("backup.txt"))); String s1; s1 = br.readLine(); while (s1 != null) pw.println(s1); br.close(); pw.close(); } catch (FileNotFoundException e) { System.out.println("One of the required files, \ninfo.txt or " + "backup.txt, was not successfully opened."); System.exit(0); } } } Exercises 12.3 1. Enter and execute Program 12-7 on your computer. Once the prices.dat file has been written, execute Program 12-7 a second time to verify that it does not overwrite the existing file without your permission.

Students should enter and execute the program according to directions. 3. Write, compile, and run a Java program that writes the numbers 92.65, 88.72, 77.46, and 82.93 as double-precision values to a bytebased file named results.dat. After writing the data to the file your program should read the data from the file, determine the average of the four numbers read, and display the average. Verify the output produced by your program by manually calculating the average of the four input numbers. import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("results.dat"))); double numberList[] = {92.65,88.72,77.46,82.93}; double numberList2[] = new double[4]; for (int i = 0; i < 4; i++) dos.writeDouble(numberList[i]); dos.close(); DataInputStream dis = new DataInputStream(

new BufferedInputStream(new FileInputStream("results.dat"))); double total = 0; for (int i = 0; i < 4; i++) { numberList2[i] = dis.readDouble(); total += numberList2[i]; } dis.close(); System.out.println("The average of the numbers is: " + total/4); } } 5a. Write, compile, and run a Java program that creates a bytebased file named grades.bin and writes the following data to the file: 90.3 85.3 93.2 82.4 93.5 92.7 90.5 88.4 95.6 80.2 90.3 87.3 93.8 78.2 92.9 99.8 90.8 75.6 90.0 94.4

import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException {

DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("grades.bin"))); double numberList[][] = {{90.3, 90.3, 99.8}, {85.3, 87.3, 90.8}, {93.2, 93.8, 75.6}, {82.4, 78.2, 90.0}, {93.5, 92.9, 94.4}}; 92.7, 90.5, 88.4, 95.6, 80.2,

for (int i = 0; i < 5; i++) for (int j = 0; j < 4; j++) dos.writeDouble(numberList[i][j]); dos.close(); } }

b. Using the data in the grades.bin file created in Exercise 5a write, compile, and run a Java program that reads, computes, and displays the average of each group of four grades. import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException {

DataInputStream dis = new DataInputStream( new BufferedInputStream(new FileInputStream("grades.bin"))); double numberList[][] = new double[5][4]; double total; for (int i = 0; i < 5; i++) { total = 0; for (int j = 0; j < 4; j++) { numberList[i][j] = dis.readDouble(); total += numberList[i][j]; } System.out.println("Average of Row " + i + ": " + total/4); } dis.close(); } }

7a. A byte-based file named polar.dat contains the polar coordinates needed in a graphics program. Currently, this file contains the following data: DISTANCE ANGLE (INCHES) (DEGREES) ----------------2.0 45.0 6.0 30.0 10.0 45.0

4.0 13.0 8.0

60.0 55.0 15.0

Write a Java program to create the data in this file on your computer system (without the header lines). import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("polar.bin"))); double numberList[][] = {{ 2.0, { 6.0, {10.0, { 4.0, {13.0, { 8.0, 45.0}, 30.0}, 45.0}, 60.0}, 55.0}, 15.0}};

for (int i = 0; i < 6; i++) for (int j = 0; j < 2; j++) dos.writeDouble(numberList[i][j]); dos.close(); } }

b. Using the polar.dat file created in Exercise 7a, write a Java program that reads this file and creates a second byte-based file named xycord.dat. The entries in the new file should contain the rectangular coordinates corresponding to the polar coordinates in the polar.dat file. Polar coordinates can be converted to rectangular coordinates using the equations x = r cos y = r sin where r is the distance coordinate and is the radian equivalent of the angle coordinate in the polar.dat file. public class QuickTest { public static void main(String[] args) throws java.io.IOException { DataInputStream dis = new DataInputStream( new BufferedInputStream(new FileInputStream("polar.bin"))); DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("xycoord.bin"))); double r, theta; for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) { r = dis.readDouble(); theta = dis.readDouble();

dos.writeDouble(r*Math.cos(theta*Math.PI/180)); dos.writeDouble(r*Math.sin(theta*Math.PI/180)); } dis.close(); dos.close();

} }

Exercises 12.4 1. Explain why the class name Date is required in Program 12-9's call to getHolidays(). The static method is being called from outside the Data class and therefore one requires the class name to preceed the method name. 3. Enter, compile, and execute Program 12-9. Students should enter and execute the desired program. 5. Execute and execute Program 12-11 on your computer. Do successfully accomplish this you will have to complete Exercise 4. Students should enter and execute the specified program. 7. Program 12-9's getHolidays() method is actually one of three methods typically used in creating, maintaining, and using a list of constants stored in a file. As such, this method can be defined in its own class, which would contain all of the necessary file related methods. For this exercise, place the getHolidays() method within a class named Holidays, and make all of the necessary adjustments to

the Date class to ensure that the isEquals() method works correctly when Program 12-11 is executed. import java.io.*; public class Holidays { public static ArrayList hTable = new ArrayList(); public static void getHolidays() throws java.io.IOException { String fileName = "Holidays.txt"; String inline; int mm, dd, yy; Date a = new Date(); // create a single Date object try // this block tries to open the file and create the input streams { // set up the basic input streams FileReader fr = new FileReader(fileName); // buffer the input stream BufferedReader br = new BufferedReader(fr); null) while ( (inline = br.readLine()) != {

StringTokenizer parser = new StringTokenizer(inline, "/ \t\n\r,");

mm = Integer.parseInt(parser.nextToken()); dd = Integer.parseInt(parser.nextToken()); yy = Integer.parseInt(parser.nextToken()); a.setDate(mm, dd, yy); //convert to a date hTable.add(a); // add the holiday into the array } // System.out.println("The Holiday file was successfully read and stored."); br.close(); hTable.trimToSize(); // remove any blank records } catch (FileNotFoundException e) { System.out.println("The file " + fileName + " was not successfully opened." + "\nPlease check that the file currently exists."); System.exit(0); } } } import java.text.*; import java.io.*; Holiday File import java.util.*; public class Date // needed for formatting // needed to read in // needed for ArrayList

{ // class variable declaration section private int month; private int day; private int year; // class method definition section public Date() // default constructor { setDate(7, 4, 2005); } public Date(int mm, int dd, int yyyy) overloaded constructor { setDate(mm, dd, yyyy); } public void setDate(int mm, int dd, int yyyy) // mutator { month = mm; day = dd; year = yyyy; } public void showDate() // modified accessor { DecimalFormat df = new DecimalFormat("00"); System.out.println(df.format(month) + '/' + df.format(day) + '/' //

+ df.format(year % 100)); // extract the last 2 year digits } public boolean isEqual(Date secDate) { int mm = secDate.getMonth(); int dd = secDate.getDay(); int yy = secDate.getYear(); if (month == mm && day == dd && year == yy) return true; else return false; } // accessors public int getMonth() {return month;} public int getDay() {return day;} public int getYear() {return year;} public boolean isHoliday() throws java.io.IOException { int i, mm, dd, yy; Object holiday; // read the Holiday file if the Holiday table is empty if ((Holidays.hTable).isEmpty()) Holidays.getHolidays(); Date // search the Holiday table for the given for(i = 0; i < Holidays.hTable.size(); i++)

{ holiday = (Holidays.hTable).get(i); retrieve a holiday if (isEqual((Date)holiday)) return true; } return false; } } //

9a. A file named Polar.dat contains the polar coordinates needed in a graphics program. Currently, this file contains the following data: Distance (inches) -------2 6 10 4 12 8 Angle (degrees) ---------45 30 45 60 55 15

Write a Java program to create this file on your computer system. See problem 7a. b. Using the Polar.dat file created in Exercise 9a, write a Java program that accepts distance and angle data from the user and adds the data to the end of the file.

import java.io.*; import javax.swing.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("polar.bin",true))); double radius; double angle; String s1; try { while (1==1) { s1 = JOptionPane.showInputDialog("Enter additional radius " + "(Enter invalid number to quit)"); radius = Double.parseDouble(s1); s1 = JOptionPane.showInputDialog("Enter additional angle"); angle = Double.parseDouble(s1); dos.writeDouble(radius); dos.writeDouble(angle);

} } catch (NumberFormatException e) { dos.close(); System.exit(0); }

} }

c. Using the Polar.dat file created in Exercise 9a, write a Java program that reads this file and creates a second file named XYcoord.dat. The entries in the new file should contain the rectangular coordinates corresponding to the polar coordinates in the Polar.dat file. Polar coordinates are converted to rectangular coordinates using the equations: x = r cos() y = r sin() where r is the distance coordinate and is the radian equivalent of the angle coordinate in the Polar.dat file. See problem 7b. 11. Pollen count readings, which are taken from August through September in the northeastern region of the United states, measure the number of ragweed pollen grains in the air. Pollen counts in the range of 10 to 200 grains per cubic meter of air are typical during this time of year. Pollen counts above 10 begin to affect a small percentage of hay fever sufferers, counts in the range of 30 to 40 will

noticeably bother approximately 30 percent of hay fever sufferers, anc counts between 40 and 50 adversely affect more than 60 percent of all hay fever sufferers. Write a Java program that updates a file containing the 10 most recent pollen counts. As a new count is obtained, it is to be added to the end of the file, and the oldest count, which is the first value in the file, is to be deleted. Additionally, the averages of the old and new files' data must be calculated and displayed. To test your program first create a file named Pollen.dat, that contains the following pollen count data: 30, 60, 40, 80, 90, 120, 150, 130, 160, 170. Here the first value, 30, corresponds to the oldest pollen count, and the last value, 170, corresponds to the most recent pollen count. The pseudocode for the file update program is: Display a message indicating what the program does Request the name of the data file Request a new pollen count reading Open the data file Do for ten data items Read a value into an array Add the value to a total EndDo Calculate and display the old ten-day average Calculate and display the new ten-day average Write the nine most recent pollen counts from the array to the file Write the new pollen count to the file Close the file import javax.swing.*; import java.io.*; public class PollenList {

public static void updatePollenList() throws java.io.IOException { System.out.println("This program keeps track of pollen counts"); String filename = JOptionPane.showInputDialog( "Enter the name of the data file"); String s1 = JOptionPane.showInputDialog("Enter new pollen reading"); double reading = Double.parseDouble(s1); double total = 0; double pollenCounts[] = new double[10]; BufferedReader br = new BufferedReader(new FileReader(filename)); for (int i = 0; i < 10; i++) { pollenCounts[i] = Double.parseDouble(br.readLine()); total += pollenCounts[i]; } System.out.println("The old pollen count average was " + total/10); System.out.println("The new pollen count average is " + ((total pollenCounts[0]+reading)/10));

br.close(); PrintWriter pr = new PrintWriter( new BufferedWriter(new FileWriter(filename))); for (int i = 1; i < 10; i++) pr.println("" + pollenCounts[i]); pr.println("" + reading); pr.close(); } }

13a. Write a Java program to create a data file containing the following information: Cumulative Student Student Course Grade Point ID Number Name Credits Average (GPA) --------------------------------------2333021 Bokow, R. 48 4.0 2574063 Fustil, D. 12 1.8 2663628 Kingsley, M. 36 3.5 public class QuickTest { public static void main(String[] args) { PrintWriter pw = new PrintWriter( new BufferedWriter(new FileWriter(studends.dat));

pw.println(2333021 Bokow, R. 48, 4.0); pw.println(2574063 Fustil, D. 12, 1.8); pw.println(2663628 Kingsley, M. 36 3.5); } } b. Using the file created in Exercise 13a as a master file and the file created in Exercise 12b as a transactions file, write a file update program to create an updated master file. import java.io.*; import java.util.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { BufferedReader brMain = new BufferedReader(new FileReader("main.txt")); BufferedReader brTrans = new BufferedReader(new FileReader("trans.txt")); PrintWriter pw = new PrintWriter( new BufferedWriter(new FileWriter("updated.txt"))); String transLine, mainLine; StringTokenizer stMain, stTrans; pw.close();

String idNumber; String name; int numCredits, additional; double gpa; int grade; mainLine = brMain.readLine(); while (mainLine != null) { stMain = new StringTokenizer(mainLine); idNumber = stMain.nextToken(); name = stMain.nextToken() + " " + stMain.nextToken(); numCredits = Integer.parseInt(stMain.nextToken()); gpa = Double.parseDouble(stMain.nextToken()); brTrans.mark(1000); transLine = brTrans.readLine(); while (transLine != null) { stTrans = new StringTokenizer(transLine); if (stTrans.nextToken().equals(idNumber)) { // Discard the name and course number stTrans.nextToken();

stTrans.nextToken(); stTrans.nextToken(); additional = Integer.parseInt(stTrans.nextToken()); grade = 'F' stTrans.nextToken().charAt(0)-1; gpa = (gpa*numCredits + additional*grade)/(numCredits + additional); numCredits += additional; } transLine = brTrans.readLine(); } brTrans.reset(); pw.println(idNumber + " " + name + " " + numCredits + " " + gpa); mainLine = brMain.readLine(); } pw.close(); brMain.close(); brTrans.close(); } }

Exercises 12.5

1. Either by copying the file from the Web site associated with this text or writing a Java program, create a byte-based file named test.dat that stores the following four letters as individual characters (see Figure 12-12): Next The file can be created in Java using either DataOutputStream or RandomAccessFile methods. Students may copy the appropriate file from the web site. 3. Assume that a text editor created the file test.dat for Exercise 1, or the file was created as a text-based file using methods from the PrintWriter class. In this case: a. How would the stored characters differ from those shown in Figure 12-12? In the byte based file, the two byte unicode representation of the characters would be stored. In the character based file, the ascii code of each character would be stored, and as a result, can be viewed in a text editor. b. What modification would you have to make to Program 12-12 to read and display the characters in the file? You need to take into account the fact that each character is stored as only a byte.

5. Write a method named findChars() that returns the total number of characters in a byte-based file. Assume that the file consists of character data only. public static int findChars(filename) { RandomAccessFile raf = new RandomAccessFile(fileName, "r"); return raf.length() / 8; // get length of the file } 7. Enter and execute Program 12-13 on your computer. Students should enter and execute the specified program. 9. Enter and execute Program 12-15 on your computer. Students should enter and execute the specified program. Exercises 12.6 1a. Describe the difference between numbers stored in a characterbased file and numbers stored in byte-based file. In a byte based file, numbers are stored according to their data type. In a character based file, numbers are stored as an array of ASCII characters such that each digit in the number is represented by an ASCII code. b. Describe the difference between letters stored in a characterbased file and letters stored in a byte-based file. In a byte based file, letters are stored as 2-byte unicode values. In character based files, letters are stored as one-byte ascii codes.

3. Modify Program 12-16 so that the file name can be interactively entered by user. import java.io.*; import javax.swing.*; public class CheckFile { public static void main(String[] args) throws java.io.IOException { fileName = JOptionPane.showInputDialog(Enter the filename); String nextName = "backup.dat"; File inFile = new File(fileName); File newName = new File(nextName); if (inFile.exists()) { System.out.println("The file " + fileName + " exists"); // check the type of file if (inFile.isDirectory()) System.out.println(" This is a directory"); else if (inFile.isFile()) System.out.println(" This is a regular file"); // check if file is readable if (inFile.canRead())

System.out.println(" read"); else System.out.println(" readable");

The file can be The file is not

// check if file is writeable if (inFile.canWrite()) System.out.println(" The file can be written to"); else System.out.println(" The file is not writeable"); // report the file's length System.out.println("The file length is " + inFile.length() + " bytes."); // report the file's directory path System.out.println("The pathname of this file's parent is " + inFile.getParent()); // rename the file inFile.renameTo(newName); System.out.println("The file has been renamed " + newName); System.out.println("The full pathname for this file is " + newName.getAbsolutePath()); } else System.out.println("The file " + fileName + " does not exist.");

} } 5. Enter and execute Program 12-17 on your computer. Students should enter and execute the specified program. 7. Modify Program 12-1 to include the input file check provided by Program 12-18. import java.io.*; public class WriteTextPrices { public static void main(String[] args) throws java.io.IOException { File outFile = new File(prices.txt); // check that the file does not already exist if (outFile.exists()) { System.out.println("The file " + fileName + "currently exists."); System.out.print("Are you sure you want to write to it? Enter y or n:"); response = (char) System.in.read(); if (response == 'n') System.exit(0); } // set up the basic output stream

FileWriter fw = new FileWriter("prices.txt"); // buffer it for faster output BufferedWriter bw = new BufferedWriter(fw); // this provides a set of useful methods PrintWriter pw = new PrintWriter(bw); pw.println("Mats 39.95"); pw.println("Bulbs 3.22"); pw.println("Fuses 1.08"); } } pw.close();

III. Sample Test Questions Chapter 12 1) A data file a) is a collection of data stored under a common name in main memory b) is the same as a stream object c) is a collection of data stored under a common name on a device other than main memory d) never contains program code Answer: (C) 2) An external file name a) is created with the Java keyword extern b) is the name of a file as it is known to the operating system c) is always 1 to 8 characters in length d) should be kept as simple as possible Answer: (B) 3) To check the status of a file, declare a variable of type a) file b) FILE c) fileCheck d) File Answer: (D)

4) After opening a file it is very important to verify that the connection to the file object has been established. This is accomplished by checking if the a) exits() method returns true b) file name is null c) first character in the file is null d) getName() method returns a valid name Answer: (A)

5) After you have finished reading from or writing to a file, you should call the ____ method. a) stop() b) close() c) exit() d) end() Answer: (B) 6) Store the name of a file in a program required a(n) a) File variable b) String variable c) access variable d) name variable Answer: (B)

7) To write to a byte-based file, use the ____ class. a) FileOutputStream b) ByteOutputStream c) FileByteStream d) FileWriter Answer: (A) 8) A FileOutputStream object opened with access mode true a) can only be used for input b) must already exit c) can be used for either input or output d) can be used for appending to an existing file Answer: (D) 9) When the end of a stream has been detected, the read() method returns a) 0 b) 1 c) 2 d) -1 Answer: (D) 10) To force an output stream to output its contents, use the ____ method

a) out() b) flush() c) empty() d) display() Answer: (B) 11) A random access file allows characters to be accessed a) internally b) randomly, as with a psuedorandom number generator c) sequentially d) directly, without searching through all previous characters Answer: (D) 12) When using random access files, the seek() method a) moves to the offset position indicated b) searches for a particular piece of data c) searches for an appropriate place to insert new data d) checks whether the file has been correctly opened Answer: (A) 13) The FileReader class is used for a) reading byte-based files b) reading character based files c) reading program files d) reading data from an external device

Answer: (B)

14) The DataOutputStream class a) Supplies additional output methods and typically uses either a FileOutputStream object or BufferedOutputStream object argument. b) provides buffering which improves performance and supplies character-bycharacter and line-by-line output. It typically uses a FileOutputStream object argument. c) provides a basic stream used for byte-based output. It also supplies character-bycharacter output d) is none of the above Answer: (A) 15) The seek() method is used for a) finding a string within a file b) finding the end of a file c) finding a specified value in a file d) moving to a certain location in a file Answer: (D)

I. OVERVIEW: Chapter 13 Collections: List Creation and Maintenance As shown in Section 8.5, Java provides an ArrayList class for storing, ordering, and retrieving objects that permits the list to expand or contract, as objects are added or removed from the list. This chapter presents three additional types of list maintenance classes, all of which are supported by the same Collection Framework set of classes from which ArrayLists are derived. All of the three new classes are based on the concept of a linked list, which is explained in Section 13.2.The first class, named LinkedList, permits direct construction of a classical linked list. The remaining types, Stacks and Queues, are specialized forms of a linked list, which can also be constructed using the Collection Framework classes. Because the Collection Framework forms the basis for all of these new list types, a review of the Framework is provided at the end of Section 13.1. 13.1 Introduction The Collection Framework Parallel Arrays as Records 13.2 Linked Lists Constructing Your Own Linked List LinkedList Class Implementation 13.3 Stacks Stack Class Implementation 13.4 Queues LinkedList Class Implementation 13.5 Common Programming Errors 13.6 Chapter Review

Potential Problem areas:

At this point, the Collection Framework may seem pretty straightforward to the students. They will no doubt be relieved that the low-level programming details of the various container classes are handled for them.

a. Exercises 13.1

II. ANSWERS TO ODD-NUMBERED EXERCISES

1. Define the following terms: a. container Containers are generic list structures that can be used to store, maintain, and retrieve individual records. b. collection A collection is a group of zero or more elements . c. Collection Framework The Collection Framework is a collection of classes providing a number of generic list structures, called containers. d. data field The individual data items within a record are formally referred to as data fields. e. data structure A list must provide a means for accessing individual elements. In an array this ability is provided by the position of each element in the array, which is designated using an integer index value. More formally, any data type that provides this minimum set of capabilities is referred to as a data structure f. list A list is a homogeneous data structure. g. parallel arrays Parallel arrays are several arrays with the same number of elements that work in tandem to produce data.

h. record A list is a heterogenous data structure 3. What container types can be created from the List class? ArrayList LinkedList Vector Stack

5. For each of the following, define a single class named Student that contains only a data declaration section and can be used to create the following records. Each part (a through e) should have its own Student class. a. a student record containing a student identification number, the number of credits completed, and a cumulative grade point average public class Student { int idNumber; int numCredits; double gpa; } b. a student record capable of holding a student's name, date of birth, number of credits completed, and cumulative grade point average public class Student { String name; Date birthday;

int numCredits; double gpa;

c. a mailing list containing a title field, last name field, first name field, two street address fields, a city field, a state field, and a zip code field. public class Contact { String title; String lastName; String firstName; String address1; String address2; String city; String state; int zipCode; } d. a stock record containing the stock's name, the price of the stock, and the date of purchase public class stock { String name; double price; Date purchaseDate; } e. an inventory record containing an integer part number, a String part description, an integer number of parts in inventory, and an integer re-order value.

public class part { int partNumber; String description; int numAvailable; int reorderValue; } 7a. Write a Java program that prompts a user to input the current month, day, and year. Store the data entered in a suitably defined object and display the date in an appropriate manner. The following program uses the Date class implemented throughout this book. For multiple date entries, one merely needs to loop through the input dialog and place each object into a list. import javax.swing.*; public class QuickTest { public static void main(String[] args) { int month, day, year; Date userEntry; month = Integer.parseInt(JOptionPane.showInputDialog(En ter month)); day = Integer.parseInt(JOptionPane.showInputDialog(En ter day)); year = Integer.parseInt(JOptionPane.showInputDialog(En ter year));

} }

userEntry = new Date(month,day,year); userEntry.showDate();

b. Modify the program written in Exercise 7a to use a record that accepts the current time in hours, minutes, and seconds import javax.swing.*; import java.util.*; class Time { int hours; int minutes; int seconds; Time(int h, int m, int s) { hours = h; minutes = m; seconds = s; } } public class QuickTest { public static void main(String[] args) { int hours, minutes, seconds; String s1; Date userEntry;

hours = Integer.parseInt(JOptionPane.showInputDialog(En ter the hour)); minutes = Integer.parseInt(JOptionPane.showInputDialog(En ter the minute)); seconds = Integer.parseInt(JOptionPane.showInputDialog(En ter the second)); userEntry = new Time(hours,minutes,seconds); userEntry.showDate(); } } 9. Define a class capable of creating records for various screw types held in inventory. Each record should contain a field for an integer inventory number, double-precision screw length, double-precision diameter, kind of head (Phillips or standard slot), material (steel, brass, other), and cost. Data declaration section is shown only. public class Screw { private int inventoryNumber; private double screwLength; private double diameter; private String head; private String material; private double cost; } Exercises 13.2

1. Modify Program 13-4 to prompt the user for a name. Have the program search the existing list for the entered name. If the name is in the list, display the corresponding phone number; otherwise display this message: The name is not in the current phone directory. import java.util.*; import javax.swing.*; class NamesNumbers { String name; String phoneNumber; public NamesNumbers(String name, String phoneNumber) { this.name = name; this.phoneNumber = phoneNumber; } public String getName() {return name;} public String getNumber() {return phoneNumber;} public boolean equals(String s) { if (s.equals(name)) return true; else return false; }

} public class QuickTest { public static void main(String args[]) { int j; LinkedList namesNumbers = new LinkedList(); String s1; boolean found = false; // now add individual names to the end of the list namesNumbers.add(new NamesNumbers("Lanfrank John","111-111-1111")); namesNumbers.add(new NamesNumbers("Zebee Frank","222-222-2222")); namesNumbers.add(new NamesNumbers("Dolan Edith", "333-333-3333")); namesNumbers.add(new NamesNumbers("Acme Sam", "444-444-4444")); s1 = JOptionPane.showInputDialog("Enter name to search for"); +) for (int i = 0; i < namesNumbers.size(); i+ {

if (((NamesNumbers)namesNumbers.get(i)).equals(s1)) { System.out.println(Name Found!); System.out.println(((NamesNumbers) (namesNumbers.get(i))).getName());

System.out.println(((NamesNumbers) (namesNumbers.get(i))).getNumber()); found = true; } } if (!found) System.out.println("Name not found!"); System.exit(0); } } 3. Using the linked list of objects illustrated in Figure 13-7, write the sequence of steps necessary to delete the object for Edith Dolan from the list. 1) Find the object representing Edith Doloan while also keeping track of the previous object in the list 2) Set the previous objects reference variables value to the object immediately following the item to be removed. 5. Determine the output of the following program: import java.util.*; // needed for the Collection Framework classes public class ShowIterator { public static void main(String[] args) { int intValue;

double sum = 0.0; double average; // create an array of Integer objects Integer nums[] = {new Integer(1), new Integer(2), new Integer(3), new Integer(4), new Integer(5)}; // instantiate a LinkedList of Integer objects using a // constructor that initializes the LinkedList with values LinkedList x = new LinkedList(Arrays.asList(nums)); System.out.println("\nThe LinkedList x initially has a size of " + x.size() + "," + "\n contains the elements: "); System.out.println(x); Iterator iter = x.iterator(); while (iter.hasNext()) { intValue = ((Integer)iter.next()).intValue(); sum = sum + intValue; } average = sum / x.size(); System.out.println("The average of these numbers is: " + average); } }

and

The LinkedList x initially has a size of 5, and contains the elements: [1, 2, 3, 4, 5] The average of these numbers is: 3.0 7a. A doubly linked list is a list in which each object contains a reference to both the following and previous objects in the list. Define an appropriate type for a doubly linked list of names and telephone numbers. public class DirectoryEntry { private String name; private String number; } b. Using the type defined in Exercise 7a, modify Program 13-4 to list the names and phone numbers in reverse order. import java.util.*; class DirectoryEntry { private String name; private String number; public DirectoryEntry(String name, String number) { this.name = name; this.number = number; } public String getName() {return name;}

public String getNumber() {return number;} } public class QuickTest { public static void main(String args[]) { int j; LinkedList namesNumbers = new LinkedList(); // now add individual names to the end of the list namesNumbers.add(new DirectoryEntry("Lanfrank John","555-5454")); namesNumbers.add(new DirectoryEntry("Zebee Frank","555-3434")); namesNumbers.add(new DirectoryEntry("Dolan Edith","555-2235")); namesNumbers.add(new DirectoryEntry("Acme Sam","555-3321")); Collections.reverse(namesNumbers); reverse the sorted list //

System.out.println("\nThe list in reverse order is:\n"); for (int i = 0; i < namesNumbers.size(); i+ +) { System.out.println("Name: " + ((DirectoryEntry) (namesNumbers.get(i))).getName()); System.out.println(" Number: " +

((DirectoryEntry) (namesNumbers.get(i))).getNumber()); System.out.println(""); } } } Exercises 13.3 . 1. State whether a stack object would be appropriate for each of the following tasks. Indicate why or why not.
a.

A word processor must remember a line of up to 80 characters. Pressing the BackSpace key deletes the previous character, and pressing CTRL/BackSpace deletes the entire line. Users must be able to undo deletion operations.

This is stack implementable as each letter is placed in order and the backspace key only operates on the last item placed into the stack. Deleting an entire line amounts to multiple backspace uses.
b.

Customers must wait one to three months for delivery of their new automobiles. The dealer creates a list that will determine the "fair" order in which customers should get their cars; the list is to be prepared in the order in which customers placed their requests for a new car.

No. Stacks are implemented first-in last-out. Therefore, this system would not be fair.
c.

You are required to search downward in a pile of magazines to locate the issue for last January. Each magazine was placed on the pile as soon as it was received.

This is stack implementable. New magazines are on top of the list and one must remove each magazine from the top to find older magazines.
d.

A programming team accepts jobs and prioritizes them on the basis of urgency.

This is not stack implementable. With a stack, no ordering is possible according to urgency. Stacks could only keep track of when the job occurred.
e.

A line formed at a bus stop

Not stack implementable. A line forms as first-in first-out. A stack is first-in last-out. 3. Modify Program 13-8 to instantiate three stacks of digits named digits1, digits2, and digits3, respectively. Initialize digits1 to contain the digits 9, 8, 5, and 2, which is the number 2589 in reverse digit order. Similarly, the digits2 stack should be initialized to contain the digits 3, 1, 5, and 7, which is the number 7413 in reverse digits order. Calculate and place the sum of these two numbers in the digits3. This sum should be obtained by popping respective elements from digits1 and digits2 and adding them together with a variable named carry, which is initialized to 0. If the sum of the two popped elements and carry does not exceed 10 the sum should be pushed onto digits3 and the carry set to 0; otherwise, the carry should be set to 1 and the units digit of the sum pushed onto the digits3 stack. import java.util.*; Framework import java.io.*; Keyboard // needed for Collection // needed to access the

public class QuickTest { public static void main(String[] args) throws java.io.IOException { String name; int carry, sum; Stack digits1 = new Stack(); Stack digits2 = new Stack(); Stack digits3 = new Stack(); // Push the first number into the first stack digits1.push(new Integer(2)); digits1.push(new Integer(5)); digits1.push(new Integer(8)); digits1.push(new Integer(9)); // Push the second number onto the second stack digits2.push(new Integer(7)); digits2.push(new Integer(4)); digits2.push(new Integer(1)); digits2.push(new Integer(3)); // Start adding the two numbers carry = 0; while (!digits1.isEmpty()) { sum = Integer.parseInt((digits1.pop()).toString()) + Integer.parseInt((digits2.pop()).toString()); if (sum + carry >= 10) {

carry = 1; sum = sum+carry-10;

else carry = 0; } } } digits3.push(new Integer(sum));

5. Write a Java program that permits a user to enter a maximum of 50 characters into a stack object. Then have your program sort the stack contents into increasing order. Thus, if the contents of the stack are initially D, E, A, and B, the final contents of the stack will be A, B, D, and E. import java.util.*; // needed for Collection Framework import java.io.*; // needed to access the Keyboard import javax.swing.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { Stack charStack = new Stack(); charStack.setSize(50); Stack sortedStack = new Stack(); sortedStack.setSize(50); Stack tempStack = new Stack(); tempStack.setSize(50);

String s1; char entry; int index; entry = Character.toUpperCase(JOptionPane.showInputDialo g( "Enter a character (non alphabetic to stop").charAt(0)); while (Character.isLetter(entry)) { charStack.add(new Character(entry)); entry = Character.toUpperCase(JOptionPane.showInputDialo g( "Enter a character (non alphabetic to stop").charAt(0)); } for (int i = 'Z'; i >= 'A'; i--) { while (!charStack.isEmpty()) { if ( ((Character) (charStack.peek())).equals(new Character((char)i))) sortedStack.push(charStack.pop()); else tempStack.push(charStack.pop()); } charStack = tempStack; tempStack = new Stack(); }

System.exit(0); }

7. The program written for Exercise 5 can be expanded to include braces,{}, and brackets,[], as well as parentheses delimiters. For example, consider the string { (a + b) / [(x + y) * z] },to determine if such strings contain balanced pairs of braces, brackets, and parentheses using a stack, each left facing delimiter is pushed onto a stack of characters starting from the left most character. Whenever a right facing delimiter is encountered the top stack element is popped. An unbalanced expression results if a right facing delimiter is encountered and the popped element is not its matching left facing delimiter or if the stack is not empty when the end of the string is encountered. Using this information write a Java program that permits the user to type in a string and determines if the string contains a balanced set of braces, brackets, or parentheses. import java.util.*; import java.io.*; import javax.swing.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { Stack delimiterStack = new Stack(); String s1; int index; boolean badEntry = false; s1 = JOptionPane.showInputDialog("Enter a string");

for (int i = 0; i < s1.length(); i++) { if (s1.charAt(i) == '(' || s1.charAt(i) == '{' || s1.charAt(i) == '[') delimiterStack.push(new Character(s1.charAt(i))); else if (s1.charAt(i) == ')' && ((Character) (delimiterStack.peek())).equals(new Character('(')) && !delimiterStack.isEmpty()) delimiterStack.pop(); else if (s1.charAt(i) == ']' && ((Character) (delimiterStack.peek())).equals(new Character('[')) && !delimiterStack.isEmpty()) delimiterStack.pop(); else if (s1.charAt(i) == '}' && ((Character) (delimiterStack.peek())).equals(new Character('{')) && !delimiterStack.isEmpty()) delimiterStack.pop(); else if (s1.charAt(i) != ')' && s1.charAt(i) != '}' && s1.charAt(i) != ']'); else {

} }

badEntry = true; break;

if (badEntry == true) System.out.println("String not formatted correctly"); else System.out.println("String formatted correctly"); } } 9. Write a single-line word processor. As characters are typed they are to be pushed onto a stack. Some characters have special meanings: # Erase the previous character (pop it from the stack). @ Kill the entire line (Empty the stack). ?,!,., or Enter Terminate line entry. Move the characters to an array and write the contents of the array to the screen. import java.util.*; import javax.swing.*; public class QuickTest { public static void main(String[] args) { String s1; Object charArray[]; System.exit(0);

Stack lineStack = new Stack(); s1 = JOptionPane.showInputDialog("Enter a string"); for (int i = 0; i < s1.length(); i++) { if (s1.charAt(i) == '#') lineStack.pop(); else if (s1.charAt(i) == '@') lineStack.clear(); else if (s1.charAt(i) == '?' || s1.charAt(i) == '!' || s1.charAt(i) == '.') { lineStack.push((Object)(new Character(s1.charAt(i)))); break; } else lineStack.push((Object)(new Character(s1.charAt(i)))); } charArray = lineStack.toArray(); for (int i = 0; i < charArray.length; i++) System.out.print("" + (Character)charArray[i]); } System.exit(0);

Exercises 13.4 1. State whether a queue, a stack, or neither object would be appropriate for each of the following tasks. Indicate why or why not. a. A waiting list of customers to be seated in a restaurant. Queue. A waiting list leads to a first in first-out arrangement. b. A group of student tests waiting to be graded. Stack. The last test placed on the pile will be the first test graded. Therefore a first-in last-out arrangement is required. c. An address book listing names and telephone numbers in alphabetical order. Neither a stack or queue will order things in this manner. d. Patients waiting for service in a doctor's office. Queue. Reasoning is the same as for part a. 3. Write a Java program that permits a user to enter a maximum of 50 double-precision values into a queue. Then have your program sort the queue contents into increasing order. Thus, if the contents of the queue are initially D, E, A, and B, the final contents of the queue will be A, B, D, and E.

public class QuickTest { public static void main(String[] args) throws java.io.IOException { Queue charQueue = new Queue(); Queue sortedQueue = new Queue(); Queue tempQueue = new Queue(); String s1; char entry; int index; Character temp; entry = Character.toUpperCase(JOptionPane.showInputDialo g( "Enter a character (non alphabetic to stop").charAt(0)); while (Character.isLetter(entry)) { charQueue.push(new Character(entry)); entry = Character.toUpperCase(JOptionPane.showInputDialo g( "Enter a character (non alphabetic to stop").charAt(0)); } for (int i = 'A'; i <= 'Z'; i++) { while (!charQueue.isEmpty()) { temp = (Character)(charQueue.pop()); if (temp.equals(new Character((char)i)))

sortedQueue.push(temp); else tempQueue.push(temp); } charQueue = tempQueue; tempQueue = new Queue();

} } }

System.exit(0);

5. Add a menu method to Program 13-10 that gives the user a choice of adding a name to the queue, removing a name from the queue, or listing the contents of the queue without removing any objects from it. public class QuickTest { public static void main(String[] args) throws java.io.IOException { String s1, name; Queue nameQueue = new Queue(); // create an empty stack Queue tempQueue = new Queue(); // set up the keyboard input stream BufferedReader br = new BufferedReader( new InputStreamReader(System.in));

System.out.println("\nMake a choice"); System.out.println("-------------"); System.out.println(" (E)nter a name"); System.out.println(" (R)emove a name"); System.out.println(" (L)ist names"); System.out.println("E(X)it\n"); s1 = br.readLine(); while (!s1.equals("X")) { if (s1.equals("E")) { // push names onto the queue while(true) { System.out.print("Enter a name (or x to stop): "); name = br.readLine(); if (name.equalsIgnoreCase("X")) break; nameQueue.push(name); } } else if (s1.equals("R")) { while(true) { System.out.print("Enter a name (or x to stop): "); name = br.readLine(); if (name.equalsIgnoreCase("X")) break; nameQueue.remove(name); } } else if (s1.equals("L"))

{ System.out.println("\nThe names in the queue are:"); // pop names from the stack while(!nameQueue.isEmpty()) { name = (String)nameQueue.pop(); tempQueue.push(name); System.out.println(name); } nameQueue = tempQueue; tempQueue = new Queue(); } else if (s1.equals("X")) break; System.out.println("\nMake a choice"); System.out.println("-------------"); System.out.println(" (E)nter a name"); System.out.println(" (R)emove a name"); System.out.println(" (L)ist names"); System.out.println(E(X)it\n); s1 = br.readLine(); } } }

7. Write a queue-handling program that asks each customer for their names as they place orders at a fast food restaurant. Each object in the queue should consist of a name field with a maximum of twenty characters and an integer field, which keeps track of the total number of customers served. The value in the integer field

should be automatically provided by the program each time a name is entered. Orders are processed in the same sequence as they are placed. The order taker examines the queue and calls the names when the order is ready. When the queue is empty, print a message telling the staff to take a break. class Customer { String name; int number; public Customer(String name, int number) { if (name.length() > 20) this.name = name.subString(0,20); else this.name = name; } this.number = number;

public String getName(){return name;} public int getNumber(){return number;}

public class QuickTest { public static void main(String[] args) { String s1; int number = 1; Queue customerQueue = new Queue(); Customer temp;

s1 = JOptionPane.showInputDialog("Enter customer name (Q to quit)"); while (!s1.equals("Q")) { customerQueue.push(new Customer(s1,number)); s1 = JOptionPane.showInputDialog("Enter customer name (Q to Quit)"); number++; } while (!customerQueue.isEmpty()) { temp = (Customer)(customerQueue.pop()); System.out.println("\nOrder is ready for the following customer"); System.out.print(" Name: " + temp.getName() + "\n Number: " + temp.getNumber()); System.out.println(""); } System.out.println("Orders filled...take a break!"); System.exit(0); } }

9a. On your electronic mail terminal you receive notes to call people. Each message contains the Name and Phone number of the caller as well as a date in the form month/day/year and a 24-hour integer

clock in the form hours:minutes that objects the time that the message was received. A Latest Attempt field is initially set to 0, indicating that no attempt has yet been made to return the call. For example, a particular object may appear as: Jan Williamson (215)666-7777 8/14/96 17:05 0 Write a Java program to store these objects in a queue as they arrive an to feed them to you, one at a time, upon request. If you cannot reach a person when you try to call, place that object at the end of the queue and fill the Latest Attempt field with the time you tried to return the call, in the form DaysLater/hours:min. Thus, if your last unsuccessful attempt to return Jan Williamson's call was on 8/16/96 at 4:20, the new enqueued object would be Jan Williamson (215)666-7777 8/14/96 17:05 2/16:20 The solution to this problem will be similar to that in part (b). One only needs to replace the Java supplied Date class with the user specified Date class.

b. Modify the program written for Exercise 9 so that the time and date fields are automatically filled in using system calls to time and date methods provided by your compiler. import java.util.*; import javax.swing.*; { class MissedCall String name; String number; Date callDate; String lastAttempt;

public MissedCall(String name, String number, Date date, String la) { this.name = name; this.number = number; callDate = date; lastAttempt = la; } public Date getDate(){return callDate;} public String getLastAttempt(){return lastAttempt;} public void missCall(String la) { lastAttempt = la; } } public class QuickTest { public static void main(String[] args) { String s1, s2; Queue missedCallQueue = new Queue(); MissedCall temp; long duration; int size; s1 = JOptionPane.showInputDialog("Enter a new call (Q to quit)"); while (!s1.equals("Q")) { s2 = JOptionPane.showInputDialog("Enter a number");

missedCallQueue.push( new MissedCall(s1,s2, new Date(System.currentTimeMillis()),"0")); s1 = JOptionPane.showInputDialog("Enter a new call (Q to quit)"); } // Miss each call in the list once size = missedCallQueue.size(); for (int i = 0; i < size; i++) { // Delay Between calls for (double j = 0; j < 10000000.; j++); temp = (MissedCall)missedCallQueue.pop(); // Compute the time elapsed duration = System.currentTimeMillis() temp.getDate().getTime(); s1 = "" + (duration/(1000*60*60*24)) + "/" + (duration/(1000*60*60)) + ":" + (duration/(1000*60)); temp.missCall(s1); missedCallQueue.push(temp); } System.out.println( ((MissedCall) (missedCallQueue.get(0))).getLastAttempt()); System.exit(0);

} }

III. Sample Test Questions Chapter 13 1) Which of the following should be implemented with a stack? a) a movie theater line b) a dictionary c) an in-basket on a persons desk d) a line at a restaurant Answer: (C) 2) Which of the following should be implemented with a Queue? a) a pile of newspapers b) a line at a movie theater c) an in-basket d) a sequence of function calls Answer: (B) 3) A stack is implemented in the following format a) FIFO b) LILO c) LILI d) LIFO Answer: (D) 4) A queue is implemented in the following format a) FIFO

b) FILO c) FILI d) LIFI Answer: (A) 5) Singly-linked lists have all of the following properties except a) the ability to easily delete a node and reconstruct the list without having to modify all the following nodes in the list b) the ability to easily add a node to the beginning of the list without shifting the contents of the rest of the list c) can only store primitive Java data types d) All of the above are properties of linked lists. Answer: (C) 6) A doubly-linked list differs from a singly-linked list in that a) a doubly linked list does not store a reference to both the previous and next node in the list while a singly-linked list does b) a doubly-linked, at each node in the list, stores an extra reference to the beginning of the list c) a doubly-linked list stores two references to the next element in the list d) a doubly-linked list stores, at each node, an extra reference to the previous element in the list while a singly-linked list only has a reference pointing to the next list

element Answer: (D) 7) The individual data items within a record are formally referred to as a) arguments b) data fields c) methods d) parameters Answer: (B) 8) A homogenous data structure a) has components that are all of the same size in bytes b) can consist of components of different data types as long as those different types are placed within the structure in an orderly manner c) is never a list d) has components that are all of the same data type Answer: (D) 9) A heterogeneous data structure a) cannot be a list b) is characterized by having components of all the same data type c) is always implemented as a doubly-linked list d) has components of different data types and each of the different types must be evenly distributed throughout the list

Answer: (A) 10) Which of the following is not a List type as defined by the Collection Framework? a) arraylist b) vector c) hashtable d) stack Answer: (C) 11) Which of the following is not a Set type as defined by the Collection Framework? a) stack b) treeset c) hashset d) none of the above Answer: (A) 12) Suppose that stack one contained the values [1,2,3,4] and stack two contained the values [5, 6, 7, 8], ordered from the top of the stack to the bottom of the stack. What are the contents of stack three after the following psuedocode is executed? do four times: three.push(one.pop() + two.pop());

end do a) [12,10, 8, 6] b) [6, 8, 10, 12] c) [12, 6, 10, 8] d) [6, 8, 12, 10] Answer: (A) 13) Suppose that queue one contained the values [1,2,3,4] and queue two contained the values [5, 6, 7, 8]. The left most element is the element that was most recently placed into the queue. What are the contents of stack three after the following psuedocode is executed? do four times: three.push(one.pop() + two.pop()); end do a) [12,10, 8, 6] b) [6, 8, 10, 12] c) [12, 6, 10, 8] d) [6, 8, 12, 10] Answer: (B) 14) Popping an item off of a stack a) returns the element at the bottom of the stack and removes it from the stack

b) returns the element at the bottom of the stack and keeps it in the stack c) returns the element at the top of the stack and keeps it in the list c) returns the element at the top of the stack and removes it from the stack Answer: (D) 15) Suppose you were creating a database of a large amount of information. It it was required that for each addition or deletion there must be a minimum number of operations to reorganize the list, which data structure should be chosen? a) stack b) array c) linked-list d) queue Answer: (C)

I. OVERVIEW: Chapter 14 Additional Capabilities Previous chapters have presented Java's basic structure, statements, and capabilities. This chapter presents additional capabilities that you may require or find useful as you progress in your understanding and use of Java. None of these are advanced features, but their usage is typically rather restricted. The features described in Sections 14.1 and 14.2 are almost never used to the extent of the topics presented in the prior chapters. Unlike the other topics, command line arguments, the topic of Section 14.3, are used extensively by some programmers. The topic is included in this chapter because it can be introduced almost at any point within your study of Java. 14.1 Additional Features 14.2 Bit Operators 14.3 Command Line Arguments 14.4 Chapter Review

Potential Problem areas: This chapter can be skipped if time is running out. Some students will find the low-level topics interesting; most will not see the relevance.

II. ANSWERS TO ODD-NUMBERED EXERCISES 1. Rewrite each of the following if-else statements using a conditional expression: a. if (a < b); minimunValue = a; else minimumValue = b; minimumValue = (a < b) ? a : b; b. if (num < 0) sign = 1; else sign = 1; sign = (num < 0) ? -1 : 1; c. if (flag == 1) value = num; else value = num * num; value = (flag == 1) ? num : num*num; d. if (credit == plus) rate = prime; else rate = prime + delta; rate = (credit == plus) ? prime : prime + delta;

e. if (!bond) coupon = .075; else coupon = 1.1; coupon = (!bond) ? 0.075 : 1.1; 3. Write the octal representations of the binary numbers given in Exercise 2. 11001010 = 011 001 010 = 312 10100101 = 010 100 101 = 245 5. Enter and execute Program 14-1 on your computer. Students should enter and execute the specified program. 7a. Write a program that accepts the name of a data file as a command line argument. Have your program open the data file and display its contents, line by line, on the screen. import java.io.*; public class QuickTest { public static void main(String[] args) throws java.io.IOException { BufferedReader br = new BufferedReader(new FileReader(args[0])); String s1; s1 = br.readLine(); while (s1 != null)

{ System.out.println(s1); s1 = br.readLine(); } } } 7b. Would the program written for Exercise 7a work correctly for a program file? No, the above application assumes a character based file and not a byte based file. It would execute and display information to the screen; however, the displayed results would not be legible. br.close();

III. Sample Test Questions Chapter 14 1) Which of the following situations will not necessarily result in a buffer flush? a) the end of a program is reached b) a newline sequence appearing in the buffer c) calling the print() method d) calling the flush() method Answer: (C) 2) Any integer having a leading ______ is taken to be an octal number. a) O (uppercase O) b) o (lowercase o) c) 0 (zero) d) X Answer: (C) 3) What number, in base 10, is stored in the variable result after the following line is executed in Java: result = 035 * 13; a) 455 b) 377 c) 299 d) 0 Answer: (B)

4) To empty the print buffer, use the method called ______ a) empty() b) out() c) display() d) flush() Answer: (D)

5) Assuming hours is 30, what is the value of the expression rate = (hours > 30) ? .4 : .2; a) rate = .4 b) rate = .2 c) hours = .4 d) hours = .2 Answer: (B) 6) The conditional operator is an alternative to a(n) a) do-while loop b) if-else statement c) if statement d) for loop Answer: (B)

7) The & operator a) is essentially the same as adding two operands b) is essentially the same as subtracting two operands c) performs a bit-by-bit AND comparison of two operands d) performs a logical AND of two operands Answer: (C) 8) AND operations are useful in a) masking selected bits from an operand b) forcing selected bits to take on a value of 1 c) creating the complement of an indididual bit d) creating the complement of all bits in an operand Answer: (A) 9) The inclusive OR operator is useful in a) making selected bits from an operand b) forcing selected bits to take on a value of 1 c) creating the complement of an individual bit d) creating the complement of all bits in an operand Answer: (B) 10) What is the effect on op1 of the following statement op1 = op1 << 2; a) addition by 4 b) subtraction by 4

c) division by 4 d) multiplication by 4 Answer: (D) 11) What is the effect on op1 of the following statement op1 = op1 >> 2 a) addition by 2 b) subtraction by 4 c) division by 4 d) multiplication by 2 Answer: (C) 12) What number is stored in result after the following line of Java code is executed: result = ((op1 >> 2) << 4) & 1101(binary) where op1 = 1024(base 10). a) 0011(binary) b) 1010(binary) c) 0 (decimal) d) 1024(decimal) Answer: (C) 13) The exclusive OR operator is useful in a) masking selected bits from an operand b) forcing selected bits to take on a value of 1 c) creating the complement of an individual bit

d) creating the complement of all bits in an operand Answer: (C) 14) What is the result of an AND operation on the following binary values: 11010110 & 110111111 a) 10010110 b) 11011101 c) 11101111 d) 00100111 Answer: (A) 15) What is the result of an exclusive OR operation on the following binary values? 11010110 & 110111111 a) 110111101 b) 001011001 c) 001010111 d) 101101001 Answer: (D)

Você também pode gostar