SOLUTION MANUAL FOR A COMPREHENSIVE INTRODUCTION TO OBJECT ORIENTED PRORAMMING WITH JAVA 1ST EDITION

Page 1


SOLUTION MANUAL FOR A COMPREHENSIVE INTRODUCTION TO OBJECT ORIENTED PRORAMMING WITH JAVA 1ST EDITION BY C THOMAS WU Chapter 1 Solutions 1.1

Graphically represent a Vehicle class and three Vehicle objects named car1, car2, and car3.

Vehicle

car1:Vehicle

1.2

car2:Vehicle

car3:Vehicle

Graphically represent a Person class with the following components: • Instance variables name, age, and gender. • Instance methods setName, getName, and getAge. • Class method getAverageAge.

setName() getAge()

Person name

age

age

getGender()

gender

gender

getAverageAge() average age 1.3

Design a CD class where a CD object represents a single music CD. What kinds of information (artist, genre, total playing time, etc.) do you want to know about a CD? Among the information in which you are interested, which are instance variables? Are there any class variables or class constants? State Album Name Artist Genre Total Playing Time

instance variable instance variable instance variable instance variable


Maximum Playing Time

class constant


Behaviors getAlbumName(), setAlbumName() instance methods getArtist(), setArtist() instance methods getGenre(), setGenre() instance methods getPlayingTime(), setPlayingTime() instance methods getMaxPlayingTime() class method Students may also include a list of songs on the CD and methods to access them. A song itself would probably have its own class to represent it. However this concept is more advanced than is necessary at this stage. 1.4

Suppose the Vehicle class in Exercise 1 is used in a program that keeps track of vehicle registration for the Department of Motor Vehicles. What kinds of instance variables would you define for such Vehicle objects? Can you think of any useful class variables for the Vehicle class? Instance variables owner licenseID registrationNumber make model color value Class variables At this stage, the number of total vehicles could be thought to belong to the class. Information relating to the length of a licenseID or registrationNumber could be stored as class constants. Aside from these, there are no obviously necessary traits for which all vehicles share the same value or which the class may need to function.

1.5

Suppose the following formulas are used to compute the annual vehicle registration fee for the vehicle registration program in Exercise 1.4: • For cars, the annual fee is 2 percent of the value of the car. • For trucks, the annual fee is 5 percent of the loading capacity (in pounds) of the truck. Define two new classes Car and Truck as subclasses of Vehicle. Hint: Associate class and instance variables common to both Car and Truck to Vehicle. Vehicle Class See Exercise 1.4 Car Class (subclass of Vehicle) registrationRate

class constant


Note: Value is already an instance variable in Vehicle since all vehicles have some value. Truck Class (subclass of Vehicle) registrationRate loadingCapacity 1.6

class constant instance variable

Consider a student registration program used by the registrar’s office. The program keeps track of students who are registered for a given semester. For each student registered, the program maintains the student’s name, address, and phone number; the number of classes in which the student is enrolled and the student’s total credit hours. The program also keeps track of the total number of registered students. Define instance and class variables of a Student class that is suitable for this program. Instance variables name address phoneNumber numClassesThisSemester totalCreditHours Class variables numStudentsRegistered

1.7

Suppose the minimum and maximum number of courses for which a student can register are different depending on whether the student is a graduate, undergraduate, or work-study student. Redo Exercise 6 by defining classes for different types of students. Relate the classes using inheritance. Student See Exercise 1.6 GraduateStudent (subclass of Student) maximumHours minimumHours

class constant class constant

UndergraduateStudent (subclass of Student) maximumHours class constant minimumHours class constant WorkStudyStudent (subclass of Student) maximumHours minimumHours

class constant class constant


1.8

Imagine you are given a task of designing an airline reservation system that keeps track of flights for a commuter airline. List the classes you think would be necessary for designing such a system. Describe the data values and methods you would associate with each class you identify. Note: For this exercise and Exercises 9 through 12, we are not expecting you to design the system in complete detail. The objective of these exercises is to give you a taste of thinking about a program at a very high level. Try to identify about a half dozen or so classes, and for each class, describe several methods and data members. Database Data Members Collection of clients Collection of flights Methods Accessors (get ()) and Mutators (set __ ()) for clients and flights1 Make reservation Add new flight Client Data Members Name Address Phone Collection of reservations BillingInformation Methods Accessors and Mutators for name, address, BillingInformation, and collection of reservations Add reservation Flight Data Members Departure city Arrival city Departure time Arrival time Seats available Aircraft type

1

Accessors and Mutators (also called gets and sets) allow other people to use your classes data members while allowing you to control just how they access them. This allows you to perform various activities like bounds checking (making sure the value set is not illegal, such as –6 for an age data member). This is part of the concept of encapsulation and is fundamental to the object-oriented paradigm.


Collection of passengers Methods Accessors and Mutators for departure and arrival information, seats available, aircraft type Compute flight time Compute ticket price (may vary with departure date, time, seats available…) Reservation Data Members Client Flight Paid Status (i.e., true/false) Methods Accessors and Mutators for client and flight BillingInformation Data Members Name Billing Address Credit Card number Credit Card expiration Credit Card type Methods Accessors and Mutators for all data members Note: This is a high-level design and by no means the only appropriate one. When designed in more detail, there will be ways to eliminate the duplicate data. 1.9

Repeat Exercise 8, designing a university course scheduling system. The system keeps track of classes offered in a given quarter, the number of sections offered, and the number of students enrolled in each section. Quarterly Database Data Members Collection of courses Methods Add Course Remove Course


Course Data Members Collection of Sections Title Code College Department Methods Add Section Remove Section Accessors and Mutators for all data members Section Data Members Maximum number of students Current number of students Section ID Methods Add Student Remove Student Accessors and Mutators for all data members 1.10

Repeat Exercise 8, designing the state Department of Motor Vehicles registration system. The system keeps track of all licensed vehicles and drivers. How would you design objects representing different types of vehicles (e.g., motorcycles and trucks) and drivers (e.g., class A for commercial licenses and class B for towing vehicles)? Vehicle Data Members VIN Class type (A, B, etc.) Make Model Year Registration fee Owner Methods Accessors and Mutators for all data members Note: Could also implement with several subclasses of Vehicle, one for each class (car, commercial truck, livery, etc.) especially if each type required some specialized information.


Driver Data Members License number Name Address Collection of Vehicles Collection of Violations Methods Add Vehicle/Violation Remove Vehicle/Violation Accessors and Mutators for all data members Violation Data Members Number Date Location Charge Officer Methods Accessors and Mutators for all data members 1.11

Repeat Exercise 8, designing a sales tracking system for a fast-food restaurant. The system keeps track of all menu items offered by the restaurant and the number of daily sales per menu item. Menu Data Members Collection of menu items Total Sales Methods Get Menu Item Add Menu Item Delete Menu Item MenuItem Data Members Name Price Total Sales Methods Accessors and Mutators for name, price, and total sales


1.12

When you write a term paper, you have to consult many references: books, journal articles, newspaper articles, and so forth. Repeat Exercise 8, designing a bibliography organizer that keeps track of all references you used in writing a term paper. Document Data Members Collection of sources Methods Add Source Delete Source Source Data Members Author Title Publisher Copyright Date City of Publication Volume (or Issue) Pages Used Methods Print Bibliography Entry It would be common practice for there to be several different subclasses of Source, each with a slightly different implementation of Print Bibliography Entry, for example: paper in a conference proceedings, article in a journal, journal, book, article in a magazine, magazine, etc.

1.13

Consider the inheritance hierarchy given in Figure 1.12. List the features common to all classes and the features unique to individual classes. Propose a new inheritance hierarchy based on the types of accounts your bank offers. Possible Common Features: Account Number Opening Balance Opening Date Current Balance Minimum Balance Owner(s) Possible Unique Features:


Number of free withdrawals Fee per withdrawal Interest Rate Check writing privileges Debit Card information Account

1.14

Savings Account

Checking Account

Money Market Account

Student Checking

Classic Checking

Business Checking

Consider a program that maintains an address book. Design an inheritance hierarchy for the classes such as Person, ProfessionalContact, Friend, and Student that can be used in implementing such a program.


1.15

Do you think the design phase is more important than the coding phase? Why or why not? The design phase is much more important than the coding phase. Design has a huge impact on not only the ease and speed of implementation during the coding phase but also on the testing and maintenance phases. A proper design allows testing to be done in terms of structural components, which makes bugs easier to trace back to the improper implementation. Furthermore, a good design is far more maintainable. Maintenance is considered the most expensive of all the phases, thus a more easily maintained project is considerably less expensive. It is important to remember that maintenance includes more than just fixing bugs; extension of the original design to meet new requirements is a common and important task.

1.16

How does the quality of design affect the total cost of developing and maintaining software? A low quality design will not only slow implementation, thus increasing expense and delay, but will also force design decisions to be revisited later. Inevitably, the design will have to change. Related implementation will have to be adapted or recoded. Testing will have to be redone. The more patchwork done, the more likely new errors are injected into the code. Not only are the maintenance programmers burdened with what is almost certainly a less coherent design (and documentation that tended to become outdated as more changes to the design were made), but they must also hunt for more bugs.


Chapter 2 Solutions 1. Identify all errors in the following program: /* Program Exercise1 Attempting to display a frame window //  1 import swing.JFrame;  2 class Exercise 1 {  3 public void Main() {  4 JFrame frame;  5 frame.setVisible(TRUE)  6 } }

1. Should be */ to terminate the multi-line comment. 2. Correct statement is: import javax.swing.JFrame;

or import javax.swing.*;

3. The class name is not a valid identifier. It should be Exercise1. 4. The correct declaration for the main method is public static void main(String[] args)

5. Should include an object creation statement JFrame frame = new JFrame();

6. Semicolon is missing after the statement. Also, TRUE is not valid syntax in JAVA. The correct statement is: frame.setVisible(true);

2. Identify all errors in the following program: //  1 Program Exercise2 Attempting to display a frame of the size 300 by 200 pixels //  2 import Javax.Swing.*;  3 class two { public static void main method() {  4 myFrame JFrame;  5 myFrame = new JFrame(); myFrame.setSize(300, 200); myFrame.setVisible();  6


} }

Should be /* to begin a multi-line comment Should be */ to terminate a multi-line comment The correct package name is javax.swing Java is case sensitive. The correct declaration for the main method is public static void main(String[] args) 5. When declaring a variable, the type comes before the variable name. The correct statement is: 1. 2. 3. 4.

JFrame myFrame; 6. The setVisible method requires a boolean parameter. The correct

statement is: myFrame.setVisible(true);

3. Identify all errors in the following program: /* Program Exercise3 Attempting to display the number of characters in a given input. */  1 class three { public static void main( ) {  2 String input; input = JOptionPane(“input:”);  3 JOptionPane.showMessageDialog( null,“Input has ”+ input.length() + “ characters”); } }

1. JOptionPane is defined in the javax.swing package. In order to use JOptionPane we must import javax.swing. We must insert the following statement import javax.swing.*;

or import javax.swing.JOptionPane;

2. The correct declaration for the main method is public static void main(String[] args) 3. In order to get user input from a JOptionPane, we must use the showInputDialog method. The correct statement is: input = JOptionPane.showInputDialog(null, “input:”);

4. Describe the purpose of comments. Name the types of comments available. Can you include comment markers inside a comment?


Purposes: To describe the program, methods, data values, and other components To explain the meaning of code To provide other helpful information to improve the readability Types: Multi-line comments Single-line comments Javadoc comments In some cases yes (like including // in a multi-line comment), but in other cases no. 5. What is the purpose of the import statement? Does a Java program always have to include an import statement? Imports allow us to use or refer to classes in the imported package without having to use the fully qualified class name. Import statements are not always required. For example, any classes in the java.lang package can be used without importing. If we use fully qualified names in our program, the import statements are not necessary. 6. Show the syntax for importing one class and all classes in a package. One class: import <package name>.<class name>;

All classes: import <package name>.*;

7. Describe the class that must be included in any Java application. Every java application requires one class to be designated as its main class. The designated main class must include the main method. 8. What is a reserved word? List all the Java reserved words mentioned in this chapter. A reserved word is an identifier that is reserved by a programming language and used for a specific purpose. It can be used to designate a special operator such as new or syntactical element of the language such as class and public. Reserved words introduced in this chapter are new, import, class, public, static, void, true, false, and null. 9. Which of the following are invalid Java identifiers? a. R2D2 b. Whatchamacallit

g. 3CPO h. This is okay.


c. HowAboutThis? d. Java e. GoodChoice f. 12345

i. thisIsReallyOkay j. DEFAULT_AMT k. Bad-Choice l. A12345

Invalid identifiers are c (no question mark is allowed), f (the first character must be a non-digit), g (the first character must be a non-digit), h (no space is allowed), and k (no hyphen is allowed). 10. Describe the steps you take to run a Java application and the tools you use in each step. What are source files and bytecode files? What different types of errors are detected at each step? The cycle is Edit-Compile-Run. In the Edit state, you enter a program using any text editor. The file you create is called the source file, which is in human readable form and contains the Java statements that make up the program. In the Compile stage, you compile the source file to create a bytecode file. The tool (another piece of software) to compile the Java source file is called javac. In the Run stage, you execute the bytecode file by using the Java interpreter called java. Note: The Java interpreter is called the Java Virtual Machine (JVM). Syntax and semantic errors are caught by the compiler. A compiler cannot catch logic errors. Logic errors are detected when the program is actually executed. 11. Describe the difference between object declaration and object creation. Use a stateof-memory diagram to illustrate the difference. Object declaration associates an object name to a designated class. It also reserves a small amount (like four bytes) of memory to store a reference to an object. JFrame myFrame;

Object creation (provided that the object is already declared) allocates the memory space for the object itself and stores the reference (arrow) to this object in the object name.


Get complete Order files download link below https://www.mediafire.com/file/hiv6tkbgaqyvy3v/SM+ A+Comprehensive+Introduction+to+ObjectOriented+Programming+with+Java,+1e+C.+Thomas+W u.zip/file

If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.


myFrame = new JFrame();

12. Show a state-of-memory diagram after each of these statements is executed: JFrame Resident

window1; res1, res2;

window1 res1 res2

= new JFrame(); = new Resident(); = new Resident();

After 3 objects are declared:

After 3 new operations are executed:

13. Show a state-of-memory diagram after each of these statements is executed: Person

person1, person2;


person1 person2 person2

= =

new Person(); new Person(); = new Person();

After two objects are declared:

After the first new operation is executed:

After the second new operation is executed:

After the third new operation is executed:


14. Which of these identifiers violate the naming convention for class names? a. r2D2 b. whatchamacallit c. Java d. GoodName

e. CPO f. ThisIsReallyOkay g. java h. badName

The convention is to use an uppercase letter for the first character. The first character of a new word is also capitalized. All other letters are lowercase. The identifiers a, b, g, and h violate the convention. The identifier CPO should be considered as valid if it is interpreted as some kind of acronym. 15. Which of these identifiers violate the naming convention for object names? a. R2D2 b. isthisokay? c. Java d. goodName

e. 3CPO f. ThisIsReallyOkay g. java h. anotherbadone

The convention for object names is almost identical to the one for class names, except the first character is lowercase. The identifiers a, b, c, e, f, and h violate the convention. Notice that b and e are not even valid identifiers. 16. For each of these expressions determine its result. Assume the value of text is a string Java Programming. String text = “Java Programming”; a. text.substring(0, 4) b. text.length( ) c. text.substring(8, 12) d. text.substring(0, 1) + text.substring(7, 9) e. text.substring(5, 6) + text.substring(text.length() – 3, text.length())

a. Java b. 16


c. gram d. Jog e. Ping 17. Write a Java application that displays today’s date in this format: Sunday November 10, 2002. See Exercise2_17.java 18. Write a Java application that displays a frame window 300 pixels wide and 200 pixels high with the title My First Frame. Place the frame so that its top, left corner is at a position 50 pixels from the top of the screen and 100 pixels from the left of the screen. To position a window at a specified location, you use the setLocation method, as in //assume mainWindow is declared and created frame.setLocation( 50, 50 );

Through experimentation, determine how the two arguments in the setLocation method affects the positioning of the window. See Exercise2_18.java 19. Write a Java application that displays the two messages I Can Design and And I Can Program, using two separate dialogs. See Exercise2_19.java 20. Write a Java application that displays the two messages I Can Design and And I Can Program, using one dialog but in two separate lines. See Exercise2_20.java 21. Write a Java application that displays a very long message. Try a message that is wider than the display of your computer screen, and see what happens. See Exercise2_21.java 22. Because today’s computers are very fast, you will probably not notice any discernable difference on the screen between the code JFrame myWindow; myWindow = new JFrame( ); myWindow.setVisible( true );

and


JFrame myWindow; myWindow = new JFrame( ); myWindow.setVisible( true ); myWindow.setVisible( false ); myWindow.setVisible( true );

One way to see this disappearance and reappearance of the window is to put a delay between the successive setVisible messages. To put a delay, you can use a Clock object from the javabook package. Here’s a simple usage of the Clock class: import javabook.*;

… Clock myClock; myClock = new Clock(); // put statement X here myClock.pause( 2 ); // put statement Y here

The unit for the argument you pass in the pause message is seconds. If you want a 0.5-s delay, for example then you pass 0.5 as an argument. Using the Clock class, write a program that makes a JFrame object appear, disappear, and appear again. The window remains visible for 5 s when it appears for the first time, and once it disappears, it won’t reappear for 3 s. See Exercise2_22.java 23. At the textbook website or at the author’s website, you will find a Java package called galapagos (www.drcaffeine.com/packages). The galapagos package includes a Turtle class that is modeled after Seymour Papert’s logo. This Turtle has a pen, and when you move the Turtle, its pen will trace the movement. So by moving a Turtle object, you can draw many different kinds of geometric shapes. For example, this program commands a Turtle to draw a square: import galapagos.*; class Square { public static void main( String[] args ) { Turtle turtle; turtle = new Turtle(); turtle.move( 50 ); turtle.turn( 90 ); counterclockwise turtle.move( 50 ); turtle.turn( 90 );

//move 50 pixels //turn 90 deg


turtle.move( 50 ); turtle.turn( 90 ); turtle.move( 50 ); } }

Write a program to draw a triangle. Read the documentation and see if you can find a way to draw the square in a different color and line thickness. See Exercise2_23.java You can use the penSize and penColor methods to change the thickness and color of the Turtle’s pen. 24. Write a program to draw a star, using a Turtle from Exercise 23. See Exercise2_24.java 25. Write a program to draw a big letter J, using a Turtle from Exercise 23. See Exercise2_25.java 26. Using a Turtle from Exercise 23, write a Java application that displays the text Hello as illustrated here:

See Exercise2_26.java 27. Using a Turtle from Exercise 23 and employing the incremental development steps, build a Java application that draws a house.


See Exercise2_27.java 28. Add the moon and a tree to the house you drew in Exercise 27. See Exercise2_28.java 29. Follow the incremental development methodology explained in this chapter to implement a program for the following problem statement. You must clearly write down the program tasks, create a design document with class descriptions, and draw the program diagram. Identify the development steps. State any assumptions you must make about the input. Articulate any design alternatives and justify your selection. Be sure to perform adequate testing at the end of each development step. Problem Statement: Write an application that asks the user for his or her birth date and replies with the day of the week on which he or she was born. We learned in this chapter that we can create a Date object for today’s date by writing import java.util.*; … Date today = new Date();

To create a Date object for a date other than today, we can use the Date class from the java.sql package. (A more general and flexible way to deal with a date by using the GregorianCalendar class is introduced in Chapter 3.) Notice that there are two distinct classes with the same name Date, but from different packages – one from java.util and another from java.sql. To distinguish the two we will use the fully qualified names. To create a new java.util.Date object, we can call the class method valueOf of the java.sql.Date class with the string representation of a date. The string representation must be in the format yyyy-MM-dd. For example, to create a java.util.Date object for July 4, 1776, we write


java.util.Date bdate = java.sql.Date.valueOf(“1776-07-04”);

Notice that valueOf is a class method of the Data class in the java.sql package. Calling it with a correct argument will return a java.util.Date object for the specified date. See Exercise2_29.java Design Document: Birthday Program Class Purpose Exercise2_29 The main class of the program. JOptionPane The showInputDialog method is used for getting the birth date. The showMessageDialog method is used for displaying the day of the week. java.util.Date Used to hold the date the user was born java.sql.Date Used to generate the java.util.Date version of the user’s birth date. SimpleDateFormat Used to display the day of the week to the user. Assumptions: The user enters valid input in the form yyyy-mm-dd Development Step 1: Getting Input Alternative: Get the month, date, and year separately Development Step 2: Computing and Displaying the Day of the Week


30. Repeat Exercise 29 for this problem statement: Problem Statement: Write an application that asks the user for her or his full name in the format first middle last and replies with the name in the format last, first middle-initial. where the last name is followed by a comma and the middle initial is followed by a period. For example, if the input is Decafe Chai Latte then the output is Latte, Decafe C. See Exercise2_30.java


Design Document: Name Manipulation Class Purpose Exercise2_30 The main class of the program. JOptionPane The showInputDialog method is used for getting the user’s full name. The showMessageDialog method is used for displaying the result. String The class is used for String manipulation, extracting the first name, last name, and middle initial. Assumptions: The user enters valid input in the form first middle last Development Step 1: Getting Input Alternative: Get the first, middle, and last names separately Development Step 2: Computing and Displaying the reformatted name


Chapter 3 Solutions 3.1

Suppose we have the following declarations: int i = 3, j = 4, k = 5; float x = 34.5f, y = 12.25f;

Determine the value for each of the following expressions or explain why it is not a valid expression. a. (x + 1.5) / (250.0 * (i/j)) b. x + 1.5 / 250.0 * i / j c. –x * -y * (i + j) / k d. (i / 5) * y e. Math.min(I, Math.min(j,k))

a. undefined

f. Math.exp(3, 2) g. y % x h. Math.pow(3, 2) i. (int)y % k j. i / 5 * y

(i/j) evaluates 0 resulting in division by 0. Note: if you actually execute this expression, Java will return the value Infinity.

b. 34.5045 c. 591.675f d. 0

(i/5) evaluates to 0.

e. 3 f. Invalid.

No such method

g. 12.25 h. 9.0 i. 2 j. 0.0f

3.2

Suppose we have the following declarations: int m, n, i = 3, j = 4, k = 5; float v, w, x = 34.5f, y = 12.25f

Determine the value assigned to the variable in each of the following assignment statements or explain why it is not a valid assignment.


a. b. c. d. e. f. g. h. i. j.

w = Math.pow(3, Math.pow(i,j)); v = x / i; w = Math.ceil(y) % k; n = (int) x / y * i / 2; x = Math.sqrt(i*i – 4*j*k); m = n + i * j; n = k /(j * i) * x + y i = i + 1; w = float(x + i); x = x / i / y / j;

a. Expression value: 4.34264882430377E38 Not a valid assignment. Compilation error due to the possible loss of precision (assigning a double value to a float variable) b. 11.5f c. Expression value: 3.0f Not a valid assignment. Compilation error due to the possible loss of precision (assigning a double value to a float variable) d. Expression value: 4.163265f Not a valid assignment. Compilation error due to the possible loss of precision (assigning a float value to an int variable) e. Expression value: NaN (or not a number because you can’t take the square root of a negative number) Not a valid assignment. Compilation error due to the possible loss of precision (assigning a double value to a float variable) f. Invalid

Variable n has no value assigned.

g. Expression value: 12/25f Not a valid assignment. Compilation error due to the possible loss of precision (assigning a float value to an int variable) h. 4 i. Invalid syntax j. 0.23469388f

3.3

Suppose we have the following declarations: int

i, j;


float double

x, y; u, v;

Which of the following assignments are valid? a. b. c. d. e.

3.4

i = x; x = u + y; x = 23.4 + j * y; v = (int) x; y = j / i * x;

a. Invalid

Cannot assign a float value to an int variable. Variable x is not initialized.

b. Invalid

Cannot assign a double value to a float variable. Variables u and y are not initialized.

c. Invalid

Cannot assign a double value to a float variable. Variables j and y are not initialized.

d. Invalid

Variable x is not initialized. If it is initialized, then this expression is valid.

e. Invalid

Variables i, j, and x are not initialized. If they are initialized, then this expression is valid.

Write Java expressions to compute each of the following: a. b. c. d.

The square root of B2 + 4AC (A and C are distinct variables) The square root of X + 4Y3 The cube root of the product of X and Y The area R2 of a circle

a. Math.sqrt(B*B + 4*A*C)

b. Math.sqrt(X + 4*Y*Y*Y) or Math.sqrt(X + 4 * Math.pow(Y, 3))

c. Math.pow(X*Y, 1.0/3.0)

d. Math.PI * R * R

3.5

Determine the output of the following program without running it:


class TestOutputBox { public static void main(String[] args) { System.out.println(“One”); System.out.print(“Two”); System.out.print(“\n”); System.out.print(“Three”); System.out.println(“Four”); System.out.print(“\n”); System.out.print(“Five”); System.out.println(“Six”); } } One Two ThreeFour FiveSix

3.6

Determine the output of the following code: int x, y; x = 1; y = 2; System.out.println(“The output is “ + x + y); System.out.println(“The output is “ + (x + y) ); The output is 12 The output is 3

3.7

Write an application that displays the following pattern in the standard output window:


Note: The output window is not drawn to scale. See Exercise3_7.java. The screenshot of the output is as follows:

3.8

Write an application to convert centimeters (input) to feet and inches (output). Use JOptionPane for input and output. 1 inch = 2.54 centimeters. See Exercise3_8.java.

3.9

Write an application that inputs temperature in degrees Celsius and prints out the temperature in degrees Fahrenheit. Use System.in for input and System.out for output. The formula to convert degrees Celsius to the equivalent degrees Fahrenheit is Fahrenheit = 1.8 * Celsius + 32 See Exercise3_9.java.

3.10

Write an application that accepts a person’s weight and displays the number of calories the person needs in one day. A person needs 19 calories per pound of body weight, so the formula expressed in Java is calories = bodyweight * 19;

Use JOptionPane for input and output. (Note: We are not distinguishing between genders.)


See Exercise3_10.java. 3.11

A quantity known as the body mass index (BMI) is used to calculate the risk of weightrelated health problems. BMI is computed by the formula BMI = w / (h / 100.0)2 where w is height in kilograms and h is height in centimeters. A BMI of about 20 to 25 is considered “normal.” Write an application that accepts weight and height (both integers) and outputs the BMI. Use System.in for input and System.out for output. See Exercise3_11.java

3.12

Your weight is actually the amount of gravitational attraction exerted on you by the earth. Since the Moon’s gravity is only one-sixth of the earth’s gravity, on the Moon you would weigh only one-sixth of what you weigh on earth. Write an application that inputs the user’s earth weight and outputs her or his weight on Mercury, Venus, Jupiter, and Saturn. Use your preferred choice for input and output. Use the values in this table. Planet Mercury Venus Jupiter Saturn

Multiply the Earth Weight by 0.4 0.9 2.5 1.1

See Exercise3_12.java. 3.13

When you say you are 18 years old, you are really saying that the earth has circled the sun 18 times. Since other planets take fewer or more days than earth to travel around the sun, your age would be different on other planets. You can compute how old you are on other planets by the formula y = x * 365 / d where x is the age on the Earth, y is the age on planet Y, and d is the number of Earth days the planet Y takes to travel around the Sun. Write an application that inputs the user’s Earth age and prints out his or her age on Mercury, Venus, Jupiter, and Saturn. Use your preferred choice for input and output. The values for d are listed in the table.

Planet Mercury Venus Jupiter Saturn

d = Approximate Number of Earth Days for This Planet to Travel around the Sun 88 225 4380 10767


See Exercise3_13.java. 3.14

Write an application to solve quadratic equations of the form Ax2 + Bx + C = 0 where the coefficients A, B, and C are real numbers. The two real number solutions are derived by the formula

For this exercise, you may assume that A  0 and the relationship B2  4AC holds, so there will be real number solutions for x. Use standard input and output See Exercise3_14.java. 3.15

Write an application that determines the number of days in a given semester. Input to the program is the year, month, and day information of the first and the last days of a semester. Hint: Create GregorianCalendar objects for the start and end dates of a semester and manipulate their DAY_OF_YEAR data. See Exercise3_15.java.

3.16

Modify the Ch3FindDayOfWeek program by accepting the date information as a single string instead of accepting the year, month, and day information separately. The input string must be in the MM/dd/yyyy format. For example, July 4, 1776, is entered as 07/04/1776. There will be exactly two digits for the month and day and four digits for the year. See Exercise3_16.java.

3.17

Write an application that accepts the unit weight of a bag of coffee in pounds and the number of bags sold and displays the total price of the sale, computed as totalPrice = unitWeight * numberOfUnits * 5.99; totalPriceWithTax = totalPrice + totalPrice * 0.0725;

where 5.99 is the cost per pound and 0.0725 is the sales tax. Display the result in the following manner:


Use JOptionPane for input and System.out for output. Draw the program diagram. See Exercise3_17.java. 3.18

If you invest P dollars at R percent interest rate compounded annually, in N years, your investment will grow to

dollars. Write an application that accepts P, R, and N and computes the amount of money earned after N years. Use JOptionPane for input and output. See Exercise 3_18.java. 3.19

Leonardo Fibonacci of Pisa was one of the greatest mathematicians of the Middle Ages. He is perhaps most famous for the Fibonacci sequence, which can be applied to many diverse problems. One amusing application of the Fibonacci sequence is in finding the growth rate of rabbits. Suppose a pair of rabbits matures in 2 months and is capable of reproducing another pair every month after maturity. If every new pair has the same capability, how many pairs will there be after 1 year? (We assume here that no pairs die.) The table below shows the sequence for the first 7 months. Notice that at the end of the second month, the first pair matures and bears its first offspring in the third month, making the total two pairs.

The Nth Fibonacci number in the sequence can be evaluated with the formula


Write an application that accepts N and displays FN. Note that the result of computation using the Math class is double. You need to display it as an integer. Use JOptionPane for input and output. See Exercise3_19.java. 3.20

According to Newton’s universal law of gravitation, the force F between two bodies with masses M1 and M2 is computed as

where d is the distance between the two bodies and k is a positive real number called the gravitational constant. The gravitational constant k is approximately equal to 6.67E-8 dyn * cm2/g2. Write an application that (1) accepts the mass for two bodies in grams and the distance between the two bodies in centimeters, and (2) computes the force F. Use the standard input and output, and format the output appropriately. For your information, the force between the earth and the moon is 1.984E25 dyn. The mass of the earth is 5.983R27 g, the mass of the moon is 7.347E25g, and the distance between the two is 3.844E10 cm. See Exercise3_20.java. 3.21

Dr. Caffeine’s Law of Program Readability states that the degree of program readability R (whose unit is mocha) is determined as

where k is Ms. Latte’s constant, C is the number of lines in the program that contain comments, T is the time spent (in minutes) by the programmer developing the program, and V is the number if lines in the program that contain nondescriptive variable names. Write an application to compute the program readability R. Use your preferred choice for input and output. Ms. Latte’s constant is 2.5E2 mocha lines2/min2. (Note: This is just for fun. Develop your own law, using various functions from the Math class.) See Exercise3_21.java. 3.22

If the population of a country grows according to the formula y = cekx where y is the population after x years from the reference year, then we can determine the population of a country for a given year from two census figures. For example, given that a country with a population of 1,000,000 in 1970 grows to 2,000,000 by 1990, we can predict the country’s population in the year 2000. Here’s how we do the


computation. Letting x be the number of years after 1970, we obtain the constant c as 1,000,000 because 1,000,000 = cek0 = c Then we determine the value of k as y = 1,000,000ekx 2,000,000 / 1,000,000 = e20k k = (1/20)ln(2,000,000/1,000,000) = 0.03466 Finally we can predict the population in the year 2000 by substituting 0.03466 for k and 30 for x (2000 – 1970 = 30). Thus we predict y = 1,000,000e0.03466(30) = 2,828,651 as the population of the country for the year 2000. Write an application that accepts five input values – year A, the population in year A, year B, population in year B, and year C – and predict the population for year C. Use any technique for input and output. See Exercise3_22.java. 3.23

In section 3.10, we use the formula MR = AR / 12 to derive the monthly interest rate from a given annual interest rate, where MR is the monthly interest rate and AR is the annual interest rate (expressed in a fractional value such as 0.083). This annual interest rate AR is called the stated annual interest rate to distinguish it from the effective annual interest rate, which is the true cost of a loan. If the stated annual interest rate is 9 percent, for example, the effective annual interest rate is actually 9.38 percent. Naturally, the rate that the financial institutions advertise more prominently is the stated interest rate. The load calculator program in section 3.10 treats the annual interest rate that the user enters as the stated annual interest rate. If the input is the effective annual interest rate, then we compute the monthly rate as MR = (1 + EAR)1/12 – 1 where EAR is the effective annual interest rate. The difference between the stated and effective annual interest rates is negligible only when the load amount is small or the load period is short. Modify the loan calculator program so that the interest rate that the user enters is treated as the effective annual interest rate. Run the original and modified loan calculator programs, and compare the difference in the monthly and total payments. Use the load amount of 1, 10 and 50 million dollars with the load period of 10, 20, and 30


years and annual interest rates of 0.07, 0.10 and 0.18 respectively. Try other combinations also. Visit several websites that provide a loan calculator for computing a monthly mortgage payment (one such site is the financial page at www.cnn.com). Compare your results to the values computed by the websites you visited. Determine whether the websites treat the input annual interest rate as stated or effective. See Exercise2_23.java. 3.24

Develop an application that reads a purchase price and an amount tendered and then displays the change in dollars, quarters, dimes, nickels, and pennies. Two input values are entered in cents, for example, 3480 for $34.80 and 70 for $0.70. Use any appropriate technique for input and output. Display the output in the following format:

Notice the input values are to be entered in cents (int data type), but the echo-printed values must be displayed with decimal points (float data type). 3.25

MyJava Coffee Outlet runs a catalog business. It sells only one type of coffee beans, harvested exclusively in the remote area of Irian Java. The company sells the coffee in 2lb bags only, and the price of a single 2-lb bag is $5.50. When a customer places an order, the company ships the order in boxes. The boxes come in three sizes: the large box holds twenty 2-lb bags, the medium 10 bags, and the small 5 bags. The cost of a large box is $1.80; a medium box, $1.00; and a small box, $0.60. The order is shipped using the least number of boxes. For example, the order of 25 bags will be shipped in two boxes, one large and one small. Develop an application that computes the total cost of an order. Use any appropriate technique for input and output. Display the output in the following format:


3.26

Repeat exercise 25, but this time, accept the date when the order is placed and display the expected date of arrival. The expected date of arrival is two weeks (14 days) from the date of order. The order date is entered as a single string in the MM/dd/yyyy format. For example, November 1, 2004 is entered as 11/01/2004. There will be exactly two digits each for the month and day and four digits for the year. Display the output in the following format:

3.27

Using a Turtle object from the galapagos package (see exercise 23 on page 147) draw three rectangles. Use JOptionPane to accept the width and the length of the smallest rectangle from the user. The middle and the largest rectangles are 40 and 80 percent larger, respectively, than the smallest rectangle. The galapagos package and its documentation are available at www.drcaffeine.com/. See Exercise3_27.java.

3.28

Develop a program that draws a bar chart using a Turtle object (see exercise 23 on page 146). Input five int values and draw the vertical bars that represent the entered values in the following matter:


Your Turtle must draw everything shown in the diagram, including the axes and numbers. Use any suitable approach for input. See Exercise3_28.java.


Chapter 4 Solutions 1. Consider the following class declaration. class QuestionOne { public final int A = 345; public int b; private float c; private void methodOne( int a ) { b = a; } public float methodTwo() { return 23; } }

Identify invalid statements in the following main class. For each invalid statement, state why it is invalid. class Q1Main { public static void main( String[] args ) { QuestionOne q1; q1 = new QuestionOne(); 1 2

q1.A = 12; q1.b = 12; q1.c = 12;

3 4 5 6

q1.methodOne( 12 ); q1.methodOne(); System.out.println( q1.methodTwo( 12 ) ); q1.c = q1.methodTwo(); }

}

1. Data member A is a constant 2. Data member c is private 3. The method is private 4. Wrong number of arguments and the method is private 5. Wrong number of arguments 6. Data member c is private 2. What will be the output from the following code? class Q2Main { public static void main( String[] args ) { QuestionTwo q2; q2 = new QuestionTwo( ); q2.init(): q2.increment();


q2.increment(); System.out.println( q2.getCount() ); } } class QuestionTwo { private int count; public void init( ) { count = 1; } public void increment( ) { count = count + 1; } public int getCount() { return count; } }

3

3. What will be the output from the following code? Q3Main and QuestionThree classes are the slightly modified version of Q2Main and QuestionTwo. class Q3Main { public static void main( String[] args ) { QuestionThree q3; q3 = new QuestionThree( ); q3init(): q3.count = q3.increment() + q3.increment(); System.out.println( q2.increment() ); } } class QuestionThree { public int count; public void init( ) { count = 1; } public int increment() { count = count + 1; return count; } }

6


4. Is there any problem with the following class? Is the passing of an argument to the private methods appropriate? Are the data members appropriate? Explain. /* Problem Question4 */ class MyText { private String word; private String temp; private int idx; public String firstLetter( ) { idx = 0; return getLetter(word); } public String lastLetter( ) { idx = word.length() – 1; return getLetter(word); } private String getLetter(String str) { temp = str.substring(idx, idx+1); return temp; } }

The data member temp is unnecessary because it is only used in one function. A String parameter should not be passed to the getLetter function because the value of the String is already stored in the class. If any parameter were to go to the private method it could be the index of the letter to get. That would eliminate the need for storing the index and changing it each time firstLetter or lastLetter are called. 5. In the RollDice program, we created three Dice objects and rolled them once. Rewrite the program so you will create only one Dice object and roll it three times. See source in Exercise4_5 6. Modify the Bicycle class so instead of assigning the name of an owner (Student), you can assign the owner object itself. Model this new Bicycle class after the LibraryCard class. See source in Exercise4_6 7. Extend the LibraryCard class by adding the expiration date as a new property of a library card. Define the following four methods: //sets the expiration date


public void setExpDate(GregorianCalendar date) {...} //returns the expiration year public int getExpYear( ) { ... } //returns the expiration month public int getExpMonth( ) { ... } //returns the expiration day public int getExpDay( ) { ... }

8. Write a program that displays the recommended weight, given the user’s age and height. The formula for calculating the recommended weight is recommendedWeight = (height – 100 + age / 10) * 0.90

Define a service class named Height and include an appropriate method for getting a recommended weight of a designated height. See source in Exercise4_8 9. Write a program that computes the total ticket sales of a concert. There are three types of seatings: A, B, and C. The program accepts the number of tickets sold and the price of a ticket for each of the three types of seats. The total sales are computed as totalSales =

numberOfA_Seats * pricePerA_Seat + numberOfB_Seats * pricePerB_Seat + numberOfC_Seats * pricePerC_Seat;

Write this program, using only one class, the main class of the program. See source in Exercise4_9 10. Redo Exercise 9 by using a Seat class. An instance of the Seat class keeps track of the ticket price for a given type of seat (A, B, or C). See source in Exercise4_10 11. Write a program that computes the area of a circular region (the shaded area in the diagram) given the radii of the inner and the outer circles, ri and ro, respectively.


We compute the area of the circular region by subtracting the area of the inner circle from the area of the outer circle. Define a Circle class that has methods to compute the area and the circumference. You set the circle’s radius with the setRadius method or via a constructor. See source in Exercise4_11 12. Write a WeightConverter class. An instance of this class is created by passing the gravity of an object relative to the Earth’s gravity (see Exercise 12 on page 143). For example, the Moon’s gravity is approximately 0.167 of the Earth’s gravity, so we create a WeightConverter instance for the Moon as WeightConverter moonWeight; moonWeight = new WeightConverter( 0.167 );

To compute how much you weigh on the Moon, you pass your weight on Earth to the convert method as yourMoonWeight = moonWeight.convert( 160 );

Use this class and redo Exercise 12 on page 143. See source in Exercise4_12 13. Redo Exercise 26 on page 148, but this time, define and use programmer-defined classes. See source in Exercise4_13 14. Write a program that accepts the unit weight of a bag of coffee in pounds and the number of bags sold and displays the total price of the sale, computed as totalPrice = bagWeight * numberOfBags * procePerLb; totalPriceWithTax = totalPrice + totalPrice * taxrate;

Display the result in the following manner:


Define and use a programmer-defined CoffeeBag class. Include class constants for the price per pound and tax rate with the values $5.99 per pound and 7.25 percent, respectively. See source in Exercise4_14 15. In the Turtle exercises from earlier chapters, we dealt with only one Turtle (e.g., see Exercise 23 on page 146). It is possible, however, to let multiple turtles draw on a single drawing window. To associate multiple turtles to a single drawing, we create an instance of TurtleDrawingWindow and add turtles to it, as in TurtleDrawingWindow canvas = new TurtleDrawingWindow( ); Turtle winky, pinky, tinky; //create turtles; //pass Turtle.NO_DEFAULT_WINDOW as an argument so //no default drawing window is attached to a turtle. winky = new Turtle(Turtle.NO_DEFAULT_WINDOW); pinky = new Turtle(Turtle.NO_DEFAULT_WINDOW); tinky = new Turtle(Turtle.NO_DEFAULT_WINDOW); //now add turtles to the drawing window canvas.add( winky ); canvas.add( pinky ); canvas.add( tinky );

Ordinarily, when you start sending messages such as turn and move to a Turtle, it will begin moving immediately. When you have only one Turtle, this is fine. However, if you have multiple turtles and want them to start moving at the same time, you have to pause them, give instructions, and then command them to start moving. Here’s the basic idea: winky.pause( ); pinky.pause( ); tinky.pause( ); //give instructions to turtles here, //e.g., pinky.move(50); etc. //now let the turtles start moving winky.start( ); pinky.start( ); tinky.start( );


Using these Turtle objects, draw the following three triangles:

Use a different pen color for each triangle. Run the same program without pausing and describe what happens. See source in Exercise4_15 There is no visible difference between running the program with pausing and running it without. This is because there are so few commands that the sequence of calling is very short.


Chapter 5 Solutions 1. Indent the following if statements properly. a. if (a == b) if (c == d) a = 1; else b = 1; else

b.

c.

d.

c = 1; if (a == b) a = 1; if (c == d) b = 1; else c = 1; if (a == b) { if (c == d) a = 1; b = 2; } else b = 1; if (a == b) { if (c == d) a = 1; b = 2; } else { b = 1; if (a == d) d = 3; }

2. Which two of the following three if statements are equivalent? a. if (a == b) b. c.

if (c == d) a = 1; else b = 1; if (a == b) { if (c == d) a = 1; } else b = 1; if (a == b) if (c == d) a = 1; else b = 1;

a. and c. are equivalent. In both cases the else part is matching the (c == d) test. 3. Evaluate the following boolean expressions. For each of the following expressions, assume x is 10, y is 20, and z is 30. Indicate which of the following boolean expressions are always true


and which are always false, regardless of the values for x, y, or z. a. x < 10 || x > 10 b. x > y && y > x c. (x < y + z) && (x + 10 <= 20) d. z - y == x && Math.abs(y - z) == x e. x < 10 && x > 10 f. x > y || y > x g. !(x < y + z) || !(x + 10 <= 20) h. !(x == y)) && (x != y) && (x < y || y < x) a. false b. false (values for x and y are irrelevant) c. true d. true e. false (value for x is irrelevant) f. true g. false h. true 4. Express the following switch statement by using nested if statements. switch (grade) { case 10: case 9: a = 1; b = 2; break; case 8: a = 3; b = 4; break; default: a = 5; break; } if (grade == 10 || grade == 9) { a = 1; b = 2; } else if (grade == 8) { a = 3; b = 4; } else { a = 5; }

5. Write an if statement to find the smallest of three given integers without using the min method of the Math class. minimum = num1;


if (num2 < minimum) { minimum = num2; } if (num3 < minimum) { minimum = num3; }

6. Draw control flow diagrams for the following two switch statements. switch (choice) { case 1: a = 0; break; case 2: b = 1; break; case 3: c = 2; break; default: d = 3; break; }

switch (choice) { case 1: a = 0; case 2: b = 1; case 3: c = 2; default: d = 3; }

7. Write an if statement that prints out a message based on the following rules:


if (totalPoints >= 100) { System.out.print("You won a free cup of coffee"); } if (totalPoints >= 200) { System.out.println(" and"); System.out.print("a regular-size doughnut"); } if (totalPoints >= 300) { System.out.println(" and"); System.out.print("a 12 oz. orange juice"); } if (totalPoints >= 400) { System.out.println(" and"); System.out.print("a combo breakfast"); } if (totalPoints >= 500) { System.out.println(" and"); System.out.print("a reserved table for one week"); }

8. Rewrite the following if statement, using a switch statement. selection = Integer.parseInt( JOptionPane.showInputDialog(null, "Enter selection:")); if (selection == 0) System.out.println("You selected Magenta"); else if (selection == 1) System.out.println("You selected Cyan"); else if (selection == 2) System.out.println("You selected Red"); else if (selection == 3) System.out.println("You selected Blue"); else if (selection == 4) System.out.println("You selected Green"); else System.out.println("Invalid selection");


selection = Integer.parseInt( JOptionPane.showInputDialog(null, "Enter selection:")); switch(selection) { case 0: System.out.println("You selected Magenta"); break; case 1: System.out.println("You selected Cyan"); break; case 2: System.out.println("You selected Red"); break; case 3: System.out.println("You selected Blue"); break; case 4: System.out.println("You selected Green"); break; default: System.out.println("Invalid selection"); break; }

9. At the end of movie credits you see the year movies are produced in Roman numerals, for example, MCMXCVII for 1997. To help the production staff determine the correct Roman numeral for the production year, write an application that reads a year and displays the year in Roman numerals.

See Exercise5_9.java 10. Write a program that replies either Leap Year or Not a Leap Year, given a year. It is a leap year if the year is divisible by 4 but not by 100 (for example, 1796 is a leap year because it is divisible by 4 but not by 100). A year that is divisible by both 4 and 100 is a leap year if it is also divisible by 400 (for example, 2000 is a leap year, but 1800 is not). See Exercise5_10.java


11. One million is 106 and 1 billion is 109. Write a program that reads a power of 10 (6, 9, 12, etc.) and displays how big the number is (Million, Billion, etc.). Display an appropriate message for the input value that has no corresponding word. The table below shows the correspondence between the power of 10 and the word for that number.

See Exercise5_11.java 12. Write a program RecommendedWeightWithTest by extending the RecommendedWeight (see Exercise 8 on page 215). The extended program will include the following test: if (the height is between 140cm and 230cm) compute the recommended weight else display an error message. See Exercise5_12/RecommendedWeightTest.java 13. Extend the RecommendedWeightWithTest program in Exercise 12 by allowing the user to enter his or her weight and printing out the message You should exercise more if the weight is more than 10 lb over the ideal weight and You need more nourishment if the weight is more than 20 lb under the recommended weight. See Exercise5_13/RecommendedWeightTest.java 14. Employees at MyJava Lo-Fat Burgers earn the basic hourly wage of $7.25. They will receive time-and-a-half of their basic rate for overtime hours. In addition, they will receive a commission on the sales they generate while tending the counter. The commission is based on the following formula:

See Exercise5_14.java 15. Using the DrawingBoard class, write a screensaver that displays a scrolling text message. The text messages moves across the window, starting from the right edge toward the left edge. Set the motion type to stationary, so the DrawingBoard does not adjust the position. You have to


adjust the text’s position inside your DrawableShape. See Exercise5_15.java 16. Define a class called Triangle that is capable of computing the perimeter and area of a triangle, given its three sides a, b, and c, as shown below. Notice that side b is the base of the triangle.

The design of this class is identical to that for the Ch5Circle class from Section 5.1. Define a private method isValid to check the validity of three sides. If any one of them is invalid, the methods getArea and getPerimeter will return the constant INVALID_DIMENSION. See Exercise5_16.java 17. Modify the Ch5RoomWinner class so the three dorm lottery cards are drawn vertically. Make the code for drawing flexible by using the HEIGHT constant in determining the placement of three cards. See Exercise5_17.java 18. MyJava Coffee Outlet (see Exercise 25 from Chap. 3) decided to give discounts to volume buyers. The discount is based on the following table:

Each bag of beans costs $5.50.Write an application that accepts the number of bags ordered and prints out the total cost of the order in the following style.


Get complete Order files download link below https://www.mediafire.com/file/hiv6tkbgaqyvy3v/SM+ A+Comprehensive+Introduction+to+ObjectOriented+Programming+with+Java,+1e+C.+Thomas+W u.zip/file

If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.


See Exercise5_18.java 19. Combine Exercises 18 and 25 of Chap. 3 to compute the total charge including discount and shipping costs. The output should look like the following:

See Exercise5_19.java 20. You are hired by Expressimo Delivery Service to develop an application that computes the delivery charge. The company allows two types of packaging—letter and box—and three types of service—Next Day Priority, Next Day Standard, and 2-Day. The following table shows the formula for computing the charge:

The program will input three values from the user: type of package, type of service, and weight of the package. See Exercise5_20.java


21. Ms. Latte’s Mopeds ‘R Us rents mopeds at Monterey Beach Boardwalk. To promote business during the slow weekdays, the store gives a huge discount. The rental charges are as follows:

Write a program that computes the rental charge, given the type of moped, when it is rented (either weekday or weekend), and the number of hours rented. See Exercise5_21.java 22. Write an application program that teaches children how to read a clock. Use JOptionPane to enter the hour and minute. Accept only numbers between 0 and 12 for hour and between 0 and 59 for minute. Print out an appropriate error message for an invalid input value. Draw a clock that looks something like this:

To draw a clock hand, you use the drawLine method of the Graphics class. The endpoints of the line are determined as follows:


The value for constant K determines the length of the clock hand. Make the K larger for the minute hand than for the hour hand. The angle θ is expressed in radians. The angle θmin of the minute hand is computed as

and the angle θhr of the hour hand is computed as

where Hour and Minute are input values. The values 6.0 and 30.0 designate the degrees for 1 min and 1 h (i.e., the minute hand moves 6 degrees in 1 min and the hour hand moves 30.0 degrees in 1 h). The factor Π/180 converts a degree into the radian equivalent. You can draw the clock on the content pane of a frame window by getting the content pane’s Graphic object as described in the chapter. Here’s some sample code: import javax.swing.*; import java.awt.*; //for Graphics ... JFrame win; Container contentPane; Graphics g; ... win = new JFrame(); win.setSize(300, 300); win.setLocation(100,100); win.setVisible(true);


... contentPane = win.getContentPane(); g = contentPane.getGraphics(); g.drawOval(50,50,200,200);

See Exercise5_22.java 23. Extend the application in Exercise 22 by drawing a more realistic, betterlooking clock, such as this one:

See Exercise5_23.java 24. After starting a successful coffee beans outlet business, MyJava Coffee Outlet is now venturing into the fast-food business. The first thing the management decides is to eliminate the drive-through intercom. MyJava Lo-Fat Burgers is the only fast-food establishment in town that provides a computer screen and mouse for its drive-through customers. You are hired as a freelance computer consultant. Write a program that lists items for three menu categories: entree, side dish, and drink. The following table lists the items available for each entry and their prices. Choose appropriate methods for input and output.

See Exercise5_24.java


Solutions to Chapter 6 1. Identify all the errors in the following repetition statements. Some errors are syntactical while others are logical (e.g., infinite loops). a. for (int i = 10; i > 0; i++ ) { x = y; a = b; }

Infinite loop: i is always greater than 0. b.

sum = 0; do { num = Integer.parseInt( JOptionPane.showInputDialog(null, "Enter value:")); sum += num; } until (sum > 10000) ;

until is not a valid reserved word in Java. while should be used. c. while ( x < 1 && x > 10) { a = b; }

The conditional expression is never true. d.

while ( a == b ); { a = b; x = y; }

Syntax error: no semicolon after the conditional expression. e.

for ( int i = 1.0; i <= 2.0; i += 0.1 ) { x = y; a = b; }

i should be a double or the initial, condition and increment values should be integers. 2. Write for, do-while, and while statements to compute the following sums and products. a. 1 + 2 + 3 + ... + 100 int sum = 0;


for ( int i = 1; i <= 100; i++ ) { sum = sum + i; } int sum = 0, i = 1; do { sum = sum + i; i++; } while (i <= 100); int sum = 0, i = 1; while (i <= 100) { sum = sum + i; i++; }

b. 5 + 10 + 15 + … + 50 int sum = 0; for ( int i = 5; i <= 50; i+=5 ) { sum = sum + i; } int sum = 0, i = 5; do { sum = sum + i; i += 5; } while (i <= 50); int sum = 0, i = 5; while (i <= 50) { sum = sum + i; i += 5; }

c. 1 + 3 + 7 + 15 + 31 + ... + (220 - 1) int sum = 0; for ( int i = 1; i <= 20; i++ ) { sum = sum + (int) Math.pow(2,i) - 1; } int sum = 0, i = 1; do { sum = sum + (int) Math.pow(2,i)-1; i++; } while (i <= 20); int sum = 0, i = 1; while (i <= 20) { sum = sum + (int) Math.pow(2,i) - 1;


i++; }

d. 1 + 1/2 + 1/3 + 1/4 + ... + 1/15 float sum = 0; for ( int i = 1; i <= 15; i++ ) { sum = sum + 1.0f / i; } float sum = 0, i = 1; do { sum = sum + 1.0f / i; i++; } while (i <= 15); float sum = 0, i = 1; while (i <= 15) { sum = sum + 1.0f / i; i++; }

e. 1  2  3  ...  20 int product = 1; for ( int i = 1; i <= 20; i++ ) { product = product * i; } int product = 1, i = 1; do { product = product * i; i++; } while (i <= 20); int product = 1, i = 1; while (i <= 20) { product = product * i; i++; }

f. 1  2  4  8  ...  220 int product = 1; for ( int i = 0; i <= 20; i++ ) { product = product * (int) Math.pow(2,i); } int product = 1, i = 0; do {


product = product * (int) Math.pow(2,i); i++; } while (i <= 20); int product = 1, i = 0; while (i <= 20) { product = product * (int) Math.pow(2,i); i++; }

3. What will be the value of sum after each of the following nested loops is executed? a. sum = 0; for (int i = 0; i <= 10; i++ ) { for ( int j = 0; j <= 10; j++ ) { sum += i; } }

605 b. sum = 0; j = 0; do { j++; for ( int i = 5; i > j; i-- ) { sum = sum + (i+j); } } while ( j < 11 );

60 c. sum = 0; i = 0; while ( i < 5 ) { j = 5; while (i != j) { sum += j; j--; } i++; }

55 d. sum = 0;


for (int i = 0; i <= 10; i++) { for (int j = 10; j > 2*i; j-- ) sum = sum + (j - i); }

165 4. Determine the output from the following code without actually executing it. System.out.format("%4d", 234); System.out.format("%5d", 234); System.out.format("%s", "\n"); System.out.format("$%6.2f", 23.456); System.out.format("%s", "\n"); System.out.format("%1$3d+%1$3d=%2$5d", 5, (5+5));

NOTE: Blank space is denoted by an underscore. Underscores are not a part of real output. _234 234 $_23.46 5+ 5=

10

5. Rewrite the following nested-for statements using nested do-while and while statements. a. sum = 0; number = 0; for (int i = 0; i <= 10; i++ ) { for (int j = 10; j >= i; j-- ) { number++; sum = sum + (j - i); } }

sum = 0; number = 0; i = 0; do { j = 10; do { number++; sum = sum + (j-i); j--; } while ( j >= i );


i++; } while ( i <= 10 );

sum = 0; number = 0; i = 0; while ( i <= 10 ) { j = 10; while ( j <= i ) { number++; sum = sum + ( j - i); j--; } i++; }

b. product = 1; number = 0; for ( int i = 1; i < 5; i++ ) { for ( int j = 1; j < 5; j++ ) { number++; product *= number; } } product = 1; number = 0; i = 1; do { j = 1; do { number++; product *= number; j++; } while ( j < 5 ); i++; } while ( i < 5 ); product = 1; number = 0; i = 1; while ( i < 5 ) { j = 1;


while ( j < 5 ) { number++; product *= number; j++; } i++; }

6. You can compute sin x cos x, using the following power series:

Write a program that evaluates sin x and cos x, using the power series. Use the double data type and increase the number of terms in the series until the overflow occurs. You can check if the overflow occurs by comparing the value against Double.POSITIVE_INFINITY. Compare the results you obtained to the values returned by the sin and cos methods of the Math class. The program computes the power series until the overflow occurs. It is important that the ‘denominator’ is checked against the overflow, because when the denominator overflows the ith term becomes zero. This causes the sum to remain the same value once the denominator overflows. Thus the sum will never overflow— infinite loop. See Exercise6_06.java 7. Write an application to print out the numbers 10 through 49 in the following manner: 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

How would you do it? Here is an example of poorly written code: for ( int i = 10; i < 50; i++ ) { switch (i) { case 19: case 29: case 39: System.out.println(" " + i); // move to the next line break: default: System.out.println(" " + i); }


}

This code is not good because it works only for printing 10 through 49. Try to develop the code so that it can be extended easily to handle any range of values. You can do this coding in two ways: with a nested-for statement or with modulo arithmetic. (If you divide a number by 10 and the remainder is 9, then the number is 9, 19, 29, or 39, and so forth.) Nested-for loop: for (int i = 10; i < 50; i += 10 ) { for (int j = 0; j < 9; j++) { System.out.println(" " + (i+j) ); } System.out.println(" " + (i+9)); }

Modulo arithmetic: for (int i = 10; i < 50; i++ ) { num = i % 10; switch (num) { case 9: System.out.println( " " + i ); break; default: System.out.println( " " + i); } }

See Exercise6_07.java Notice the use of constants in the program. Experiment by changing the values for STARTING_NUMBER, ENDING_NUMBER, and INCREMENT. For example, change INCREMENT to 5 and see what happens. 8. A prime number is an integer greater than 1 and divisible only by itself and 1. The first seven prime numbers are 2, 3, 5, 7, 11, 13, and 17. Write a method that returns true if its parameter is a prime number. public static boolean isPrime( int num ) { boolean isPrime = false; if ( num > 1 ) { isPrime = true; for ( int i = (int) Math.sqrt(num); i > 1 && isPrime; i-- ) { if ( num % i == 0 ) { isPrime = false; } } } return isPrime;


} }

See Exercise6_08.java 9. There are 25 primes between 2 and 100, and there are 1229 primes between 2 and 10,000. Write a program that inputs a positive integer N > 2 and displays the number of primes between 2 and N (inclusive). Use the timing technique explained in Section 6.10 to show the amount of time it took to compute the result. See Excercise6_09.java 10. Instead of actually computing the number of primes between 2 and N, we can get an estimate by using the prime number theorem, which states that

Where prime(N) is the number of primes between 2 and N (inclusive). The function ln is the natural logarithm. Extend the program for Exercise 9 by printing the estimate along with the actual number. You should notice the pattern that the estimate approaches the actual number as the value of N gets larger. See Excercise6_10.java 11. A perfect number is a positive integer that is equal to the sum of its proper divisors. A proper divisor is a positive integer other than the number itself that divides the number evenly (i.e., no remainder). For example, six is a perfect number because the sum of its proper divisors 1, 2, and 3 is equal to 6. Eight is not a perfect number because 1 + 2 + 4 ≠ 8. Write an application that accepts a positive integer and determines whether the number is perfect. Also, display all proper divisors of the number. Try a number between 20 and 30 and another number between 490 and 500. See Excercise6_11.java 12. Write an application that lists all perfect numbers between six and N, an upper limit entered by the user. After verifying the program with a small number for N, gradually increase the value for N and see how long the program takes to generate the perfect numbers. Since there are only a few perfect numbers, you might want to display the numbers that are not perfect so you can easily tell that the program is still running. See Excercise6_12.java 13. Write a program that displays all integers between low and high that are the sum of the cube of their digits. In other words, find all numbers xyz such that xyz = x3 + y3 + z3, for example, 153 = 13 + 53 + 33. Try 100 for low and 1000 for high.


See Exercise6_13.java 14. Write a method that returns the number of digits in an integer argument; for example, 23,498 has five digits. public static int numDigits( int num ) { return (int) (Math.log(num) / Math.log(10)); }

See Exercise6_14.java 15. Your freelance work with MyJava Lo-Fat Burgers was a success (see exercise 22 of Chapter 5). The management loved your new drive-through ordering system because the customer had to order an item from each of the three menu categories. As part of a public relations campaign, however, management decided to allow a customer to skip a menu category. Modify the program to handle this option. Before listing items from each category, use a confirmation dialog to ask the customer whether he or she wants to order an item from that category. See Exercise6_15_MenuIem.java, Exercise6_15_DriveThruControl2.java, Exercise6_15_MenuCategory.java, and Exercise6_15_MenuIem.java 16. Extend the program from Exercise 15 so that customers can order more than one item from each menu category. For example, the customer can buy two orders of Tofu Burgers and three orders of Buffalo Wings from the Entree menu category. See Exercise6_16.java, Exercise6_16_DriveThruControl2.java, and Exercise6_16_MenuCategory.java 17. Complete the loan table application discussed in Section 6.9. See Exercise6_17.java 18. Implement the describeRules method of the HiLo class from Section 6.10. Use a confirmation dialog to ask the user whether to display the game rules. See Exercise6_18.java 19. The price table for carpet we printed out in Section 6.7 contains index values for width and length, but not labels to identify them. Write an application to generate the table shown next:


See Exercise6_19.java 20. Extend the HiLo class to allow the user to designate the lower and upper bounds of the secret number. In the original HiLo class, the bounds are set to 1 and 100, respectively. See Exercise6_20.java 21. A formula to compute the Nth Fibonacci number was given in exercise 19 in Chapter 3. The formula is useful in finding a number in the sequence, but a more efficient way to output a series of numbers in the sequence is to use the recurrence relation FN = FN1 + FN-2, with the first two numbers in the sequence F1 and F2 both defined as 1. Using this recurrence relation, we can compute the first 10 Fibonacci numbers as follows: F1 = 1 F2 = 1 F3 = F2 + F1 = 1 + 1 = 2 F4 = F3 + F2 = 2 + 1 = 3 F5 = F4 + F3 = 3 + 2 = 5 F6 = F5 + F4 = 5 + 3 = 8 F7 = F6 + F5 = 8 + 5 = 13 F8 = F7 + F6 = 13 + 8 = 21 F9 = F8 + F7 = 21 + 13 = 34 F10 = F9 + F8 = 34 + 21 = 55

Write an application that accepts N, N ≥ 1, from the user and displays the first N numbers in the Fibonacci sequence. Use appropriate formatting to display the output cleanly. See Exercise6-21.java. NOTE: Due to the size limitation of the data type int, the largest value for N that


does not cause an overflow is 46. Any N bigger than 46 will result in an overflow. To avoid the overflow you can use the BigInteger class that can represent an integer value with arbitrary precision (i.e. its precision is made as large as necessary to accommodate the number).

22. Modify the application of Exercise 21 to generate and display all the numbers in the sequence until a number becomes larger than the value maxNumber entered by the user. See Exercise6_22.java 23. Improve the LoanCalculator class from Chapter 4 to accept only the valid input values for loan amount, interest rate, and loan period. The original LoanCalculator class assumed the input values were valid. For the exercise, let the loan amount between $100.00 and $1,000,000.00, the interest rate between 5 and 20 percent, and the load period between 1 year and 30 years be valid. See Exercise6_23.java, Exercise6_23_LoanCalculator.java, and Exercise6_23_Loan.java 24. Extend Exercise 20 in Chapter 5 by drawing a more realistic clock. Instead of drawing a clock like this

Draw a circle at 5-minute intervals as follows:


Use a for loop to draw 12 circles. See Exercise6_24.java and Exercise6_24_ClockHand.java 25. In the formatting examples from the chapter, we always provided a fixed control string, such as System.out.format("%4d", 23);

It is possible, however, to dynamically create the control string, as in int i = 4; System.out.format("%" + i + "d", 23);

Using this idea of dynamically creating a control string, write a code fragment that outputs 50 X’s, using a separate line for each X. An X on a single line is preceded by two more leading spaces than the X on the previous line. The following figure shows the output for the first five lines.

See Exercise6_25.java 26. (Optional) Write a recursive method to compute the sum of the first N positive integers. Note: This is strictly for exercise. You should not write the real method


recursively. See Excercise6_26.java 27. (Optional) Write a recursive method to compute the sum of the first N positive odd integers. Note: This is strictly for exercise. You should not write the real method recursively. See Excercise6_27.java 28. Write an application that draws nested N squares, where N is an input to the program. The smallest square is 10 pixels wide, and the width of each successive square increases by 10 pixels. The following pattern shows seven squares whose sides are 10, 20, 30,… and 70 pixels wide.

See Exercise6_28.java, Exercise6_28_NestedSquares.java, and Exercise6_28.doc 29. The monthly payments for a given loan are divided into amounts that apply to the principal and to the interest. For example, if you make a monthly payment of $500, only a portion of the $500 goes to the principal and the remainder is the interest payment. The monthly interest is computed by multiplying the monthly interest rate by the unpaid balance. The monthly payment minus the monthly interest is the amount applied to the principal. The following table is the sample loan payment schedule for a one-year loan of $5,000 with a 12 percent annual interest rate.


Write an application that accepts a loan amount, annual interest rate, and loan period (in number of years) and displays a table with five columns: payment number, the interest and principal paid for that month, the remaining balance after the payment, and the total interest paid to date. Note: The last payment is generally different from the monthly payment, and your application should print out the correct amount for the last payment. Use the Format class to align the output values neatly. See Exercise6_29.java, Exercise6_29_PaymentSchedule.java, and Exercise6_29.doc 30. Instead of dropping a watermelon from a building, let’s shoot it from a cannon and compute its projectile. The (x, y) coordinates of a watermelon at time t are

where g is the acceleration of gravity, V is the initial velocity, and alpha is the initial angle. The acceleration of gravity on earth is 9.8 m/sec2.


Write an application that inputs an initial velocity V (m/sec) and an initial angle alpha (in degrees) and computes the projectile of a watermelon cannon ball. The program should repeat the computation until the user wants to quit. The program outputs the (x,y) coordinate value for every second, that is, t = 0, 1, 2, and so forth. The program stops the output when the y value becomes zero or less. To use the cos and sin methods of the Math class, don’t forget that you have to convert the input angle given in degrees to radians. You can convert a degree to the equivalent radians using the following Radian = degree   / 180 Or calling toRadians method of the Math class. Note: Air resistance is not considered in the formula. Also, we assumed the watermelon will not get smashed at firing. See Exercise6_30.java, Exercise6_30_WaterMelon.java, and Exercise6_30.doc 31. Write an application that simulates a slot machine. The player starts out with M coins. The value of M is an input to the program, and you charge 25 cents per coin. For each play, the player can bet 1 to 4 coins. If the player enters 0 as the number of coins to bet, then the program stops playing. At the end of the game, the program displays the number of coins left and how much the player won or lost in the dollar amount. There are three slots on the machine, and each slow will display one of the three possible pieces: BELL, GRAPE, and CHERRY. When certain combinations appear on the slots, the machine will pay the player. The payoff combinations are these: 1 2 3 4 5 6 7 8 9

BELL GRAPES CHERRY CHERRY CHERRY ---------CHERRY ------------------

BELL GRAPES CHERRY CHERRY ---------CHERRY --------CHERRY ----------

BELL GRAPES CHERRY ----------CHERRY CHERRY ------------------CHERRY

10 7 5 3 3 3 1 1 1

The symbol ---------- means any piece. If the player bets 4 coins and gets combination 5, for example, the machine pays the player 12 coins. See Exercise6_31.java, Exercise6_31_SlotMachine.java, and Exercise6_31.doc


Chapter 7 Solutions 1. Consider the following classes. class Cat { private String name; private Breed breed; private double weight; public Cat(String name, Breed breed, double weight){ this.name = name; this.breed = breed; this.weight = weight; } public Breed getBreed() { return breed; } public double getWeight() { return weight; } //other accessors and mutators . . . } class Breed { private String name; private double averageWgt; //in lbs. public Breed(String name, double averageWgt){ this.name = name; this.averageWgt = averageWgt; } public double getWeight( ) { return averageWgt; } //other accessors and mutators . . . }

Identify the invalid statements in the following main class. For each invalid statement, state why it is invalid. class Q1Main { public static void main( String[] args ) { Breed persian = new Breed("Persian", 10.0); Cat chacha = new Cat("Cha Cha", persian, 12.0); Cat bombom = new Cat("Bom Bom", "mix", 10.0);  1


Cat puffpuff = new Cat("Puff Puff", chacha, 9.0);  2 double diff = chacha.getWeight() - persian.getWeight(); System.out.println( puffpuff.getBreed().getWeight()); } }

1: “mix” is a String, not a Breed 2: chacha is a Cat, not a Breed 2. Given the Cat and Breed classes from Exercise 1, what will be the output from the following code? class Q2Main { public static void main( String[] args ) { Cat myCat = new Cat("winky", new Breed("mix", 10.5), 9.5); System.out.println(myCat.getWeight()); System.out.println(myCat.getBreed().getWeight()); } }

9.5 10.5 3. Given the Fraction class from Section 7.8, draw the state-of-memory diagram at the point immediately after the last statement is executed. Fraction f1, f2, f3; f1 = new Fraction(3, 8); f2 = new Fraction(2, 3); f3 = f1.add(f2);


f1

this

f2

sum

f3

: Fraction

: Fraction

: Fraction

numerator = 2 denominator = 3

numerator = 3 denominator = 8

numerator = 25 denominator = 24

4. Consider the following class. class Dog { . . . private double weight; . . . public boolean isBiggerThan(Dog buddy) { return this.getWeight() > buddy.getWeight(); } public double getWeight() { return weight; } . . . }

For each of the following codes, complete the state-of-memory diagram by filling in the arrows for this and buddy. a. Dog tuffy = new Dog(...); Dog puffy = new Dog(...); puffy.isBiggerThan(tuffy);


b.

Dog tuffy = new Dog(...); Dog puffy = new Dog(...); tuffy.isBiggerThan(puffy);

5. Complete the following constructor. class Student { private String name; private int age; private Address address; public Student(String name, int age, Address address){ //assign passed values to the data members }

Answer: public Student(String name, int age, Address address){


//assign passed values to the data members this.name = name; this.age = age; this.address = address; }

6. Which of the following groups of overloaded constructors are valid? a. public Cat(int age) { ... } b. c. d.

public Cat(double wgt) { ... } public Dog(String name, double weight) { ... } public Dog(String name, double height) { ... } public Dog(String name, double weight) { ... } public Dog(double weight, String name) { ... } public Cat(String name) { ... } public Cat(String name, double weight) { ... } public Cat(double weight) { ... }

All the groups are valid except b, because both constructors have the same signature: Dog(String, double) 7. Which of the following groups of overloaded methods are valid? a. public void compute(int num) { ... } b. c. d.

public int compute(double num) { ... } public void move(double length) { ... } public void move( ) { ... } public int adjust(double amount) { ... } public void adjust(double amount, double charge) { ... } public void doWork( ) { ... } public void doWork(String name) { ... } public int doWork(double num) { ... }

All of them are valid (all the signatures are different). 8. Complete the first four constructors of the following class. Each of the four constructors calls the fifth one by using the reserved word this. class Cat { private static final String DEFAULT_NAME = "No name"; private static final int DEFAULT_HGT = 6; private static final double DEFAULT_WGT = 10.0; private String name; private int height; private double weight; public Cat( ) { //assign defaults to all data members } public Cat(String name) {


//assign the passed name to the data member //use defaults for height and weight } public Cat(String name, int height) { //assign passed values to name and height //use default for weight } public Cat(String name, double weight) { //assign passed values to name and weight //use default for height } public Cat(String name, int height, double weight){ this.name = name; this.height = height; this.weight = weight; } . . . }

Answer: public Cat( ) { this(DEFAULT_NAME, DEFAULT_HGT, DEFAULT_WGT); } public Cat(String name) { this(name, DEFAULT_HGT, DEFAULT_WGT); } public Cat(String name, int height) { this(name, height, DEFAULT_WGT); } public Cat(String name, double weight) { this(name, DEFAULT_HGT, weight); }

9. Define a class method (static) named compare to the Fraction class. The compare method accepts two Fraction objects f1 and f2. The method returns -1 if f1 is less than f2 0 if f1 is equal to f2 +1 if f1 is greater than f2 public static compare(Fraction f1, Fraction f2) { return f1.decimal() – f2.decimal(); }


10. Rewrite the compare method from Exercise 9 by changing it to an instance method. This method accepts a Fraction object and compares it to the receiving object. The method is declared as follows: public int compare(Fraction frac) { //compare the Fraction objects this and frac //return the result of comparison }

Answer: public int compare(Fraction frac) { return decimal() – frac.decimal(); }

11. Discuss the pros and cons of the compare methods from Exercise 8 and Exercise 9. Both ways of implementing the compare method yield very similar results. In this case, having a class method does not really give any advantages, since we need to have two Fractions to begin with, so we could as easily use the compare method of one of them. 12. Consider the following class. class Modifier { public static change(int x, int y){ x = x - 10; y = y + 10; } }

What will be an output from the following code? int x = 40; int y = 20; Modifier.change(x,y); System.out.println("x = " + x); System.out.println("y = " + y); x = 40 y = 20

13. Modify the following class to make it a part of the package named myutil. In addition to adjusting the source file, what are the steps you need to take so that the class becomes usable/accessible from other classes that are outside of this myutil package? class Person { private String name; public Person( ) { name = "Unknown"; } public String getName() {


return name; } public void setName(String name) { this.name = name; } }

First we need to modify the class as follows: package myutil; public class Person { private String name; public Person( ) { name = "Unknown"; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

Then, we need to place the modified Person class into the myutil folder (we need to create the folder if this is the first class we add to the package). Finally, if we have not done so before, we need to modify the CLASSPATH environment variable to include the folder that contains the myutil folder. 14. Reimplement the Library Overdue Checker program by replacing console input with JOptionPane. See Exercise7_14.java 15. (Optional) Although we have not discussed the internal workings of the BookTracker class, it is not too difficult to realize the portion that handles the generation of book list. Define a new method called getListWithCharge based on the getList method. Generate a book list as the getList method does, but include the overdue charge for each book also. See BookTracker.java 16. Design a class that keeps track of a student’s food purchases at the campus cafeteria. A meal card is assigned to an individual student. When a meal card is first issued, the balance is set to the number of points. If the student does not specify the number of points, then the initial balance is set to 100 points. Points assigned to each food item are a whole number. A student can purchase additional points at any time during a semester.


Every time food items are bought, points are deducted from the balance. If the balance becomes negative, the purchase of food items is not allowed. There is obviously more than one way to implement the MealCard class. Any design that supports the key functionalities is acceptable. See MealCard.java 17. Write an application that plays the game of Fermi. Generate three distinct random digits between 0 and 9. These digits are assigned to positions 1, 2, and 3. The goal of the game is for the player to guess the digits in three positions correctly in the least number of tries. For each guess, the player provides three digits for positions 1, 2, and 3. The program replies with a hint consisting of Fermi, Pico, or Nano. If the digit guessed for a given position is correct, then the reply is Fermi. If the digit guessed for a given position is in a different position, the reply is Pico. If the digit guessed for a given position does not match any of the three digits, then the reply is Nano. Here are sample replies for the three secret digits 6, 5, and 8 at positions 1, 2, and 3, respectively:

Notice that if the hints like the above are given, the player can tell which number did not match. For example, given the hint for the second guess, we can tell that 3 is not one of the secret numbers. To avoid this, provide hints in a random order or in alphabetical order (e.g., it will be Fermi Nano Pico instead of Pico Fermi Nano for the second reply). Play games repeatedly until the player wants to quit. After each game, display the number of guesses made. Use javadoc comments to document the classes you design for this application. See Exercise7_17.java, Fermi.java and Exercise7_17.doc

18. Write an application that teaches children fraction arithmetic. For each training session, randomly generate 10 questions involving addition, subtraction, division, and multiplication of two fractions. Use either JOptionPane or the console I/O to display questions and get answers from the user. At the beginning of each session, the user has the option of specifying the time limit for answering the questions. If the time limit is not specified, then use 30 s as a default time limit. After you pose a question, wait until the user answers the question. Award points based on the following rules:


After one session is over, use the console output to display the grade distribution and the total points in the following manner:

After one session is over, give the user the option to play another session.


Solutions to Chapter 8 1. Determine the output of the following code when the input is (a) –1, (b) 0, and (c) 12XY try { number = Integer.parseInt( JOptionPane.showInputDialog(null, "input")); if (number != 0) { throw new Exception("Not Zero"); } } catch (NumberFormatException e) { System.out.println("Cannot convert to int"); } catch (Exception e) { System.out.println("Error: " + e.getMessage());

a) Error: Not Zero b) no output c) Cannot convert to int 2. Determine the output of the following code when the input is (a) –1, (b) 0, and (c) 12XY. This is the same question as Exercise 1, but the code here has the finally clause. try { number = Integer.parseInt( JOptionPane.showInputDialog(null, "input")); if (number != 0) { throw new Exception("Not Zero"); } } catch (NumberFormatException e) { System.out.println("Cannot convert to int"); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } finally { System.out.println("Finally Clause Executed"); }

a) Error: Not Zero Finally Clause Executed b) Finally Clause Executed c) Cannot convert to int Finally Clause Executed 3. Why is the following code not a good use of the assertion? public void compute(int size) { assert size > 0; //computation code comes here


}

We should throw an exception because the argument is invalid instead of using an assertion. Remember: use assertions to detect internal errors and use exceptions to notify the client programmers of the misuse of our class. 4. Modify the following code by adding the assert statement. The value of gender is either MALE or FEMALE if the program is running correctly. switch (gender) { case MALE: totalFee = tuition + parkingFee; break; case FEMALE: totalFee = tuition + roomAndBoard; break; }

We can add a control flow invariant as follows: switch (gender) { case MALE: totalFee = tuition + parkingFee; break; case FEMALE: totalFee = tuition + roomAndBoard; break; default: assert false: "Value of gender " + "is invalid. Value = " + gender; }

5. Modify the following method by adding the assert statement. Assume the variable factor is a data member of the class. public double compute(double value) { return (value * value) / factor; }

We can add a precondition assertion as follows: public double compute(double value) { assert factor != 0 : "Serious Error – factor == 0, which will lead " "to a division by zero"; return (value * value) / factor; }

6. Modify the getInput method of the InputHandler class from Section 8.7 so that the method will throw an exception when an empty string is entered for the name, room, or password. Define a new exception class EmptyInputException.


public void getInput( ) { throws new EmptyInputException name = JOptionPane.showInputDialog(null, "Enter Name:"); if (name.trim().equals("")) throw new EmptyInputException("Name should not be empty"); room = JOptionPane.showInputDialog(null, "Enter Room No.:"); if (room.trim().equals("")) throw new EmptyInputException("Room should not be empty"); pwd = JOptionPane.showInputDialog(null, "Enter Password:"); if (pwd.trim().equals("")) throw new EmptyInputException("Password should not be empty"); } class EmptyInputException extends Exception { private static final String DEFAULT_MESSAGE = "Empty input string"; public EmptyInputException (String msg) { super(msg); } }

7. The user module of the keyless entry system in Section 8.7 does not include any logic to terminate the program. Modify the program so it will terminate when the values Admin, X123, and $maTrix%TwO$ are entered for name, room, and password, respectively. This only requires changing the validate method in Ch8EntranceMonitor, and possibly adding some new constants. See Ch8EntranceMonitor.java Development Exercises 8. In the sample development, we developed the user module of the keyless entry system. For this exercise, implement the administrative module that allows the system administrator to add and delete Resident objects and modify information on existing Resident objects. The module will also allow the user to open a list from a file and save the list to a file. Is it proper to implement the administrative module by using one class? Wouldn’t it be a better design if we used multiple classes with each class doing a single well-defined task? The solution here splits the problem into two classes, one to handle functionality and one to handle the interface. See files AdminHandler.java and Ch8EntranceAdmin.java 9. Write an application that maintains the membership lists of five social clubs in a dormitory. The five social clubs are the Computer Science Club, Biology Club, Billiard Club, No Sleep Club, and Wine Tasting Club. Use the Dorm class to manage the membership lists. Members of the social clubs are Resident objects of the dorm. Use a separate file to store the membership list for each club. Your program should be able to include a menu item for each social club. When a club is selected, open a ClubFrame frame that will allow the user


to add, delete, or modify members of the club. The program can have up to five ClubFrame frames opened at the same time. Make sure you do not open multiple instances of ClubFrame for the same club. See files ClubFrame.java, ClubKeeper.java, Dorm.java, DormAdmin.java, and Resident.java


Solutions to Chapter 9 1. What is the difference between ‘a’ and “a”? ‘a’ is a char type, while “a” is a String with one character in it. 2. Discuss the difference between str = str + word; //string concatenation

and tempStringBuffer.append(word);

where str is a String object and tempStringBuffer is a StringBuffer object. With the string concatenation, a new String object is created while the original strings remain intact. In case of the statement str = str + word;

the original str is concatenated with word forming a new string. The result is assigned to the same variable as str, which now refers to the newly formed string. With the append method of StringBuffer, no new string is created. The string word is attached to the end of tempStringBuffer, which continues to refer to the same StringBuffer object. 3. Show that if x and y are String objects and x == y is true, then x.equals(y) is also true, but the reverse is not necessarily true. If x == y is true, then it means both x and y refer to the same String object. So naturally, x.equals(y) must also be true. On the other hand, if x.equals(y) is true, it only means x and y refer to String objects that contain the same sequence of characters. They could very well be distinct String objects that just happen to contain the same sequence of characters. 4. What will be the output from the following code? StringBuffer word1, word2; word1 = new StringBuffer(“Lisa”); word2 = word1; word2.insert(0, “Mona “); System.out.println(word1);

Mona Lisa

5. Show the state of memory after the execution of each statement in the following code:


String word1, word2; word1 = “Hello”; word2 = word1; word1 = “Java”;

String word1, word2; word1

word2

word1 = “Hello”; word1

word2

word2 = word1; word1

word2

word1 = “Java”; String word1

word2

String

6. Using a state-of-memory diagram, illustrate the difference between a null string and an empty string – a string that has no characters in it. Show the state-of-memory diagram for the following code. Variable word1 is a null string, while word2 is an empty string. String word1, word2; word1 = null; word2 = “”;


word1

word2

7. Using a state-of-memory diagram, show how the following two groups of statements differ. String word1, word2;

String word1, word2;

word1 = “French Roast”; word2 = word1;

word1 = “French Roast”; word2 = “French Roast”; String word1

word1

String

word2

String

Roast

word2

8. Write an application that reads in a character and displays the character’s ASCII. The getText method of the JTextField class returns a String object, so you need to use a char value, as in String inputString = inputField.getText(); char character = inputString.charAt(0);

Display an error message if more than one character is entered. See file ASCIICode.java 9. Write a method that returns the number of uppercase letters in a String object passed to the method as an argument. Use the class method isUpperCase of the Character class, which returns true if the passed parameter of type char is an uppercase letter. You need to explore the Character class from the java.lang package on your own. public int countUpper( String str ) { int maxLength = str.length(); int countUpper = 0; char letter; for(int i = 0; i < maxLength; i++) { letter = str.charAt(i);


if( Character.isUpperCase(letter) ) { countUpper++; } } return countUpper; }

10. Redo Exercise 9 without using the Character class. Hint: The ASCII code of any uppercase letter will fall between 65 (code for ‘A’) and 90 (code for ‘Z’). public int countUpper( String str ) { int maxLength = str.length(); int countUpper = 0; int asciiCode; for(int i = 0; i < maxLength; i++) { asciiCode = (int)str.charAt(i); if( asciiCode >= 65 && asciiCode <= 90 ) { countUpper++; } } return countUpper; }

11. Write a program that reads a sentence and prints out the sentence with all uppercase letters changed to lowercase and all lowercase letters changed to uppercase. See file ReverseCase.java 12. Write a program that reads a sentence and prints out the sentence in reverse order. For example, the method will display ?ouy era who

for the input How are you?

See file ReverseSentence.java 13. Write a method that transposes words in a given sentence. For example, given an input sentence The gate to Java nirvana is near

The method outputs


ehT etag ot avaJ anavrin si raen

To simplify the problem, you may assume the input sentence contains no punctuation marks. You may also assume that the input sentence starts with a nonblank character and that there is exactly one blank space between the words. public void transposeWords(String str) { StringBuffer string = new StringBuffer(str); String substr = new String(); int beginIndex = 0; int endIndex = -1; do { beginIndex = endIndex + 1; endIndex = string.indexOf(" ", beginIndex); if( endIndex == -1 ) endIndex = string.length(); substr = string.substring(beginIndex, endIndex); substr = (new StringBuffer(substr).reverse()).toString(); string.replace(beginIndex, endIndex, substr); } while (endIndex != string.length()); System.out.println(string); }

14. Improve the method in Exercise 13 by removing the assumptions. For example, an input sentence could be Hello, how are you? I use JDK 1.2.2.

Bye-bye.

An input sentence may contain punctuation marks and more than one blank space between two words. Transposing the above will result in olleh, who era uoy? I esu KDJ 1.2.2. eyB-eyb.

Notice the position of punctuation marks does not change and only one blank space is inserted between the transposed words. public void transposeComplex(String str) { StringBuffer string = new StringBuffer(str.trim()); String substr = new String(); int beginIndex = 0; int endIndex = 0; int spaces = 0; do { // Take care of multiple spaces while( (beginIndex + spaces) < string.length() && (string.charAt(beginIndex + spaces) == ' ') ) spaces++; if(spaces > 1) {


string.replace(beginIndex, beginIndex + spaces, " "); } // Find the word boundary while( endIndex < string.length() && (string.substring(endIndex, endIndex + 1)).matches("[a-zA-Z0-9]") ) endIndex++; // Do the transposing if (endIndex <= string.length()) { substr = string.substring(beginIndex, endIndex); substr = (new StringBuffer(substr).reverse()).toString(); string.replace(beginIndex, endIndex, substr); } beginIndex = ++endIndex; spaces = 0; } while(endIndex < string.length()); System.out.println(string); }

15. The Ch9CountWords program that counts the number of words in a given sentence has a bug. If the input sentence has one or more blank spaces at the end, the value for wordCount will be 1 more than the actual number of words in the sentence. Correct this bug in two ways: one with the trim method of the String class and another without using this method. Seefiles CoutWordsA.java and CountWordsB.java 16. The Ch9ExtractWords program for extracting words in a given sentence includes the test if (beginIdx != endIdx) …

Describe the type of input sentences that will result in the variables beginIdx and endIdx becoming equal. When an input string has trailing spaces the beginIdx and endIdx will be the same. 17. Write an application that reads in a sentence and displays the count of individual vowels in the sentence. Use any output routine of your choice to display the results in this format. Count only the lowercase vowels. Vowel counts for the sentence Mary had a little lamb.


# of ‘a’ : 4 # of ‘e’ : 1 # of ‘i’ : 1 # of ‘o’ : 0 # of ‘u’ : 0

See file NumVowels.java 18. Write an application that determines if an input word is a palindrome. A palindrome is a string that reads the same forward and backward. For example, noon and madam. Ignore the case of the letter. So, for example, maDaM, MadAm, and mAdaM are all palindromes. See file PalindromeWord.java 19. Write an application that determines if an input sentence is a palindrome. For example, A man, a plan, a canal, Panama! You ignore the punctuation marks, blanks and the case of the letters. See file PalindromeSentence.java 20. Write an Eggy-Peggy program. Given a string, convert it to a new string by placing egg in front of every vowel. For example, the string I love Java

becomes eggI Leggovegge Jeggavegga

The solution presented is comprised of only one class, with one main method. The reasoning behind the simplistic design is the problem itself is very simple. The work to be done for the application does not really warrant an entire class. Seefile EggyPeggy.java 21. Write a variation of the Eggy-Peggy program. Implement the following four variations:   

Sha

Ava

Na Sha Na Na

Add sha to the beginning of every word Add na to the end of every word. Add sha to the beginning and na na to the end of every word Move the first letter to the end of the word and add ava to it

Allow the user to select one of four possible variations. Use JOptionPane for input.


This problem is slightly more complex than the previous one, so a class devoted entirely to generating the eggy-peggy string was created. The SuperEggyPeggy class takes a string and the desired egg to use and generates the new string based on that information. Each egg has its own method to generate the string, because each of them is different and goes in a different location in the string. The second class is simply the main method, which contains the user interface. See files SupperEggyPeggy.java and PlaySupperEggyPeggy.java 22. Write a word guessing game. The game is played by two players, each taking a turn in guessing the secret word entered by the other player. Ask the first player to enter a secret word. After a secret word is entered, display a hint that consists of a row of dashes, one for each letter in the secret word. Then ask the second player to guess a letter in the secret word. If the letter is in the secret word, replace the dashes in the hint with the letter at all positions where this letter occurs in the word. If the letter does not appear in the word, the number of incorrect guesses is incremented by 1. The second player keeps guessing letters until either  The player guesses all the letters in the word. or  The player makes 10 incorrect guesses. Here’s a sample interaction with blue indicating the letter entered by the player: - - - S - - - A - A - A V - A V A D - A V A J J A V A Bingo! You won.

Support the following features:  Accept an input in either lowercase or uppercase.  If the player enters something other than a single letter (a digit, special character, multiple letters, etc.), display an error message. The number of incorrect guesses is not incremented.  If the player enters the same correct letter more than once, reply with the previous hint.  Entering an incorrect letter the second time is counted as another wrong guess. For example, suppose the letter W is not in the secret word. Every time the player enters W as a guess, the number of incorrect guesses is incremented by 1. After a game is over, switch the role of players and continue with another game. When it is the first player’s turn to enter a secret word, give an option to the players to stop playing. Keep the tally and announce the winner at the end of the program. The tally will include for each player the number of wins and the total number of incorrect guesses


made for all games. The player with more wins is the winner. In the case where both players have the same number of wins, the one with the lower number of total incorrect guesses is the winner. If the total numbers of incorrect guesses for both players are the same also, then it is a draw. The tasks in this problem can be separated into two: playing a single game, and playing a tournament (several games and keeping track of the number of wins, etc.). Thus, we created two separate classes. See files WordGuessGame.java and WordGuessTournament.java

23. Write another word guessing game similar to the one described in Exercise 22. For this word game, instead of using a row of dashes for a secret word, a hint is provided by displaying the letters in the secret word in random order. For example, if the secret word is COMPUTER, then a possible hint is MPTUREOC. The player has only one chance to enter a guess. The player wins if he guessed the word correctly. Time how long the player took to guess the secret word. After a guess is entered, display whether the guess is correct or not. If correct, display the amount of time in minutes and seconds used by the player. The tally will include for each player the number of wins and the total amount of time taken for guessing the secret words correctly (amount of time used for incorrect guesses is not tallied). The player with more wins is the winner. In the case where both players have the same number of wins, the one who used the lesser amount of time for correct guesses is the winner. If the total time used by both players is the same also, then it is a draw.

As with the previous exercise, the tasks in this problem can be separated into two: playing a single game, and playing a tournament (several games and keeping track of the number of wins, etc.). Thus, we created two separate classes. See files WordGuessGame2.java and WordGuessTournament2.java

24. The word game Eggy-Peggy is an example of encryption. Encryption has been used since the ancient times to communicate messages secretly. One of the many techniques used for encryption is called a Caesar cipher. With this technique, each character in the original message is shifted N positions. For example, if N = 1, then the message I drink only decaf Becomes J!esjol!pomz!efdbg The encrypted message is decrypted to the original message by shifting back every character N positions. Shifting N positions forward and backward is achieved by converting the character to ASCII code and adding or subtracting N. Write an application that reads in the original text and the value for N and displays the encrypted text. Make sure the ASCII value resulting from encryption falls between 32 and 126.


For example, if you add 8 (value of N) to 122 (ASCII code for ‘z’), you should “wrap around” and get 35. Write an application that reads the encrypted text and the value for N and displays the original text by using the Caesar cipher technique. Design a suitable user interface. The solution presented is comprised of three classes. One class is the CaesarCipher object, which holds the number of characters to shift by. The CaesarCipher can encrypt and decrypt strings based on the cipher value. There is also a class for the GUI and a class for the main method. The GUI contains a CaesarCipher object, which does all the work. See files CeasarCipher.java, CipherApp.java and EncryptDecrypt.java

25. Another encryption technique is called a Vignere cipher. This technique is similar to a Caesar cipher in that a key is applied cyclically to the original message. For this exercise a key is composed of uppercase letters only. Encryption is done by adding the code values of the key’s characters to the code values of the characters in the original message. Code values for the key characters are assigned as follows: 0 for A, 1 for B, 2 for C,…, and 25 for Z. Write an application that reads in a text and displays the encrypted text. Make sure the ASCII value resulting from encryption of decryption falls between 32 and 126. You can get the code for key characters by (int)keyChar – 65. Write an application that reads in the encrypted text and displays the original text, using the Vignere cipher technique. Analysis is same as above. See files VignereCipher.java, CipherApp.java and EncryptDecrypt.java

26. A public-key cryptography allows anyone to encode messages while only people with a secret key can decipher them. Write a program that encodes and decodes messages using RSA encryption. For this solution the encryption and decryption activities were split into two classes. The reason is they should be two totally separate actions. The encryptor has no need to know anything about decryption and the private key, while the decryptor needs only the public key and nothing else related to encryption. RSAEncryptor contains the two prime numbers and the exponent to encode the characters. RSADecryptor contains the private key needed to decode the numbers. It uses the private key with the public key, which it gets from the RSAEncryptor. The GUI is a separate class, which manages the encryptor and decryptor objects, and the main method is a separate class. We used the BigInteger class (java.math.BigInteger) instead of int or long, because due to the exponentiation operations, overflow occurred and the results were not as expected.


Get complete Order files download link below https://www.mediafire.com/file/hiv6tkbgaqyvy3v/SM+ A+Comprehensive+Introduction+to+ObjectOriented+Programming+with+Java,+1e+C.+Thomas+W u.zip/file

If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.


See files RSAEncryptor.java, RSADecryptor.java, CipherApp.java and EncryptDecrypt.java


Solutions to Chapter 10 1. Identify problems with this code: public int searchAccount( int[25] number ) {  1 number = new int[15]; for (int i = 0; i < number.length; i++ )  2 number[i] = number[i-1] + number[i+1]; return number;  3 }

1. Parameter declaration cannot include size (25) information. 2. The for loop will cause an ArrayIndexOutOfBounds exception when i = 0 because it will access number[i – 1] which will be number[-1] and is out of bounds because you can’t have a negative array index. 3. The return value number is not of type int it is int[]. 2. Declare an array of double of size 365 to store daily temperatures for one year. Using this data structure, write the code to find  The hottest and coldest days of the year.  The average temperature of each month  The difference between the hottest and coldest days of every month.  The temperature of any given day. The day is specified by two input values: month (1,…,12) and day (1,…,31). Reject invalid input values (e.g., 13 for month and 32 for day). private double[] myArray = new double[365]; public double getHottest(double[] dayArray) { double max = dayArray[0]; for (int index = 1; index < dayArray.length; index++) { if (max < dayArray[index]) { max = dayArray[index]; } } return max; } public double getColdest(double[] dayArray) { double min = dayArray[0]; for (int index = 1; index < dayArray.length; index++) { if (min > dayArray[index]) { min = dayArray[index]; } } return min; } public double getMonthAvg(double dayArray[], int month) {


double sum = 0; int dayCount = 0; int start = 0; if (month == 1) { dayCount = 31; start = 0; } else if (month == 2) { dayCount = 28; start = 31; } else if (month == 3) { dayCount = 31; start = 59; } else if (month == 4) { dayCount = 30; start = 90; } else if (month == 5) { dayCount = 31; start = 120; } else if (month == 6) { dayCount = 30; start = 151; } else if (month == 7) { dayCount = 31; start = 181; } else if (month == 8) { dayCount = 31; start = 212; } else if (month == 9) { dayCount = 30; start = 243; } else if (month == 10) { dayCount = 31; start = 273; } else if (month == 11) { dayCount = 30; start = 304; } else if (month == 12) { dayCount = 31; start = 334; } else { System.out.println( “Invalid month: “ + month ); return -1; } for (int i = start; i < start + dayCount; i++) { sum += dayArray[i]; } return sum / dayCount; } public double getMonthRange(double[] dayArray, int month) { double high = 0; double low = 0; int dayCount = 0;


int start = 0; if (month == 1) { dayCount = 31; start = 0; } else if (month == 2) { dayCount = 28; start = 31; } else if (month == 3) { dayCount = 31; start = 59; } else if (month == 4) { dayCount = 30; start = 90; } else if (month == 5) { dayCount = 31; start = 120; } else if (month == 6) { dayCount = 30; start = 151; } else if (month == 7) { dayCount = 31; start = 181; } else if (month == 8) { dayCount = 31; start = 212; } else if (month == 9) { dayCount = 30; start = 243; } else if (month == 10) { dayCount = 31; start = 273; } else if (month == 11) { dayCount = 30; start = 304; } else if (month == 12) { dayCount = 31; start = 334; } else { System.out.println( “Invalid month: “ + month ); return -1; } max = min = dayArray[start]; for (int i = start + 1; i < start + dayCount; i++) { if ( dayArray[i] > max ) { max = dayArray[i]; } else if ( dayArray[i] < min ) { min = dayArray[i]; } } return max – min; } public double getDailyTemp(double[] dayArray, int month, int day) {


int dayCount = 0; int start = 0; if (month == 1) { dayCount = 31; start = 0; } else if (month == 2) { dayCount = 28; start = 31; } else if (month == 3) { dayCount = 31; start = 59; } else if (month == 4) { dayCount = 30; start = 90; } else if (month == 5) { dayCount = 31; start = 120; } else if (month == 6) { dayCount = 30; start = 151; } else if (month == 7) { dayCount = 31; start = 181; } else if (month == 8) { dayCount = 31; start = 212; } else if (month == 9) { dayCount = 30; start = 243; } else if (month == 10) { dayCount = 31; start = 273; } else if (month == 11) { dayCount = 30; start = 304; } else if (month == 12) { dayCount = 31; start = 334; } if (month > 12 || month < 1 || day < 1 || day > dayCount) { System.out.println( “Invalid month: “ + month + “ day: “ + day + “ combination”); return -1; } day--; return dayArray[start + day]; }

3. Repeat Exercise 2, using a two-dimensional array of double with 12 rows and each row having 28, 30, or 31 columns. double[][] myArray = new double[12][];


for(int i = 0; i < myArray.length; i++) { if (i == 0 || i == 2 || i == 4 || i == 6 || i == 7 || i == 9 || i == 11) { myArray[i] = new double[31]; } else if (i == 3 || i ==5 || i == 8 || i == 10) { myArray[i] = new double[30]; } else { myArray[i] == new double[28]; } } public double getHottest(double[] dayArray) { double max = dayArray[0][0]; for (int month = 0; month < 12; month++) { for (int day = 0; day < dayArray[month].length; day++) { if (max < dayArray[month][day]) { max = dayArray[month[day]; } } } return max; } public double getColdest(double[] dayArray) { double min = dayArray[0][0]; for (int month = 0; month < 12; month++) { for (int day = 0; day < dayArray[month].length; day++) { if (min > dayArray[month][day]) { min = dayArray[month[day]; } } } return min; } public double getMonthAvg( double[] dayArray, int month) { double sum = 0; if( month < 1 || month > 12) { System.out.println( “Invalid month: “ + month ); return -1; } month--; for (int i = 0; i < dayArray[month].length; i++ ) { sum +=dayArray[month][i]; } return sum / dayArray[month].length; }


public double getMonthRange(double[] dayArray, int month) { double max = 0; double min = 0; if (month < 1 || month > 12) { System.out.println( “Invalid month: “ + month ); return -1; } month--; max = dayArray[month][0]; min = dayArray[month][0]; for (int i = 1; i < dayArray[month].length; i++) { if ( dayArray[i] > max) { max = dayArray[i]; } else if ( dayArray[i] < min) { min = dayArray[i]; } } return max – min; } public double getDailyTemp(double[] dayArray, int month, int day) { if (month > 12 || month < 1 || day < 1 || day > dayArray[month – 1].length) { System.out.println( “Invalid month: “ + month + “ day: “ + day + “ combination”); return -1; } day--; month--; return dayArray[month][day]; }

4. Repeat Exercise 2, using an array of Month objects with each Month object having an array of double of size 28, 30, or 31. class Month { private double[] days; public Month(int numDays) { days = new double[numDays]; } public double getHottest() { double max = days[0]; for (int i = 1; i < days.length; i++) { if (days[i] > max) { max = days[i];


} } return max; } public double getColdest() { double min = days[0]; for (int i = 1; i < days.length; i++) { if (days[i] < min) { min = days[i]; } } return min; } public double getAverage() { double sum = 0; for (int i = 0; i < days.length; i++) { sum += days[i]; } return sum / days.length; } public double getRange() { double min = day[0]; double max = day[0]; for (int i = 1; i < days.length; i++) { if ( days[i] > max) { max = days[i]; } else if ( days[i] < min) { min = days[i]; } } return max – min; } public double getDayTemp(int theDay) { return days[theDay]; } public int getDaysInMonth() { return days.length; } } // Month Month[] myArray = new Month[12]; for (int i = 0; i < myArray.length; i++) { if (i == 0 || i == 2 || i == 4 || i == 6 || i == 7 || i == 9 || i == 11) { myArray[i] = new Month(31); } else if (i == 3 || i ==5 || i == 8 || i == 10) { myArray[i] = new Month(30);


} else { myArray[i] == new Month(28); } } public double getHottest(Month[] monthArray) { double max = monthArray[0].getHottest(); for(int i = 1; i < monthArray.length; i++) { if (monthArray[i].getHottest() > max) { max = monthArray[i].getHottest(); } } return max; } public double getColdest(Month[] monthArray) { double min = monthArray[0].getColdest(); for (int i = 1; i < monthArray.length; i++) { if (monthArray[i].getColdest() < min) { min = monthArray[i].getColdest(); } } return min; } public double getMonthAvg(Month[] monthArray, int month) { if (month < 1 || month > 12) { System.out.println(“Invalid month: “ + month); return -1; } else { return monthArray[month - 1].getAverage(); } } public double getMonthRange(Month[] monthArray, int month) { if (month < 1 || month > 12) { System.out.println(“Invalid month: “ + month); return -1; } else { return monthArray[month – 1].getRange(); } } public double getDailyTemp(Month[] monthArray, int month, int day) { if (month < 1 || month > 12) { System.out.println(“Invalid month: “ + month); return -1; } else if (monthArray[month – 1].getDaysInMonth < day || day < 1) { System.out.println(“Invalid month: “ + month + “day: “ + day + “ combination”); return -1; } else { return monthArray[month – 1].getDayTemp(day – 1);


} }

5. For Exercises 2 to 5, the following three data structures are used:  One-dimensional array of double of size 365.  Two dimensional array of double with 12 rows. Each row has 28, 30, or 31 columns.  An array of Month objects with each Month object having an array of double of size 28, 30, or 31. Discuss the pros and cons of each approach. With the one-dimensional array we can use simple indexing to find facts about the entire year such as the highest temperature of the year. With the one-dimensional array, however, it is difficult to divide the array into individual months. A twodimensional array with different length rows makes it easy to break the data into months, but a little more difficult to compute statistics about the entire year. An array of Month objects gives us the best of both worlds. We can use simple indexing to scan through each month and ask each Month to compute its own statistics. 6. Suppose you want to maintain the highest and lowest temperatures for every day of the year. What kind of data structure would you use? Describe the alternatives and list their pros and cons. Creating a Day object and Month object would be a good solution. The Day object would hold the high and low temperature. The Month object would hold an array of Day objects of size 31, 30, or 28. The main program would have an array of Month objects of size 12. This solution makes it very easy to find statistics because each Month and Day can generate their own statistics. One alternative is to have two one-dimensional arrays of double of size 365. One array would store the high and the other would store the low. This would make it quite simple to find statistics about the year, but it would be difficult to find statistics about a month. 7. If a car dealer’s service department wants a program to keep track of customer appointments, which data structure would you choose, an array or a list? If the number of appointments the service department accepts is fixed on any given day, which data structure is appropriate? What are the criteria you use to decide which data structure to use? Explain. I would use a list. It provides the most flexibility in regards to size. The size is not fixed so the dealership could make as many appointments as they like. If the number of appointments is fixed, I would use an array. This would illustrate that there are a fixed number of slots available each day. The criteria I used to decide were based in the number of appointments. If I don’t know the maximum number of appointments, a list makes sense because you can add as many appointments as


you want. If there is a specified maximum, an array makes sense because you can’t have any more appointments then there are slots to schedule them in. 8. In Figure 10.8, the last statement person[last] = null;

is significant. Show the state-of-memory diagram when the last statement is not executed.

9. Write an application that computes the standard deviation of N real numbers. The standard deviation s is computed according to

The program first prompts the user for N and then declares an array of size N. See Exercise10_9.java 10. Using the payScaleTable two-dimensional array from section 10.4, write the code to find  The average pay for every grade level  The average pay for every step (i.e., average of every column). // The average for every grade level


for (int i = 0; i < 4; i++) { double sum = 0.0; for (int j = 0; j < 5; j++) { sum += payScaleTable[i][j]; } System.out.println( “The average for grade “ + i + “ is “ + sum / 5.0 ); } // The average for every step for (int i = 0; i < 5; i++) { double sum = 0.0; for (int j = 0; j < 4; j++) { sum += payScaleTable[j][i]; } System.out.println( “The average of step “ + i + sum / 4.0 );

+ “ is “

}

11. Declare a two-dimensional array for the tuition table show in Figure 10.13. double[][] tuitionTable = { { 6000.00, 18000.00}, { 9000.00, 21000.00}, {12500.00, 24500.00} };

12. Suppose you want to maintain information on the location where a product is stored in a warehouse. Would you use a three-dimensional array such as location[i][j][k], where i is the warehouse number, j is the aisle number, and k is the bin number? Or would you define three classes Warehouse, Aisle, and Bin? Describe the alternatives and list their pros and cons. A good way to do this is to declare the three classes, Warehouse, Aisle, and Bin. In an object-oriented language it makes more sense to hold data in a onedimensional array of objects with each object containing an array or some other data structure instead of using a three-dimensional array. This approach would make it easy to modify the data, i.e., we get a new warehouse, put more aisles in a warehouse, or store two items in a bin. The three-dimensional array approach requires more complex code to search and modify the data. 13. The search method of the AddressBook class returns only one Person object. Modify the method so that it will return all the Person objects that match the search criteria. You can use an array to return multiple Person objects. public Person[] search( String searchName ) { Person[] foundPerson; int loc = 0;


assert count >= 0 && count <= entry.length; foundPerson = new Person[ entry.length ]; for ( int i = 0; i < count; i++ ) { if ( searchName.equals( entry[ i ].getName() ) ) { foundPerson[loc] = entry[ i ]; loc++; } } return foundPerson; }

14. Write new search routines for the AddressBook class. The search method given in the chapter finds a person with a given name. Add second and third search methods that find all persons, given an age and a gender, respectively. public Person[] search( int searchAge ) { Person[] foundPerson; int loc = 0; assert count >= 0 && count <= entry.length; foundPerson = new Person[ entry.length ]; for ( int i = 0; i < count; i++ ) { if ( searchAge == entry[ i ].getAge() ) { foundPerson[loc] = entry[ i ]; loc++; } } return foundPerson; } public Person[] search( char searchGender ) { Person[] foundPerson; int loc = 0; assert count >= 0 && count <= entry.length; foundPerson = new Person[ entry.length ]; for ( int i = 0; i < count; i++ ) { if ( searchGender == entry[ i ].getGender() ) { foundPerson[loc] = entry[ i ]; loc++; } } return foundPerson; }

15. Modify the add method of the AddressBook class. The method given in the chapter does not check for any duplicate names. Modify the method so that no Person object with a duplicate name is added to the address book.


public void add( Person newPerson ) { assert count >= 0 && count <= entry.length; int loc = 0; boolean found = false; // See if this person exits in the address book while (loc < count && !found) { if ( newPerson.getName().equals(entry[loc].getName()) ) { found = true; } loc++; } if (!found) { // A person with the same name does not exist so we can // add this one if (count == entry.length) { // no more space left, enlarge(); // create a new larger array } entry[count] = newPerson; count++; } }

16. Modify the AddressBook class to allow the programmer to access all Person objects in the address book. Make this modification by adding two methods: getFirstPerson and getNextPerson. The getFirstPerson method returns the first Person object in the book. The getNextPerson method returns the next Person object if there is one. If there is no next person in the book, getNextPerson returns null. The getFirstPerson method must be called before calling the getNextPerson method. // Add a private data member to the AddressBook class private int nextPerson; public Person getFirstPerson() { nextPerson = 0; Person retVal = entry[nextPerson]; nextPerson++; return retVal; } public Person getNextPerson() { Person retVal; // Make sure getFirstPerson was called first


assert nextPerson != 0; if (nextPerson == count) { // There are no more people in the book retVal = null; } else { retVal = entry[nextPerson]; nextPerson++; } return retVal; }

17. In addition to the List and Map interface, the third interface in the Java Collection Framework is Set. A Set is an unordered collection of objects with no duplicates. This interface models, as expected, the mathematical set. Two classes that implement the Set interface in the JCF are TreeSet and HashSet. Here’s a simple example of using Set: Set set = new HashSet(); set.add(“ape”); set.add(“bee”); set.add(“ape”); // duplicate, so it won’t be added set.add(“cat”); set.remove(“bee”); set.remove(“dog”); // not in the set, nothing happens System.out.println(“Set = “ + set);

The output from the code will be Set = [ape, cat]

To access individual elements of a set, call the iterator method in the manner identical to the one we used for the List interface. Modify the Kennel class from Chapter 4, so a Kennel object is capable of tracking a set of Pet objects. The board method of the modified Kennel class adds a new Pet to the set. Include new methods called workoutTime and chowTime. These two methods will iterate through the set and make the pets go through the exercise and feeding routines. Determine your own rule for the exercising and feeding. Please consult the Java API documentation for details on the Set interface. See Kennel.java 18. Consider the following Thesaurus class: class Thesaurus { // Returns all synonyms of the word as a Set // returns null if there no such word public java.util.Set get (String word){…} // Returns all key words in this thesaurus as a Set


// returns an empty set if there are no keys (if you // don’t do anything, default behavior of the // underlying JCF class will handle it) public java.util.Set keys( ){…} // Adds ‘synonym’ to the synonym set of ‘word’ // Pay close attention to this method. public void put (String word, String synonym){…} }

The get method returns a set all synonyms of a given word. The keys method returns all key words in the thesaurus. The put method adds a new synonym to the given word. Make sure to handle the cases when the word already has a synonym list and when the word is added for the first time. Using this Thesaurus class, we can write, for example, this program: class SampleMain { public static void main(String[] args) { Thesaurus t = new Thesaurus(); t.put(“fast”, “speedy”); t.put(“fast”, “swift”); t.put(“slow”, “sluggish”); Set synonyms = t.get(“fast”); System.out.println(synonyms); System.out.println(t.keys()); } }

When the sample program is executed, the output will be

Implement the Thesaurus class, using one of the Map classes. The key is the word, and the value is the set of synonyms of this word. See file Thesaurus.java 19. Write a complete address book maintenance application. The user of the program has four options: add a new person, delete a person, modify the data of a person, and search for a person by giving the name. Use the AddressBook class, either the original one from the chapter or the modified one from the previous exercises. You have to decide how to allow users enter the values for a new person, display person information, and so forth. See Exercise10_19.java, AddressBook.java, and Person.java Design Document: Address Book Program


Class Exercise10_19 AddressBook Person String

Integer

JOptionPane

Purpose The main class of the program. Used to keep track of the Person objects. Used to hold information about a Person. Used to hold input from the user. The charAt is used to get the character for the gender of the person. The parseInt method is used to transform the user input of the age from a String to an int. The showInputDialog method is used to get information from the user such as the person’s name, age, gender, etc. The showMessageDialog is used to show information to the user. This information includes error message and information about a person.

Development Step 1: Design the main GUI. Development Step 2: Add the ability to add a person to the address book. Development Step 3: Add the ability to search for and display information about a person. Development Step 4: Add the ability to delete a person from the address book. Development Step 5: Add the ability to modify a person in the address book.

20. Design a currency converter class whose instance will handle conversion of all currencies. In Chapter 4 we designed a currency converter class where we created one instance for each currency. A single instance of the new currency converter class you design here will handle all currencies. Instead of having specific


conversion methods such as toDollar, toYen, and so forth, the new currency converter class supports one generic conversion method called exchange. The method has three arguments: fromCurency, toCurrency, and amount. The first two arguments are String and give the names of the currencies. The third argument is float. To convert $250 to yen, we write yen = converter.exchange( “dollar”, “yen”, 250.00 );

To set the exchange rate for a currency, we use the setRate method. This method takes two arguments: The first argument is the currency name, and the second argument is the rate. For example, if the exchange rate for yen is 140 yen to $1, then we write converter.setRate(“yen”, 140.0);

Use an array to keep track of exchange rates. See CurrencyConverter.java Design Document: Currency Conversions Program Class Purpose CurrencyConverter This is the main class. It holds all the logic to convert from one currency to another String Used to store currency names. The equals method is used to compare currency names. Assumptions: The program assumes that if the user wants to convert to or from dollars, they will use the string dollar as one of the parameters to exchange. Development Step 1: Write a function to enlarge the array when it gets full. Development Step 2: Implement the setRate function. Development Step 3: Write the code to convert from dollars to another currency. Development Step 4: Write the code to convert from another currency to dollars. Development Step 5: Write the code to convert from one currency to another where the currencies are not dollars Development Step 6: Write the code to convert from one currency to the same currency. Development Step 7: Add code to check for invalid currencies.


21. Extend the MyJava Lo-Fat Burgers drive-through ordering system of Exercise 23 on page 295 so the program can output sales figures. For each item on the menu, the program keeps track of the sales. At closing time, the program will output the sales figure in a format similar to the following: Item Tofu Burger Cajun Chicken . . . Today’s Total Sales:

Sales Count 25 30 $

$ $

Total 87.25 137.70

2761.20

See Exercise10_21.java, MenuItem.java, MenuCategory.java, and DriveThruControl.java Design Document: Drive Thru Ordering System Class Purpose Exercise10_21 The class that contains the main method of the program. DriveThruControl This class handles the ordering logic. MenuCategory This class is used to represent the three categories of items the user can purchase. MenuItem This class represents an item on the menu. HashMap This class is used to map an item to the number that have been ordered. Development Step 1: Add code to put an item name and amount into a HashMap. Development Step 2: Add code to print all the items ordered. Development Step 3: Add code to print out the total sales for the day.


22. Redo the watermelon projectile computing program of Exercise 31 on page 365 to output the average distance covered between each time interval. Use the expression

to compute the distance between two coordinate points(x1, y1) and (x2, y2). See WatermelonCannon.java and Exercise10_22.java Design Document: Watermelon Cannon Program Class Purpose Exercise10_22 The class that contains the main method of the program. WatermelonCannon This class does all the computations and regulates program flow. Development Step 1: Modify the program to store the X and Y coordinates at each time interval in arrays. Development Step 2: Add code to calculate the average distance covered during


a time interval. Development Step 3: Add code to display the average distance covered during a time interval to the user.

23. Redo the social club program of Exercise 8 of Chapter 8. In the original program, we limit the number of clubs to 5. Remove this restriction by using an array. See ClubKeeper23.java,ClubApp.java, Dorm.java, DormAdmin.java, and Resident.java Design Document: Club Keeper Program Class Purpose ClubKeeper23 The main class of the program. ClubApp Used to display information about a club. DormAdmin Used to manage a club. Dorm Used to represent a club. Resident Used to represent a member of the club. JOptionPane The showInputDialog method is used to ask the user for the new club’s name. The showMessageDialog method is used to tell the user that they did not enter a club name. Assumptions: There will never be two clubs with the same name. Development Step 1: Change the program to hold the current clubs in an array. Development Step 2: Modify the GUI to give the user a way to add a club. Development Step 3: Write the code to allow a user to add a club.


24. Redo Exercise 23, but this time use one of the Java Collection Framework classes. See ClubKeeper24.java,ClubApp.java, Dorm.java, DormAdmin.java, and Resident.java

Design Document: Club Keeper Program Class Purpose ClubKeeper24 The main class of the program. ClubApp Used to display information about a club. DormAdmin Used to manage a club. Dorm Used to represent a club. Resident Used to represent a member of the club. JOptionPane

LinkedList

The showInputDialog method is used to ask the user for the new club’s name. The showMessageDialog method is used to tell the user that they did not enter a club name. Used to hold the clubs.

Assumptions: There will never be two clubs with the same name. Development Step 1: Change the program to hold the current clubs in a list. Development Step 2: Modify the GUI to give the user a way to add a club.


Development Step 3: Write the code to allow a user to add a club.


Solutions to Chapter 11 1.

Consider the following array of sorted integers:

Using the binary search algorithm, search for 23. Show the sequence of array elements that are compared, and for each comparison, indicate the values for low and high. low

high

mid

compare

0 0 0 1 2

11 4 1 1 1

5 2 0 1

23 < num[5] 23 < num[2] 23 < num[0] 23 < num[1] low < high, so stop. Not Found.

2. We assumed all elements in an array are distinct; that is, there are no duplicate values in the array. What will be an effect on the linear search algorithm if an array contains duplicate values? If the array contains duplicate values, then the linear search will return the value that is stored in the first position, i.e., the smallest index. A new search routine must be written to return the positions for all duplicate values. 3. Will the sorting algorithms presented in this chapter work if the unsorted array contains any duplicate values? Yes, duplicate values will not cause any problems. 4. In this chapter we analyzed sorting algorithms by counting the number of comparisons. Another possible method for analyzing the algorithms is to count the number of data exchanges. How many data exchanges do the selection and bubble sort make in the worst case? Regardless of the original list, the selection sort will make the same number of data exchanges. However, the number of data exchanges the bubble sort makes depends on the arrangement of elements in the original list. In the case of selection sort, the total number of data exchanges is N-1, the same number as the number of passes that selection sort performs one data exchange after every pass. In the case of Bubble sort, the total number of data exchanges is equal to the total number of comparisons. In other words in the worst case, every comparison will result in a data exchange. This situation happens with the original array is the reverse order (i.e., sorted in descending order). We already know the total number of comparisons (== the total number of


data exchanges) in the worst case is: (N - 2) + (N - 1) + ... + 1 = (N - 2)(N - 1) / 2 = N2 5. Another simple sorting algorithm is called an insertion sort. Suppose we have a sorted list of N elements and we need to insert a new element X into this list to create a sorted list of N+1 elements. We can insert X at the correct position in the list by comparing it with elements list[N+1], list[N+2], list[N+3], and so forth. Every time we compare X and list[i], we shift list[i] one position to list[i+1] if X is smaller than list[i]. When we find list[i] that is smaller than X, we put X at position i+1 and stop. We can apply this logic to sort an unordered list of N elements. We start with a sorted list of one element and insert the second element to create a sorted list of two elements. Then we add the third element to create a sorted list of three elements. Figure 11.18 illustrates the steps in the insertion sort. Write a method that implements the insertion sort algorithm. You may simplify the method by sorting only integers.


public void insertionSort(int[] number) { // one execution of the outer loop is one pass for (int endIndex = 1; endIndex < number.length; endIndex++) {\ int value = number[index]; int index = endEndex - 1; // if the current element at index is larger // than value, then shift down the element while (index >=0 && number[index] > value) { number[index + 1] = number[index]; index--; } // move the value to the correct position number[index + 1] = value; } }

6. Analyze the insertion sort algorithm of Exercise 5 by counting the number of comparisons and data exchanges. Provide the analysis for the worst case. The worst case occurs, as was the case with bubble sort, when the original list is in reverse order (i.e., descending order). In this case, each comparison will result in one data movement. We also have one final data movement to move the current value into the correct position. The total number of comparisons in the worst case is: (N - 1) + (N - 2) + ... + 1 = (N - 1)N / 2 = N2 The number of data movements for each pass is one more than the number of comparisons for the pass, so the total number of data movements in the worst case is: (N) + (N - 1) + ... + 2 = N(N + 1) / 2 - 1 = N2 7. Write a test program to compare the performances of selection sort, bubble sort, and heapsort algorithms experimentally. Use the random method from the Math class to generate 5000 integers, and sort the generated integers by using the three sorting algorithms. For each execution, record the time it took to sort the numbers. You can use the java.util.Date class to record the execution time in milliseconds, for example, Date startTime, endTime; startTime = new Date(); //sort the integers endTime = new Date(); //record the elapsed time double elapsedTime = endTime.getTime() - startTime.getTime();

See file Exercise11_7.java 8.

Consider the following property about the bubble sort:


If the last exchange made in some pass occurs at the Jth and (J + 1)st positions, then all elements from the (J + 1)st to the Nth positions are in their correct location. Rewrite the bubble sort algorithm, using this property. See file Exercise11_8.java 9. The Heap class given in Section 11.3 sorts only the integers. Improve the class by making it possible to sort any objects that recognize the compareTo method, which is described in Section 11.4, so the new Heap class will be able to sort Person, Integer, Double, and String objects among others. Since the elements in the internal array can be any object, declare an array of Object objects. All Java classes are automatically a subclass of Object, unless they are declared explicitly as a subclass of another class. The declaration of heap will be like this private Object[ ] heap; and the setData method will be like this: public void setData( Object[ ] data ) { heap = new Object[ data.length ]; sortedList = new Object[ data.length ]; for (int i = 0; i < data.length; i++ ) { heap[i] = data[i]; } }

See file Exercise11_9.java 10. In the Heap class, we used two separate arrays: one for the heap and another for the sorted list. It turns out we can do everything with just one array. Notice that the heap will decrease in size by one element after every rebuild step. The unused space at the end of the heap array can be used to store the sorted list. Modify the Heap class so it will use only one array. See file Exercise11_10.java 11. Modify the Heap class by defining a separate method called rebuild, which will be used by both the construct and extract methods. See file Exercise11_11/Heap.java 12. In Section 11.4, we implemented the sorting routine for the AddressBook class with the bubble sort algorithm. Modify the sorting routine by using the Heap class of Exercise 9. See file Exercise11_12/AddressBook.java 13. Instead of maintaining an unsorted list and returning the sorted list when the sort method is called, modify the AddressBook class so that it maintains the sorted list of Person in alphabetical order. Modify the search routine by using the binary search algorithm. See file Exercise11_13/AddressBook.java


Solutions to Chapter 12 1.

What will happen if you forget to close a file? Any data that is still in the data cache will be lost.

2.

What is the difference between binary files and text files? Data inside the textfiles are saved in the ASCII (or Unicode) format. Textfiles can be opened, viewed, and edited with any text editor. Data inside the binary files are saved in a machine-readable format only. As the contents are not in ASCII, binary files cannot be viewed by a text editor.

3.

Using the try-catch block, write code that opens a file default.dat when an attempt to open a user-designated file raises an exception. Answer: FileInputStream inFileStream; Scanner scanner; scanner = new Scanner( System.in ); Systemm.out.print(“Enter filename to open:”); String filename = scanner.next(); try { InFileStream = new FileInputStream( filename ); } catch (Exception e) { inFileStream = new FileInputStream(“default.dat”); }

4.

Using a File object, write code to display files in a user-specified directory. public void directoryList(String dirName) { File dir = new File(dirName); if(f.isDirectory()) { String[] fileNames = dir.list(); for(int i = 0;i < fileNames.length; i++) { String filename = dirName + File.separator + FileNames[i]; System.out.println( fileName ); directoryList(fileName); } }


5.

Write code to store and read the contents of the payScaleTable two dimensional array from Section 10.4 in the following two file formats:  A file of double values  A file of two-dimensional array See file Exercise12_5.java

6.

Write an application that reads a text file and converts its content to an EggyPeggy text. Save the converted text to another text file. Use JfileChooser to let the user specify the input and output files. Create the input file by using a text editor. See file Exercise12_6.java.

7.

Write an application that randomly generates N integers and stores them in a binary file integers.dat. The value for N is input by the user. Open the file with a text editor and see what the contents of a binary file look like. See file Exercise12_7.java.

8.

Write an application that reads the data from the file integers.dat generated in Exercise 7. After the data are read, display the smallest, the largest, and the average. See file Exercise12_8.java.

9.

Repeat Exercise 7, but this time, store the numbers in a text file integers.txt. Open this file with a text editor and verify that you can read the contents. See file Exercise12_9.java.

10.

Repeat Exercise 8 with the text file integers.txt generated in Exercise 9. See file Exercise12_10.java

11.

Extend the AddressBookStorage class by adding import and exportFile capabilities. Add a method export that stores the contents of AddressBook to a text file. Add a second method importFile that reads the text file back and constructs an AddressBook. This type of import/export feature is a convenient means to move data from one application to another. See file AddressBookStorage.java.

12.

Extend the encryption application of Exercise 25 of Chapter 10 so that the original text is read from a user-specified text file and the encrypted text is stored to another user-specified text file.


See file CipherApp.java 13.

Extend the watermelon projectile computation program of Exercise 31 on page 365 so the output is saved to a file. Which file format would you use for the program, a binary file or a text file? Or would you consider using an array to keep the (x,y) coordinates and save this array by using an object I/O? For this exercise, a text file is better, because it allows the user to open it with any text editor and see the results. A binary file, in particular a file with the whole array written to it, is a better approach if the file is going to be used as input for another program, as it makes reading and writing faster. See file WatermelonCannon.java

14.

Write a program that inputs a document from a text file and saves the modified version to another text file. Modify the original document by replacing all occurrences of the word designated by the user with the text <BLACKED OUT>. Use JFileChooser to select the input and output text file and JOptionPane to input the word to replace from the user. For the text replacement operation, consider using the pattern matching techniques discussed in Chapter 9. See file Exercise12_14.java

15.

Write a currency converter application. Allow the user to specify the from and to currencies and the amount to exchange. Use the interface of your choice to input these three values. When the application starts, read the exchange rates from a text file rate.txt. Use a text editor to create this text file. By using a text file, you can easily update the exchange rates. The format for the text file is <name of currency> <units per dollar>

For example, the following shows how much $1 is worth in five foreign currencies: French franc Indonesian rupiah Japanese yen Mexican peso Papua New Guinea kina

5.95 12900.0 123.91 9.18 2.381

You can get the exchange rates from various websites, one of which is http://www.oanda.com. See file CurrencyExchange.java.


16.

Extend any application you have written before by adding a quote-of-the-day dialog. When the user starts the application, a quote of the day is displayed (use JOptionPane). Save the quotes in a text file. Use a random number generator to select the quote to display. Notice the quotes can be about any information (many commercial applications start with a dialog that shows tips on using the software). See file QuoteOfTheDay.java.

17.

. In Exercise 5.23 you wrote a drive-through ordering system for MyJava Lo-Carb Gourmet Sandwich (the company has since changed its name to reflect the current trend in the food industry). You are hired again as a freelance computer consultant to make extensions to the program. Instead of having a fixed number of menu categories and a fixed number of menu items per category, you will input this information from a text file. The data in the input file have the following format: #menu category menu item $price menu item $price ... #menu category menu item $price Each menu category is preceded by the pound symbol (#). A list of menu items that belong to this menu category follows it. Each menu item includes its name and price. The price is preceded by the dollar sign. Here’s a sample input file: #Entree Tofu Burger $3.99 Chili Burger $2.99 Chef Salad $6.99 #Drink Oolong Tea $0.79 Latte $3.29 House Wine $4.99 Chai Latte $2.50 #Side Freedom Fries $0.99 #Appetizer Onion Bloom $4.05 Calamari $3.50 You may assume that that input file contains at least one menu category and each menu category has at least one menu item. Also, you may assume that all input lines conform to the given format; that is, there will be no invalid input lines. Finally, there will be at most 20 menu categories and 25 menu items per menu category. After the input file data are read into a program, the operation mode begins, where you continually process the customer orders. For each item on the menu, keep track of the sales. At the closing time, the store manager keys in a special code to shut down the program. Before stopping the program, output the sales figure in a format similar to the following:


Place enough space between columns so the output is easy to read. You are not required to align the decimal points of the dollar figures. Output the sales figure to the standard output. Save the sales figure to a text file. See files MenuCategory.java and DriveThruControl.java 18.

Write an application that removes extra spaces from a text file. In the days of the typewriter, it was common practice to leave two spaces after periods. We shouldn’t be doing that anymore with the computer, but many people still do. Read an original text file and output an edited version to another text file. The edited version should replace two or more consecutive spaces with one space. See file SpaceErasor.java.

19.

Write a mail merge application. You use two files for this program. The first is a text file that contains a template letter in the following style:

The tags <<N>>, <<A>>, and <<G>> are placeholders for the person’s name, age, and gender. The second file contains the name, age, and gender information of people to whom you want to send a letter. Use whatever format you wish for the second file. Read two files and print out the letter with the placeholders replaced by the actual values from the second file. For this program, output the personalized letter to System.out. Allow the user to save the personalized letters to files (one personalized letter to a file). See file EmailMerge.java.


Solutions to Chapter 13 1.

Consider the following class definitions. Identify invalid statements. class Car { public protected private

String int String

make; weight; color;

… } class ElectricCar extends Car { private int rechargeHour; public ElectricCar() { … } // Copy Constructor public ElectricCar( ElectricCar car ) { this.make = car.make; this.weight = car.weight; this.color = new String( car.color ); // This statement is not valid since color is a // private member of Car. this.rechargeHour = car.rechargeHour; } … } class TestMain { public static void main( String[] args ) { Car myCar; ElectricCar myElecCar; myCar = new Car(); myCar.make = “Chevy”; myCar.weight = 1000; // Illegal if Car and TestMain are in different // packages myCar.color = “Red”; // This statement is not valid because color is // private. myElecCar = new Car(); myCar.make = “Chevy”; myCar.weight = 500; // Illegal if Car and TestMain are in different // packages myCar.color = “Silver”; // This statement is not valid because color is // private and so no } }


2.

Consider the following class definitions. Identify which calls to the constructor are invalid. class Car { public protected private

String int String

make; weight; color;

private Car( String make, int weight, String color ) { this.make = make; this.weight = weight; this.color = color; } public Car() { this( “unknown”, -1, “white” ); } } class ElectricCar extends Car { private int rechargeHour; public ElectricCar() { this( 10 ); } private ElectricCar( int charge ) { super(); rechargeHour = charge; } } class TestMain { public static void main( String[] args ) { Car myCar1, myCar2; ElectricCar myElec1, myElec2; myCar1 = new Car(); // Legal since Car() is public. myCar2 = new Car( “Ford”, 1200, “Green” ); // Illegal since Car( String, int, String ) is // private and we are not // calling it from the Car class. myElec1 = new ElectricCar(); // Legal since ElectricCar is public. myElec2 = new ElectricCar( 15 ); // Illegal since ElectricCar( int ) is private and // we are not calling it from the ElectricCar class. } }

3.

In the ComputeGrades sample program, we set the default size of the roster array to 25. Modify the program so the size of the array will be increased if the input


file contains more than 25 students. You need to add a method that expands the array, say, by 50 percent. In buildRoster( String ) from Step 4, replace if ( student != null ) { roster[ studentCount ] = student; studentCount++; }

with if ( student != null ) { if ( studentCount == roster.length ) { // Increase roster capacity Student[] temp = new Student[ (int)(roster.length * 1.5) ]; /* Copy roster.length elements starting at element 0 from roster * to temp, starting at location 0. */ System.arraycopy( roster, 0, temp, 0, roster.length); roster = temp; } roster[ studentCount ] = student; studentCount++; }

4.

Extend the ComputeGrades sample program by storing the roster array using ObjectOutputStream. To allow the user to create and read the data using any text editor, add the menu choices Import and Export, which will read in a text file (this is how the original ComputerGrades works) and write out data in ASCII format to a text file. See Ex13_4 directory for CalculateGrades.java and Student.java

5.

Extend the ComputeGrades sample program to include menu choices Save, Open, and Quit. With the current program, you can open one file for each execution of the program. Extend the program so the user can open more than one file by selecting the menu choice Open repeatedly. Selecting menu choice Save will allow the user to save the computed results to a file she or he specifies. See Ch13_Ex5 directory for CalculateGrades.java and Student.java

6.

How would you modify the ComputeGrades sample program if the formula for computing the course grade is different for freshman, sophomore, junior, and senior undergraduate students? Would you design four subclasses of UndergraduateStudent? Discuss the pros and cons of each approach.


We should not create four new subclasses of UndergraduateStudent. We can be reasonably sure that no new type of undergraduate will come into existence, so it is unlikely that this method will need to change in the future. If we choose instead to create four new subclasses, we have a new set of problems. First, we need to differentiate among the four classes when a new student enrolls so that we create an appropriate instance. Second and more important, we have a natural progression each year as freshmen become sophomores, sophomores become juniors, and juniors become seniors. If we create subclasses, then at the end of each school year, we need to convert all the freshman objects to sophomore objects and so on. This is a large amount of overhead with no significant gain to offset it. With the single subclass UndergraduateStudent, we use an instance variable to indicate the class to which a student belongs (possibly ints 1 - 4 for freshman - senior year). At the end of each academic year, we simply increment this variable for those students who are advancing to the next year. 7.

In the Chapter 5 sample development, we defined the DrawableShape class that includes a method to draw on of the three possible shapes–rectangle, rounded rectangle, and ellipse. Modify the DrawableShape class as a superclass of the three subclasses Rectangle, RoundedRectangle, and Ellipse. The actual drawing of a shape is done by the drawShape method defined in each of the three subclasses. Using the DrawingBoard helper class from Chapter 5 and the four classes defined in this exercise, write a screensaver program that draws 10 rectangles, 15 rounded rectangles, and 20 ellipses of various sizes. All shapes will move smoothly across the screen. See Ch13_Ex7 directory for Ch13DrawShape.java, DrawableShape.java, DrawableRectangle.java, DrawableRoundedRectangle.java, and DrawableEllipse.java.

Development Exercises 8.

Write a personal finance manager program that maintains information on your bank accounts. Incorporate these rules: • For savings accounts, you can make a maximum of three withdrawals in a month without incurring a fee. The bank charges $1.00 for every withdrawal after the third. • For the checking accounts, the bank charges $0.50 for every check you write for the first twenty checks (i.e., withdrawals) in a month. After that, there will be no charge. You should be able to open and save account information to a file. You should be able to list all transactions of a given account or of all accounts. Include the appropriate menus to select the options supported by the program. Consider using the Date class to record the date of transactions. The Date class is from the java.util package. Please refer to a java.util reference for information on this class.


Tasks: •Maintain information (including transactions) about bank accounts •Create accounts •Withdraw from accounts •Deposit into accounts •Read and write account information from and to file •View transactions for an account •View transactions for all accounts Class Descriptions: Account – maintains information about an account, including owner, account number, current balance, and a list of all past transactions. SavingsAccount – a version of Account with the appropriate withdrawal rules. CheckingAccount – a version of Account with the appropriate withdrawal rules. Bank – responsible for maintaining a collection of accounts, indexed by account number as well as by owner’s name. Transaction – regroups information about a transaction including date, time, and amount. See java files in Ch13_Ex8

9.

Extend the address book sample program from Chapter 10. Instead of managing a single type of Person, incorporate additional types of persons such as PersonalFriend and BusinessAssociate. Define theses classes as a subclass of Person. Design carefully to decide whether the Person class will be an abstract class. Tasks: • Maintain a list of common interests for PersonalFriends. • Maintain the titles of BusinessAssociates and the name of the company for which they work. Classes: PersonalFriend - A Person with a list of common interests. BusinessAssociate - A Person with a title and an employer. Notes: In this exercise, the use of our address book is a open-ended. We can not assume that all Persons are either PersonalFriends or BusinessAssociates. Therefore, we keep Person as a concrete class and then create two more classes that store extra information specific to their types. See java files in Ch13_Ex9

10.

Consider an asset-tracking program that will track four types of assets: electronic appliances, automobiles, furniture, and compact disks. What classes would you design for the program? Would you define four unrelated classes or one


superclass and four subclasses? If you define a superclass, will it be an abstract superclass? Tasks: • Add asset • View owner's assets • View asset by tracking ID • View all assets, sorted by tracking ID • View assets by type • Delete asset Class Descriptions: Asset - abstract superclass for all assets AssetTracker - database for looking up assets, both by tracking ID and owner AssetTrackerUI - an interface between the system and the user Automobile - class to maintain information specific to an automobile CompactDisk - class to maintain information specific to a CD ElectronicApplianc - class to maintain information specific to an electronic appliance FurniturePiece - class to maintain information specific to piece of furniture Notes: A superclass for all assets it the most appropriate. In many contexts, we don’t care what sort of asset the asset is, just that it is an asset and therefore has certain properties (data members) knows how to do certain things (in our abstract, summarizing itself to a String, for example). The Asset superclass also should be abstract since there will be no assets in the system that are not one of its subtypes (in our system, not in the real world). One way of specifying this nature is to make the superclass abstract. Another reason for choosing abstract over concrete is that all assets may know how to do something but each may do it differently. If we were to write a concrete class (that is, one not declared abstract), we would have to choose one implementation of this behavior over another. In the case of equals for example, how do we test to see if two Assets are equal while knowing nothing about their subclass parts? Furthermore, we want to force the implementer of the subclasses to actually write a specific version of equals for every class since we will be relying on equals to be correct when we write the database.

11.

Implement the asset-tracking program of Exercise 10. Allow the user to add, modify, and delete electronic appliances, automobiles, furniture, and compact disks. Allow the user to list the assets by category and search for an asset by its serial number. See the Ch13_Ex11 directory.


12.

Extend the asset-tracking program of Exercise 11 by added an object I/O capability. See the Ch13_Ex12 directory.

13.

Write an application that reads daily temperatures for 12 months and allows the user to get statistics. Support at least three operations: monthly average of a given month, yearly average, and lowest and highest temperatures of a give month. Use a text file to store the temperatures. The first line in the text file contains temperatures for January; the second line, those for February; and so forth. Use StringTokenizer to parse a line into temperatures of type float. For a data structure, consider using either an array of Month or a two dimensional array of float. Month is a class you define yourself. A Month class is the easier way to go since it can both store the daily temperatures (the number of which varies from month to month and a class would be a good place to store this information) and compute the monthly statistics. While we could do this all with arrays and a single class contain a main method and all our other methods, this is not as organizationally sound and it fails to adhere to the object oriented paradigm. See the Ch13_Ex13 directory.


Solutions to Chapter 14 1. Define a subclass of JFrame and name it Ch14Q1Frame. Set the subclass so its instances will be 400 pixels wide and 450 pixels high and will have a blue background. The program terminates when the Close box is clicked. // Ch14Q1Frame.java import javax.swing.*; import java.awt.*; public class Ch14Q1Frame extends JFrame { private static final int FRAME_WIDTH = 400; private static final int FRAME_HEIGHT = 450; public Ch14Q1Frame() { setSize(FRAME_WIDTH, FRAME_HEIGHT); getContentPane().setBackground(Color.blue); setDefaultCloseOperation(EXIT_ON_CLOSE); } }

2. Define a JFrame subclass that has four vertically aligned buttons. The labels for the four buttons are Senior, Junior, Sophomore, and Freshman. This is one possible layout:

When a button is clicked, display a message that identifies which button is clicked, using JOptionPane.


// Ch14Q2Frame.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Ch14Q2Frame extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 350; private static final int FRAME_HEIGHT = 450; private static final int BUTTON_WIDTH = 150; private static final int BUTTON_HEIGHT = 30; private JButton senior; private JButton junior; private JButton sophomore; private JButton freshman; public Ch14Q2Frame() { setSize(FRAME_WIDTH, FRAME_HEIGHT); /* Do not use a LayoutManager seeing as they are not discussed until Chapter 14 */ getContentPane().setLayout(null); senior = new JButton("Senior"); senior.setBounds(100, 50, BUTTON_WIDTH, BUTTON_HEIGHT); senior.addActionListener(this); getContentPane().add(senior); junior = new JButton("Junior"); junior.setBounds(100, 150, BUTTON_WIDTH, BUTTON_HEIGHT); junior.addActionListener(this); getContentPane().add(junior); sophomore = new JButton("Sophomore"); sophomore.setBounds(100, 250, BUTTON_WIDTH, BUTTON_HEIGHT); sophomore.addActionListener(this); getContentPane().add(sophomore); freshman = new JButton("Freshman"); freshman.setBounds(100, 350, BUTTON_WIDTH, BUTTON_HEIGHT); freshman.addActionListener(this); getContentPane().add(freshman); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton)event.getSource(); String buttonText = clickedButton.getText();


JOptionPane.showMessageDialog(this, buttonText); } }

3. In the Ch14TextFrame1 class, event handling was done with this class. Modify the class so the button events are handled by a ButtonHandler and the text events are handled by a TextHandler. You can use the ButtonHandler class defined in the chapter, but you need to define your own TextHandler class. // Ch14TextFrame1.java import javax.swing.*; import java.awt.*; import java.awt.event.*; class Ch14TextFrame1 extends JFrame { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 200; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; private static final int BUTTON_WIDTH = 80; private static final int BUTTON_HEIGHT = 30; private JButton cancelButton; private JButton okButton; private JTextField inputLine; private ButtonHandler buttonListen; private TextHandler textListen; public static void main(String[] args) { Ch14TextFrame1 frame = new Ch14TextFrame1(); frame.setVisible(true); } public Ch14TextFrame1() { Container contentPane; // Create the event handlers buttonListen = new ButtonHandler(); textListen = new TextHandler(); // set the frame properties setSize(FRAME_WIDTH, FRAME_HEIGHT);


setResizable(false); setTitle("Program Ch14SecondJFrame"); setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN); contentPane = getContentPane(); contentPane.setLayout(null); contentPane.setBackground(Color.white); // create and place two buttons on the frame okButton = new JButton("OK"); okButton.setBounds(70, 125, BUTTON_WIDTH, BUTTON_HEIGHT); contentPane.add(okButton); cancelButton = new JButton("CANCEL"); cancelButton.setBounds(160, 125, BUTTON_WIDTH, BUTTON_HEIGHT); contentPane.add(cancelButton); cancelButton.addActionListener(buttonListen); okButton.addActionListener(buttonListen); inputLine = new JTextField(); inputLine.setBounds(90, 50, 130, 25); contentPane.add(inputLine); inputLine.addActionListener(textListen); // register 'Exit upon closing' as a default close operation setDefaultCloseOperation(EXIT_ON_CLOSE); } } // ButtonHandler.java import javax.swing.*; import java.awt.*; import java.awt.event.*; class ButtonHandler implements ActionListener { public ButtonHandler() { } public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton)event.getSource(); JRootPane rootPane = clickedButton.getRootPane(); Frame frame = (JFrame)rootPane.getParent(); String buttonText = clickedButton.getText();


frame.setTitle("You clicked " + buttonText); } } // TextHandler.java import javax.swing.*; import java.awt.*; import java.awt.event.*; class TextHandler implements ActionListener { public TextHandler() { } public void actionPerformed(ActionEvent event) { JTextField enteredText = (JTextField)event.getSource(); JRootPane rootPane = enteredText.getRootPane(); Frame frame = (JFrame)rootPane.getParent(); String fieldText = enteredText.getText(); frame.setTitle("You entered '" + fieldText + "'"); } }

4. Using the same frame layout shown, write a program that displays N prime numbers, where N is a value entered in the text field. A prime number is an integer greater than 1 and divisible only by itself and 1.

// Primes.java import javax.swing.*;


Get complete Order files download link below https://www.mediafire.com/file/hiv6tkbgaqyvy3v/SM+ A+Comprehensive+Introduction+to+ObjectOriented+Programming+with+Java,+1e+C.+Thomas+W u.zip/file

If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.


import java.awt.*; import java.awt.event.*; class Primes extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 250; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; private static final int BUTTON_WIDTH = 90; private static final int BUTTON_HEIGHT = 30; private static final String GENERATE = "Generate"; private static final String BLANK = ""; private JTextField guessEntry; private JTextArea response; private JButton guessButton; // Main method public static void main(String[] args) { Primes frame = new Primes(); frame.setVisible(true); } public Primes() { Container contentPane; // set the frame properties setSize(FRAME_WIDTH, FRAME_HEIGHT); setResizable(false); setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN); contentPane = getContentPane(); contentPane.setBackground(Color.white); addComponents(contentPane); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if(event.getSource() instanceof JTextField) { processEnterAction(command); } else { // event source is a button processButtonAction(command);


} } private void addComponents(Container contentPane) { contentPane.setLayout(null); // create and place two buttons on the frame guessButton = new JButton(GENERATE); guessButton.setBounds(80 + BUTTON_WIDTH, 10, BUTTON_WIDTH, BUTTON_HEIGHT); contentPane.add(guessButton); guessEntry = new JTextField(); guessEntry.setBounds(30, 10, BUTTON_WIDTH + 20, BUTTON_HEIGHT); contentPane.add(guessEntry); response = new JTextArea(); response.setBounds(40, 20 + BUTTON_HEIGHT, 40 + BUTTON_WIDTH, 150); response.setEditable(false); contentPane.add(response); // register this frame as an action listener of the event // sources guessButton.addActionListener(this); guessEntry.addActionListener(this); } private void processButtonAction(String buttonText) { if(buttonText.equals(GENERATE)) { processEnterAction(guessEntry.getText()); } } private void processEnterAction(String entry) { if(entry.equals(BLANK)) { JOptionPane.showMessageDialog(this, "Error: No number was entered"); } else { int input = Integer.parseInt(entry); guessEntry.setText(BLANK);


processNextGuess(input); } } private void processNextGuess(int guess) { boolean isPrime = true; int counter = 0; // Generate the sequence of primes response.setText(""); for(int i = 2; counter < guess; i++) { for(int j = 2; j <= Math.sqrt(i); j++) { if(i % j == 0) { isPrime = false; break; } } if(isPrime) { response.append(i + "\n"); counter++; } isPrime = true; } } }

5. Define an OutputBox class as a subclass of JFrame. The OutputBox class provides the functionality of System.out (PrintStream) by supporting these methods: public void println(String line) public void print(String text) The OutputBox class contains one JTextArea object. Do not use absolute positioning. Use the default layout and add a JScrollPane that wraps the JTextArea to the content pane.


// OutputBox.java import javax.swing.*; import java.awt.*; public class OutputBox extends JFrame { private static final int FRAME_WIDTH = 400; private static final int FRAME_HEIGHT = 450; JTextArea display; public OutputBox() { setSize(FRAME_WIDTH, FRAME_HEIGHT); display = new JTextArea(); display.setEditable(false); JScrollPane scrollText = new JScrollPane(display); getContentPane().add(scrollText); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void print(String text) { display.append(text); } public void println(String line) { print(line + "\n"); } }

6. Redo Exercise 19 on page 360 but this time use the OutputBox class created in Exercise 8 for output. // Exercise14_6.java public class Exercise14_6 { public static void main( String[] args ) { OutputBox cout = new OutputBox(); cout.setVisible(true); int COST_PER_SQ_FT = 19; int price;


cout.println( " cout.println( "

5

Length" ); 10

15

20

25"

); for (int width = 11; width <= 20; width++ ) { if ( width == 15 ) { cout.print( "Width }else { cout.print( "

" + width); " + width );

} for (int length = 5; length <= 25; length += 5 ) { price = width * length * COST_PER_SQ_FT; cout.print(" " + price); } cout.println(""); } } }

7. A slugging percentage of a baseball player is computed by dividing the total bases of all hits by the total times at bat (single = 1 base, double = 2 bases, triple = 3 bases, and home run = 4 bases). Write an application that computes the slugging percentage. Create a customized frame and use JTextField objects to accept five input values: number of singles, number of doubles, number of triples, number of home runs, and number of times at bat. When the user clicks the Compute button, display the slugging percentage, using JLabel. // Ch14Q7Frame.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Ch14Q7Frame extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 570; private static final int FRAME_HEIGHT = 160; private static final int FIELD_WIDTH = 100; private static final int FIELD_HEIGHT = 30; private static final String SINGLES = "Singles"; private static final String DOUBLES = "Doubles"; private static final String TRIPLES = "Triples"; private static final String HOMERS = "Home Runs"; private static final String BATS = "Times at Bat"; private static final String COMPUTE = "Compute"; private static final String SLUG = "Slugging % : "; private JLabel singleLabel;


private JLabel doubleLabel; private JLabel tripleLabel; private JLabel homerLabel; private JLabel batLabel; private JTextField singleField; private JTextField doubleField; private JTextField tripleField; private JTextField homerField; private JTextField batField; private JButton compute; private JLabel slugging; private JLabel total; // Main method public static void main(String[] args) { Ch14Q7Frame frame = new Ch14Q7Frame(); frame.setVisible(true); } public Ch14Q7Frame() { setSize(FRAME_WIDTH, FRAME_HEIGHT); setResizable(false); addComponents(getContentPane()); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void addComponents(Container contentPane) { contentPane.setLayout(null); // Create and place the Labels and TextFields singleLabel = new JLabel(SINGLES); singleLabel.setBounds(10, 10, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(singleLabel); singleField = new JTextField(); singleField.setBounds(10, 20 + FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(singleField); doubleLabel = new JLabel(DOUBLES); doubleLabel.setBounds(20 + FIELD_WIDTH, 10, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(doubleLabel); doubleField = new JTextField(); doubleField.setBounds(20 + FIELD_WIDTH, 20 + FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(doubleField);


tripleLabel = new JLabel(TRIPLES); tripleLabel.setBounds(30 + 2 * FIELD_WIDTH, 10, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(tripleLabel); tripleField = new JTextField(); tripleField.setBounds(30 + 2 * FIELD_WIDTH, 20 + FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(tripleField); homerLabel = new JLabel(HOMERS); homerLabel.setBounds(40 + 3 * FIELD_WIDTH, 10, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(homerLabel); homerField = new JTextField(); homerField.setBounds(40 + 3 * FIELD_WIDTH, 20 + FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(homerField); batLabel = new JLabel(BATS); batLabel.setBounds(50 + 4 * FIELD_WIDTH, 10, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(batLabel); batField = new JTextField(); batField.setBounds(50 + 4 * FIELD_WIDTH, 20 + FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(batField); // Add the Compute button and label compute = new JButton(COMPUTE); compute.setBounds(20 + FIELD_WIDTH, 30 + 2 * FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); compute.addActionListener(this); contentPane.add(compute); slugging = new JLabel(SLUG, JLabel.RIGHT); slugging.setBounds(30 + 2 * FIELD_WIDTH, 30 + 2 * FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(slugging); total = new JLabel("", JLabel.RIGHT); total.setBounds(40 + 3 * FIELD_WIDTH, 30 + 2 * FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(total); } public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if(command.equals(COMPUTE)) { try { total.setText(computeSlug());


} catch(Exception e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } private String computeSlug() { double slug = 0; try { slug = (Double.parseDouble(singleField.getText()) + Double.parseDouble(doubleField.getText()) * 2 + Double.parseDouble(tripleField.getText()) * 3 + Double.parseDouble(homerField.getText()) * 4) / Double.parseDouble(batField.getText()); } catch(Exception e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } return (new Double(slug)).toString(); } }

8. Write a graphical user interface for the slot machine program in Exercise 31 on page 365. Use three JLabel objects for displaying bells, grapes, and cherries. Add a button that simulates the motion of pulling down the handle. // SlotInterface.java import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class SlotInterface extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 360;


private static final int FRAME_HEIGHT = 150; private static final int FIELD_WIDTH = 60; private static final int FIELD_HEIGHT = 30; private static final String BELL = "Bell"; private static final String GRAPE = "Grape"; private static final String CHERRY = "Cherry"; private static final String HANDLE = "Pull Handle"; private JLabel[] labels; private JButton handle; private Exercise6_31_SlotMachine slot; private Random rng; private int betNum; private static boolean hasPlayed; public SlotInterface(Exercise6_31_SlotMachine slot) { this.slot = slot; betNum = 0; rng = new Random(); setSize(FRAME_WIDTH, FRAME_HEIGHT); setResizable(false); addComponents(getContentPane()); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent event) { int numBells = 0; String display = slot.play(betNum); // Parse the String StringTokenizer st = new StringTokenizer(display); for(int i = 0; i < labels.length; i++) { String graphic = st.nextToken(); if(graphic.equals("BELL")) { labels[i].setText(BELL); } else if(graphic.equals("GRAPES")) { labels[i].setText(GRAPE); } else if(graphic.equals("CHERRY")) {


labels[i].setText(CHERRY); } else { int rand = rng.nextInt(2); if(rand > 0 && numBells < 2) { labels[i].setText(BELL); numBells++; } else if(numBells >= 2 || i < 2) { labels[i].setText(GRAPE); } else { labels[i].setText(BELL); } } } JOptionPane.showMessageDialog(null, "Coins Available: " + slot.getNumCoinsAvailable() ); hasPlayed = true; } public void setBetNum(int betNum) { this.betNum = betNum; } private void addComponents(Container contentPane) { contentPane.setLayout(null); // Create and place Labels labels = new JLabel[3]; labels[0] = new JLabel(CHERRY); labels[0].setBounds(10, FRAME_HEIGHT / 2 - FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(labels[0]); labels[1] = new JLabel(CHERRY); labels[1].setBounds(20 + FIELD_WIDTH, FRAME_HEIGHT / 2 - FIELD_HEIGHT,


FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(labels[1]); labels[2] = new JLabel(CHERRY); labels[2].setBounds(30 + 2 * FIELD_WIDTH, FRAME_HEIGHT / 2 - FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(labels[2]); // Add Handle button handle = new JButton(HANDLE); handle.setBounds(40 + 3 * FIELD_WIDTH, FRAME_HEIGHT / 2 - FIELD_HEIGHT * 2, 2 * FIELD_WIDTH, FIELD_HEIGHT * 3); handle.addActionListener(this); contentPane.add(handle); } public static void main( String[] args ) { int initNum = Integer.parseInt(JOptionPane.showInputDialog(null, "How many coins do you have?")); Exercise6_31_SlotMachine slot = new Exercise6_31_SlotMachine(.25,initNum); SlotInterface frame = new SlotInterface(slot); frame.setVisible(true); int betNum = 0; try { betNum = Integer.parseInt(JOptionPane.showInputDialog(null, "How many coins do you want to bet?")); }catch ( NumberFormatException e ) { betNum = 0; } while ( betNum > 0 && slot.getNumCoinsAvailable() > 0 ) { while ( betNum < Exercise6_31_SlotMachine.MIN_BET || betNum > Exercise6_31_SlotMachine.MAX_BET ) { betNum = Integer.parseInt(JOptionPane.showInputDialog(null, "Bet invalid. Enter between " + Exercise6_31_SlotMachine.MIN_BET + " and " + Exercise6_31_SlotMachine.MAX_BET)); } // Wait until the game is played frame.setBetNum(betNum); hasPlayed = false; while(!hasPlayed); if ( slot.getNumCoinsAvailable() > 0 ) { try { betNum = Integer.parseInt(JOptionPane.showInputDialog(null, "How many coins do you want to bet?"));


}catch(NumberFormatException e) { betNum = 0; } } } JOptionPane.showMessageDialog(null,"You earned: $" + slot.getEarnings() + " and have " + slot.getNumCoinsAvailable() + " coins left"); System.exit(0); } }

9. Add images to the Exercise 12 solution. Create three gif files, one each for the bell, grape, and cherry. Use JLabel objects with ImageIcon to display these images on the frame. // SlotInterface.java import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class SlotInterface extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 360; private static final int FRAME_HEIGHT = 150; private static final int FIELD_WIDTH = 60; private static final int FIELD_HEIGHT = 30; private static final ImageIcon BELL = new ImageIcon("bell.gif"); private static final ImageIcon GRAPE = new ImageIcon("grape.gif"); private static final ImageIcon CHERRY = new ImageIcon("cherry.gif"); private static final String HANDLE = "Pull Handle"; private JLabel[] labels; private JButton handle; private Exercise6_31_SlotMachine slot; private Random rng; private int betNum; private static boolean hasPlayed; public SlotInterface(Exercise6_31_SlotMachine slot) { this.slot = slot; betNum = 0; rng = new Random(); setSize(FRAME_WIDTH, FRAME_HEIGHT);


setResizable(false); addComponents(getContentPane()); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent event) { int numBells = 0; String display = slot.play(betNum); // Parse the String StringTokenizer st = new StringTokenizer(display); for(int i = 0; i < labels.length; i++) { String graphic = st.nextToken(); if(graphic.equals("BELL")) { labels[i].setIcon(BELL); } else if(graphic.equals("GRAPES")) { labels[i].setIcon(GRAPE); } else if(graphic.equals("CHERRY")) { labels[i].setIcon(CHERRY); } else { int rand = rng.nextInt(2); if(rand > 0 && numBells < 2) { labels[i].setIcon(BELL); numBells++; } else if(numBells >= 2 || i < 2) { labels[i].setIcon(GRAPE); } else { labels[i].setIcon(BELL); } }


} JOptionPane.showMessageDialog(null, "Coins Available: " + slot.getNumCoinsAvailable() ); hasPlayed = true; } public void setBetNum(int betNum) { this.betNum = betNum; } private void addComponents(Container contentPane) { contentPane.setLayout(null); // Create and place Labels labels = new JLabel[3]; labels[0] = new JLabel(CHERRY); labels[0].setBounds(10, FRAME_HEIGHT / 2 - FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(labels[0]); labels[1] = new JLabel(CHERRY); labels[1].setBounds(20 + FIELD_WIDTH, FRAME_HEIGHT / 2 - FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(labels[1]); labels[2] = new JLabel(CHERRY); labels[2].setBounds(30 + 2 * FIELD_WIDTH, FRAME_HEIGHT / 2 - FIELD_HEIGHT, FIELD_WIDTH, FIELD_HEIGHT); contentPane.add(labels[2]); // Add Handle button handle = new JButton(HANDLE); handle.setBounds(40 + 3 * FIELD_WIDTH, FRAME_HEIGHT / 2 - FIELD_HEIGHT * 2, 2 * FIELD_WIDTH, FIELD_HEIGHT * 3); handle.addActionListener(this); contentPane.add(handle); } public static void main( String[] args ) { int initNum = Integer.parseInt(JOptionPane.showInputDialog(null, "How many coins do you have?")); Exercise6_31_SlotMachine slot = new Exercise6_31_SlotMachine(.25,initNum);


SlotInterface frame = new SlotInterface(slot); frame.setVisible(true); int betNum = 0; try { betNum = Integer.parseInt(JOptionPane.showInputDialog(null, "How many coins do you want to bet?")); }catch ( NumberFormatException e ) { betNum = 0; } while ( betNum > 0 && slot.getNumCoinsAvailable() > 0 ) { while ( betNum < Exercise6_31_SlotMachine.MIN_BET || betNum > Exercise6_31_SlotMachine.MAX_BET ) { betNum = Integer.parseInt(JOptionPane.showInputDialog(null, "Bet invalid. Enter between " + Exercise6_31_SlotMachine.MIN_BET + " and " + Exercise6_31_SlotMachine.MAX_BET)); } // Wait until the game is played frame.setBetNum(betNum); hasPlayed = false; while(!hasPlayed); if ( slot.getNumCoinsAvailable() > 0 ) { try { betNum = Integer.parseInt(JOptionPane.showInputDialog(null, "How many coins do you want to bet?")); }catch(NumberFormatException e) { betNum = 0; } } } JOptionPane.showMessageDialog(null,"You earned: $" + slot.getEarnings() + " and have " + slot.getNumCoinsAvailable() + " coins left"); System.exit(0); } }

10. Write a MyMenuFrame class with these menu choices.


When the user selects Quit, stop the program. When the user selects one of the colors, change the background of the frame (i.e., change the background color of the frame’s content pane) to the selected color. When the user selects Erase, reset the background color to white. // MyMenuFrame.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyMenuFrame extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 400; private static final int FRAME_HEIGHT = 450; private JMenu fileMenu; private JMenu editMenu; private JMenu colorMenu; public MyMenuFrame() { setSize(FRAME_WIDTH, FRAME_HEIGHT); setResizable(false); getContentPane().setLayout(null); getContentPane().setBackground(Color.white); createFileMenu(); createEditMenu(); createColorMenu(); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(colorMenu); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent event) { String menuName; menuName = event.getActionCommand(); if(menuName.equals("Quit")) { System.exit(0); } else if(menuName.equals("Erase")) {


getContentPane().setBackground(Color.white); } else if(menuName.equals("Red")) { getContentPane().setBackground(Color.red); } else if(menuName.equals("Green")) { getContentPane().setBackground(Color.green); } else if(menuName.equals("Blue")) { getContentPane().setBackground(Color.blue); } else if(menuName.equals("Pink")) { getContentPane().setBackground(Color.pink); } else if(menuName.equals("Black")) { getContentPane().setBackground(Color.black); } } private void createFileMenu() { JMenuItem item; fileMenu = new JMenu("File"); item = new JMenuItem("Quit"); item.addActionListener(this); fileMenu.add(item); } private void createEditMenu() { JMenuItem item; editMenu = new JMenu("Edit"); item = new JMenuItem("Erase"); item.addActionListener(this); editMenu.add(item); } private void createColorMenu() {


JMenuItem item; colorMenu = new JMenu("Color"); item = new JMenuItem("Red"); item.addActionListener(this); colorMenu.add(item); item = new JMenuItem("Green"); item.addActionListener(this); colorMenu.add(item); item = new JMenuItem("Blue"); item.addActionListener(this); colorMenu.add(item); item = new JMenuItem("Pink"); item.addActionListener(this); colorMenu.add(item); item = new JMenuItem("Black"); item.addActionListener(this); colorMenu.add(item); } public static void main(String args[]) { MyMenuFrame frame = new MyMenuFrame(); frame.setVisible(true); } }

11. Write a program that draws a selected geometric shape in random color and at a random location. The menu choices for the program are:

// Ch14Q11Frame.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Ch14Q11Frame extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 400; private static final int FRAME_HEIGHT = 450;


private static final int CIRCLE_DIAMETER = 50; private static final int SQUARE_HEIGHT = 50; private static final int RECT_LENGTH = 100; private JMenu shapeMenu; private java.util.Random rng; public Ch14Q11Frame() { setSize(FRAME_WIDTH, FRAME_HEIGHT); setResizable(false); getContentPane().setLayout(null); getContentPane().setBackground(Color.white); createShapeMenu(); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); menuBar.add(shapeMenu); setDefaultCloseOperation(EXIT_ON_CLOSE); rng = new java.util.Random(); } public void actionPerformed(ActionEvent event) { String menuName; Graphics myGraphics; Color myColor; int x, y; menuName = event.getActionCommand(); myGraphics = getContentPane().getGraphics(); // Randomly generate position and color x = rng.nextInt(FRAME_WIDTH + 1); y = rng.nextInt(FRAME_HEIGHT + 1); myColor = new Color(rng.nextInt(255 + 1), rng.nextInt(255 + 1), rng.nextInt(255 + 1)); myGraphics.setColor(myColor); if(menuName.equals("Circle")) { myGraphics.fillOval(x, y, CIRCLE_DIAMETER, CIRCLE_DIAMETER); } else if(menuName.equals("Rectangle")) { myGraphics.fillRect(x, y, RECT_LENGTH, SQUARE_HEIGHT); }


else if(menuName.equals("Square")) { myGraphics.fillRect(x, y, SQUARE_HEIGHT, SQUARE_HEIGHT); } } private void createShapeMenu() { JMenuItem item; shapeMenu = new JMenu("Shape"); item = new JMenuItem("Circle"); item.addActionListener(this); shapeMenu.add(item); item = new JMenuItem("Rectangle"); item.addActionListener(this); shapeMenu.add(item); item = new JMenuItem("Square"); item.addActionListener(this); shapeMenu.add(item); } public static void main(String args[]) { Ch14Q11Frame frame = new Ch14Q11Frame(); frame.setVisible(true); } }

12. Write an application that draws a circle every time the mouse button is clicked. The position where the mouse is clicked will become the center of the circle. Set the radius of the circle to 100 pixels. // Ch14Q12Frame.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Ch14Q12Frame extends JFrame implements MouseListener { private static final int FRAME_WIDTH = 640; private static final int FRAME_HEIGHT = 480; private static final int CIRCLE_DIAMETER = 200;


public Ch14Q12Frame() { setSize(FRAME_WIDTH, FRAME_HEIGHT); getContentPane().setBackground(Color.white); getContentPane().addMouseListener(this); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void mouseClicked(MouseEvent event) { Graphics myGraphics; myGraphics = getContentPane().getGraphics(); myGraphics.fillOval(event.getX() - CIRCLE_DIAMETER / 2, event.getY() - CIRCLE_DIAMETER / 2, CIRCLE_DIAMETER, CIRCLE_DIAMETER); } public void mouseEntered(MouseEvent event) { }; public void mouseExited(MouseEvent event) { }; public void mousePressed(MouseEvent event) { }; public void mouseReleased(MouseEvent event) { }; public static void main(String args[]) { Ch14Q12Frame frame = new Ch14Q12Frame(); frame.setVisible(true); } }

13. Extend Exercise 12 by adding the following menu to let the user select the shape to draw every time the mouse button is clicked. The clicked point will be the center of the selected shape. Choose appropriate values for the dimensions of the three shapes.

// Ch14Q13Frame.java import javax.swing.*;


import java.awt.*; import java.awt.event.*; public class Ch14Q13Frame extends JFrame implements MouseListener, ActionListener { private static final int FRAME_WIDTH = 640; private static final int FRAME_HEIGHT = 480; private static final int CIRCLE_DIAMETER = 200; private static final int CIRCLE = 0; private static final int SQUARE = 1; private static final int RECT = 2; private JMenu shapeMenu; private int shape; public Ch14Q13Frame() { shape = CIRCLE; setSize(FRAME_WIDTH, FRAME_HEIGHT); getContentPane().setBackground(Color.white); createShapeMenu(); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); menuBar.add(shapeMenu); getContentPane().addMouseListener(this); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void mouseClicked(MouseEvent event) { Graphics myGraphics; myGraphics = getContentPane().getGraphics(); switch(shape) { case CIRCLE: myGraphics.fillOval(event.getX() CIRCLE_DIAMETER / 2, event.getY() - CIRCLE_DIAMETER / 2, CIRCLE_DIAMETER, CIRCLE_DIAMETER); break; case SQUARE: myGraphics.fillRect(event.getX() CIRCLE_DIAMETER / 2, event.getY() - CIRCLE_DIAMETER / 2, CIRCLE_DIAMETER, CIRCLE_DIAMETER); break;


case RECT: myGraphics.fillRect(event.getX() CIRCLE_DIAMETER, event.getY() - CIRCLE_DIAMETER / 2, CIRCLE_DIAMETER * 2, CIRCLE_DIAMETER); break; default: break; } } public void actionPerformed(ActionEvent event) { String menuName; menuName = event.getActionCommand(); if(menuName.equals("Circle")) { shape = CIRCLE; } else if(menuName.equals("Rectangle")) { shape = RECT; } else if(menuName.equals("Square")) { shape = SQUARE; } } private void createShapeMenu() { JMenuItem item; shapeMenu = new JMenu("Shape"); item = new JMenuItem("Circle"); item.addActionListener(this); shapeMenu.add(item); item = new JMenuItem("Rectangle"); item.addActionListener(this); shapeMenu.add(item); item = new JMenuItem("Square"); item.addActionListener(this); shapeMenu.add(item);


} public void mouseEntered(MouseEvent event) { }; public void mouseExited(MouseEvent event) { }; public void mousePressed(MouseEvent event) { }; public void mouseReleased(MouseEvent event) { }; public static void main(String args[]) { Ch14Q13Frame frame = new Ch14Q13Frame(); frame.setVisible(true); } }

14. Rewrite the Ch14TicTacToePanel class by using the approach illustrated in Figure 14.18. // Ch14TicTacToePanel.java import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Ch14TicTacToePanel extends JPanel implements MouseListener { private boolean circle; public Ch14TicTacToePanel() { this(3); } public Ch14TicTacToePanel(int size) { Ch14TicTacToeCell cell; setLayout(new GridLayout(size, size)); for(int row = 0; row < size; row++) { for(int col = 0; col < size; col++) { cell = new Ch14TicTacToeCell(); cell.addMouseListener(this); add(cell); } }


circle = true; } public void mouseClicked(MouseEvent event) { Ch14TicTacToeCell cell = (Ch14TicTacToeCell)event.getSource(); Rectangle bounds = cell.getBounds(); Graphics g = getGraphics(); if(circle) { g.drawOval((int)bounds.getX() + (int)bounds.getWidth() / 4, (int)bounds.getY() + (int)bounds.getHeight() / 4, (int)bounds.getWidth() / 2, (int)bounds.getHeight() / 2); } else { g.drawLine((int)bounds.getX() + (int)bounds.getWidth() / 4, (int)bounds.getY() + (int)bounds.getHeight() / 4, (int)bounds.getX() + (int)bounds.getWidth() (int)bounds.getWidth() / 4, (int)bounds.getY() + (int)bounds.getHeight() (int)bounds.getHeight() / 4); g.drawLine((int)bounds.getX() + (int)bounds.getWidth() (int)bounds.getWidth() / 4, (int)bounds.getY() + (int)bounds.getHeight() / 4, (int)bounds.getX() + (int)bounds.getWidth() / 4, (int)bounds.getY() + (int)bounds.getHeight() (int)bounds.getHeight() / 4); } circle = !circle; } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } }


Development Exercises 15. Write a TeachArithmeticFrame class that teaches children arithmetic. The frame uses a JLabel for a problem and a JTextField for the user answer. When the user presses the ENTER key (while the JTextField object is active) or clicks the OK button, display a message stating whether the user’s answer is correct. When the Next button is clicked, display a new problem. The numbers are limited to two digits.

Consider using a larger font for the JLabel and JTextField text. You can change the color of text by calling the setForeground method, for example, questionLb1.setForeground(Color.red); Define a helper class that generates problems. See files in Exercise14_15/

16. Extend the TeachArithmeticFrame class so that the numbers of correct and incorrect answers are kept. Display these two numbers somewhere on the frame. Add the third button labeled Reset. When this button is clicked, the counters for correct and incorrect answers are reset to zero. See files in Exercise14_16/

17. Modify the mortgage table program of Exercise 29 in Chapter 6. Add this menu


to the program. When the user selects the menu choice New Table, the program opens another frame in which the user can enter three input values. The input frame should look something like this:

If the user clicks on the Compute button and the three input values are valid, generate a mortgage table. Use the OutputBox class from Exercise 5 to display the mortgage table. If the input values are invalid, then print out an appropriate error message. Decide on the range of valid values for the loan amount, interest rate, and loan period. When the user selects the menu choice About…, describe the purpose of the program by using another frame. You should create only one input frame, but may decide to use more than one OutputBox frame so you can see multiple loan tables at once. See files in Exercise14_17/

18. Redo Exercise 17 with a new user interface. The left side of a frame is used to enter the loan amount, interest rate, and loan period. The right side of a frame displays the mortgage table for given input values. The following layout is merely a suggestion. Feel free to use other GUI components as you see fit. For example, consider using JComboBox for entering interest rates and loan periods.


See files in Exercise14_18/

19. (Challenge) Write a class that implements a calculator with the layout similar to this:

The user enters a number, using digit buttons only. Some of the issues you need to consider include:


   

How to determine whether the user is entering a left operand or a right operand. How to handle the entering of multiple decimal points. A typical calculator accepts the first decimal point and ignores the rest. For example, if you press 1. 4. 3., the number entered is 1.43. When the display is 0 and the user enters 0, the display will not change. However, if the display is nonzero and the user enters 0, the 0 is appended to the number currently displayed. How to handle the operator precedence. For example, what will be the result if the user enters 4 + 3 x 2? Will it be 14 or 10? It is easier to treat all operators as having equal precedence and process them from left to right.

Study a real four-function calculator and try to implement a software calculator that simulates the real calculator as faithfully as possible, but feel free to make any reasonable changes. See files in Exercise14_19/

20. Extend the calculator of Exercise 19 to allow the user to enter a number by using the keyboard. The class needs to implement the KeyListener interface and define the keyTyped method. You have to find information on KeyListener and KeyEvent from a Java API reference manual. See files in Exercise14_20/

21. Latte Gallery in Carmel, California, is a small gallery that specializes in selling contemporary fine art, especially lithographs and photographs. All items sold in the gallery are signed and numbered. Write an application that keeps track of 

Customers and their art purchases

Artists and their works that have appeared in the gallery

Current inventory.

Allow the user to add, delete, or modify the customer, artist, and artwork information. An inventory will include the purchase prices of the artwork and the selling price when sold. Give the user an option to list all customers or one customer. The user will specify the customer to display by entering the customer’s last name and phone number. Define at least four data members for each type of information. For customers, include the name, phone number, address, and artwork and artist preferences. For artists, include the name, specialty, whether alive or deceased,


and price ranges of artwork. For artwork, include the title, date purchased, date sold, and artist. Feel free to add more data members as you see fit. Design appropriate GUI for entering and editing customers, artists, and artwork. See files in Exercise14_21/

22. Improve the Latte Gallery Information Manager application by adding the following capabilities: 

List all customers who bought artwork by a given artist.

List all artists who are still alive (so you can buy their artwork while the price is still reasonable).

List all artwork in the inventory that did not sell for over 3 months. (This requires the use of the Date class from the java.util package.)

Adjust the GUI accordingly. See files in Exercise14_22/

23. Improve the Latte Gallery Information Manager application by adding a feature that allows the user to select a customer from the list of all customers by clicking on the customer that he or she wants to see. The listing of all customers will include their names. When the user clicks on a name, the full information of the selected customer will appear on the right side of the frame.


See files in Exercise14_23/

24. Write a program that plays the game of Fermi. The program generates three distinct random digits between 0 and 9. These digits are assigned to positions 1, 2, and 3. The goal of the game is for the player to guess the digits in three positions correctly in the least number of tries. For each guess, the player provides three digits for positions 1, 2, and 3. The program replies with a hint consisting of Fermi, Pio, or Nano. If the digit guessed for a given position is correct, then the reply is Fermi. If the digit guessed for a given position is in a different position, the reply is Pico. If the digit guessed for a given position does not match any of the three digits, then the reply is Nano. Here are sample replies for the three secret digits 6, 5, and 8 at positions 1, 2, and 3, respectively. Guess 125 853

Hint Nano Nano Pico Pico Fermi Nano

586

Pico Pico Pico

Explanation The value 5 matches but at the wrong position. The value 5 matches at the correct position. The value 8 matches but at the wrong position. All match at the wrong positions.

Notice that if the hints like the above are given, the player can tell which number did not match. For example, given the hint for the second guess, we can tell that 3 is not one of the secret numbers. To avoid this, provide hints in a random order or in alphabetical order (e.g., it will be Fermi Nano Pico instead of Pico Fermi Nano for the second reply). Implement the program with an attractive and elegant GUI. See files in Exercise14_24/

25. Extend the Fermi playing program by allowing the player to   

Select the number of secret digits. Select alphabets instead of digits. Include duplicate secret digits.

Adjust the GUI accordingly. See files in Exercise14_25/

26. Write a personal scheduler application. Each entry in the scheduler is an appointment, a to-do item, or a memo. Each entry has the date and the time it is entered. An entry can be locked, and if it is locked, the user cannot modify it. For an appointment entry, include the person and the place of meeting. For a


to-do entry, include a short description of a task and the due date. For a memo, include a text. Implement the program with an attractive and elegant GUI. See files in Exercise14_26/ 27. Write a rental point-tracking system for an up-and-coming Espresso’s Dynamo Mopeds in Monterey, California. To compete against Ms. Latte’s Mopeds R Us, Espresso’s Dynamo Mopeds decided to install an automated points-tracking system. When a customer first rents a moped, his or her information is entered into a database. For each rental, a customer receives points, and when the total points reach 100, the customer can rent a moped free for 3 h or redeem a free movie rental coupon from Espresso’s Majestic Movies. The points are earned in the following scheme: Renter College student Adult Senior

Type 50cc Moppi 150cc Magnum 50cc Moppi 150cc Magnum 50cc Moppi 150cc Magnum

Points 15 20 10 15 20 30

In addition to the basic operations of updating the point information for every rental, include an operation to list all customers who earned over 100 points. Also, support an operation to edit the customer information. Implement the program with an attractive and elegant GUI. See files in Exercise14_27/ 28. Update the rental point-tracking system to support a new rental system and point-awarding rules for Espresso’s Dynamo Mopeds. Now the customers can rent only on an hourly basis, and the points are awarded accordingly. Upon rental, the customer will state the number of hours he or she will rent in increments of 1 h with a maximum of 10 h. The rental fee is based on the following formula: Renter

Type

College student

50cc Moppi 150cc Magnum 50cc Moppi 150cc Magnum 50cc Magnum 150cc Magnum

Adult Senior See files in Exercise14_28/

Total Rental ( <= 5 h) $3.50 / hour $4.50 / hour $5.00 / hour $6.50 / hour $4.00 / hour $5.25 / hour

Total Rental ( > 5 h) $2.50 / hour $3.50 / hour $4.00 / hour $5.00 / hour $3.00 / hour $4.00 / hour


Solutions to Chapter 15 1. Write a recursive method to find the smallest element in an array. Note: This is strictly an exercise. You should not write the real method recursively. //minimum element in an array of integers //the first call to this method should use start = 0 int findMinimum(int[] intArray, int start) { //base case for last element of the array if (start == intArray.length – 1) { return intArray[start]; } else { //find minimum of remainder of array int min = findMinimum(intArray, start + 1); if (intArray[start] < min) { return intArray[start]; } else { return min; } } }

2. Write a recursive method to compute the average of the elements in an array. Note: This is strictly an exercise. You should not write the real method recursively. //average of elements in an array //the first call to this method should use start = 0, sum = 0 float findAverage(float[] floatArray, int start, float sum){ sum += floatArray[start]; //base case for last element of the array if (start == floatArray.length – 1) { return sum / start; } else { return findAverage(floatArray, start + 1, sum); } }

3. Write a recursive method to determine whether a given string is a palindrome or not. A string is a palindrome if it reads the same forward and backward. Ignore the case of the letters and punctuation marks. //determine if the given string is a palindrome //first call should have index = 0 boolean isPalindrome(String str, int index) { int endPos = str.length() – index – 1; if (index >= str.length() / 2) { return true; } else if (Character.toUpperCase(str.charAt(index)) == Character.toUpperCase(str.charAt(endPos))) { return isPalindrome(str, index + 1);


} else { return false; } }

4. Write a recursive binary search method. Should this method be written recursively or nonrecursively in practice? //recursive binary search //returns position of found object or –1 if not found //first call should have low = 0 and high = intArray.length int binarySearch(int[] intArray, int searchFor, int low, int high) { if (high < low) { return –1; } int mid = (high + low) / 2; if (searchFor == intArray[mid]) { return mid; } else if (searchFor < intArray[mid]) { return binarySearch(intArray, searchFor, low, mid – 1); } else { return binarySearch(intArray, searchFor, mid + 1, high); } }

In practice, this will usually be a nonrecursive method because the algorithm is straightforward. 5. Write a recursive method to reverse a given string. The method accepts a string as an argument and returns the reverse of the argument. For example, if the argument is Java, then the method returns avaJ. Should this method be written recursively or nonrecursively in practice? //reverse a given string String reverse(String str) { if (str.length() <= 1) return str; return reverse(str.substring(1)) + str.charAt(0); }

In practice, this will usually be a nonrecursive method because the algorithm is straightforward. 5. In Chapter 6, we gave the nonrecursive and recursive solutions for finding the greatest common divisor of given two integers. Which version is the one you should use in practice?


The recursive solutions seem more natural for the problem, but both are very similar. 7. The partition method of the quicksort selects the first element as its pivot. Improve the method by using the median of the values in the first, the middle, and the last element of an array. If an array number to partition has 8 elements indexed from 0 to 7, then the first element is number[0], the middle element is number[4], and the last element is umber[7]. If these elements are 55, 34, and 89, for example, then the median is 55. /** * Divides the portion of the number array into two halves. The * first half contains elements less than pivot, and * the second half contains elements greater than * pivot. * * @param start the low end of the array to partition * @param end the high end of the array to partition. * * @return the location of the position where the pivot rests */ private int partition( int[] number, int start, int end ) { //set the pivot int pivot, index; int p1, p2, p3; index = (end - start + 1) / 2; p1 = number[start]; p2 = number[index]; p3 = number[end]; if( p1 < p2 && p2 < p3 ) { pivot = p2; } else if (p2 < p3 && p3 < p1) { pivot = p3; } else { pivot = p1; } do { //look for a number smaller than pivot from the end while ( start < end && number[end] >= pivot) { end--; } if ( start < end ) { //found a smaller number number[start] = number[end]; //now find a number larger than pivot //from the start while ( start < end && number[start] <= pivot) { start++; } if (start < end) { //found a larger number number[end] = number[start]; } }


} while ( start < end ); //done, move the pivot back to the array number[start] = pivot; return start; }

8. What would happen if the anagram method is called initially by passing an empty string as the second parameter? anagram( "", "" );

Will the method work? Why or why not? If not, correct the problem. If yes, then would it be logical to leave it as is or should the method be corrected to make it more logical? The method will still work if the second parameter is empty. If the parameter suffix is empty, then the local variable numOfChars will be zero. So the else part will be executed. Because the for loop inside the else part is bounded by numOfChars with i beginning from 1, this for loop will not get executed. Thus, the correct result is produced. Although the method works, it is not logically clear. A more logical statement would be if (numOfChars == 0) { //End case: print out one anagram outputBox.printLine(prefix); } else { //recursion }

9. Another recursive sorting algorithm is called merge sort. The merge sort divides the array into two halves, sorts the two halves recursively using mergesort, and finally merges the two sorted halves into a sorted list. In diagram, the process of merge sort looks like this:


Write the mergesort method. public void mergesort( int low, int high ) { int mid; if ( low < high ) { mid = ( low + high ) / 2; mergesort( low, mid ); //sort the first half mergesort( mid+1, high ); //sort the other half merge( low, mid, high ); } } private void merge ( int low, int mid, int high ) { //Assumption: ‘list’ and ‘temp’ arrays //are data members of the class and accessible //from this method. int i = low; int j = mid+1; int k = low; while ( i <= mid && j <= high ) { if ( list[i] < list[j] ) { temp[k] = list[i]; i++; } else { temp[k] = list[j]; j++; } k++; } //the loop body of only one of the two while loops //will be executed to move the remaining data while ( i <= mid ) {


temp[k] = list[i]; i++; k++; } while ( j <= high ) { temp[k] = list[j]; j++; k++; } }

10. You can visualize the growth of a tree recursively. First you start with a trunk of set length:

From this trunk, two branches grow out:

Now if you consider the two branches as the trunks of their respective subtrees, you have another growth, resulting in:

Continue this recursive growth, and you will end up with a tree that looks something like this:


The length of the branch will get shorter and shorter. Once the length becomes shorter than some preset value, the recursion stops. Also, as you can see from the tree above, you should use some form of probability whether the branch will continue to grow or not. Try first the fixed probability of 0.9. Experiment with others, such as the probability of growth is a function based on the length of the branch. import javax.swing.*; import java.awt.*; import java.awt.geom.*; import java.awt.event.*; public class recursiveTree extends JFrame implements ActionListener{ private JPanel drawingField; private Graphics paper; private JButton draw1; private JButton draw2; public recursiveTree() { Container contentPane = getContentPane(); setSize(500, 500); setResizable(false); draw1 = new JButton("Linear"); draw1.setBounds( 25, 420, 80, 30 ); draw1.addActionListener(this); draw2 = new JButton("Logarithmic"); draw2.setBounds( 110, 420, 80, 30); draw2.addActionListener(this); drawingField = new JPanel(); drawingField.setBounds( 25, 10, 400, 400 ); contentPane.add(drawingField); setVisible(true);


contentPane.add(draw1); contentPane.add(draw2); contentPane.add(new JLabel("")); paper = drawingField.getGraphics(); paper.setColor(Color.BLACK); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed( ActionEvent a ) { JButton pressed = (JButton)(a.getSource()); paper.clearRect(0,0,400,400); if( pressed == draw1 ) { drawTree( 200, 400, 270.0, 80.0 ); } else if( pressed == draw2 ) { drawTree2( 250, 400, 270.0, 80.0 ); } } public void drawTree( int x, int y, double angle, double length ) { int dx = (int)(Math.cos(Math.toRadians(angle)) * length); int dy = (int)(Math.sin(Math.toRadians(angle)) * length); paper.drawLine(x, y, x+dx, y+dy); if( length > 5 && Math.random() <= 0.9 ) { drawTree( x+dx, y+dy, angle - 22.0, length *= 0.8 ); drawTree( x+dx, y+dy, angle + 22.0, length *= 0.8 ); } } public void drawTree2( int x, int y, double angle, double length ) { int dx = (int)(Math.cos(Math.toRadians(angle)) * length); int dy = (int)(Math.sin(Math.toRadians(angle)) * length); double prob = .85 + Math.log(length); paper.drawLine(x, y, x+dx, y+dy); if( length > 5 && Math.random() <= prob ) { drawTree( x+dx, y+dy, angle - 22.0, length *= 0.9 ); drawTree( x+dx, y+dy, angle + 22.0, length *= 0.9 ); } } public static void main( String [] args ) { recursiveTree tree = new recursiveTree(); tree.drawTree2( 200, 400, 270.0, 80.0 ); } }



Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.