SlideShare ist ein Scribd-Unternehmen logo
1 von 110
Downloaden Sie, um offline zu lesen
IBM Enterprise IT and Asset Management 7.1: Java for
Customization
Student Exercises
S150-3086-00
May 2009
Copyright Notice
Copyright © 2009 IBM Corporation, including this documentation and all software. All rights
reserved. May only be used pursuant to a Tivoli Systems Software License Agreement, an IBM Soft-
ware License Agreement, or Addendum for Tivoli Products to IBM Customer or License Agreement.
No part of this publication may be reproduced, transmitted, transcribed, stored in a retrieval system,
or translated into any computer language, in any form or by any means, electronic, mechanical,
magnetic, optical, chemical, manual, or otherwise, without prior written permission of IBM Corpora-
tion. IBM Corporation grants you limited permission to make hardcopy or other reproductions of any
machine-readable documentation for your own use, provided that each such reproduction shall carry
the IBM Corporation copyright notice. No other rights under copyright are granted without prior writ-
ten permission of IBM Corporation. The document is not intended for production and is furnished “as
is” without warranty of any kind. All warranties on this document are hereby disclaimed, including the
warranties of merchantability and fitness for a particular purpose.
Note to U.S. Government Users—Documentation related to restricted rights—Use, duplication or
disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corporation.
Trademarks
The following are trademarks of IBM Corporation or Tivoli Systems Inc.: IBM, Tivoli, AIX, Cross-Site,
NetView, OS/2, Planet Tivoli, RS/6000, Tivoli Certified, Tivoli Enterprise, Tivoli Ready, TME. In Den-
mark, Tivoli is a trademark licensed from Kjøbenhavns Sommer - Tivoli A/S.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in
the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other countries.
C-bus is a trademark of Corollary, Inc. in the United States, other countries, or both.
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States,
other countries, or both.
Lotus is a registered trademark of Lotus Development Corporation.
PC Direct is a trademark of Ziff Communications Company in the United States, other countries, or
both and is used by IBM Corporation under license.
ActionMedia, LANDesk, MMX, Pentium, and ProShare are trademarks of Intel Corporation in the
United States, other countries, or both.
SET and the SET Logo are trademarks owned by SET Secure Electronic Transaction LLC. For fur-
ther information, see http://www.setco.org/aboutmark.html.
Other company, product, and service names may be trademarks or service marks of others.
Notices
References in this publication to Tivoli Systems or IBM products, programs, or services do not imply
that they will be available in all countries in which Tivoli Systems or IBM operates. Any reference to
these products, programs, or services is not intended to imply that only Tivoli Systems or IBM prod-
ucts, programs, or services can be used. Subject to valid intellectual property or other legally pro-
tectable right of Tivoli Systems or IBM, any functionally equivalent product, program, or service can
be used instead of the referenced product, program, or service. The evaluation and verification of
operation in conjunction with other products, except those expressly designated by Tivoli Systems or
IBM, are the responsibility of the user. Tivoli Systems or IBM may have patents or pending patent
applications covering subject matter in this document. The furnishing of this document does not give
you any license to these patents. You can send license inquiries, in writing, to the IBM Director of
Licensing, IBM Corporation, North Castle Drive, Armonk, New York 10504-1785, U.S.A.
Printed in Ireland.
•
•
•
•
•
I
Table of Contents
Student Exercises for Unit 1
No student exercises are provided for this unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1
Student Exercises for Unit 2
Exercise 1: Create a Java Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1
Exercise 2: Create the HelloWorld Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Exercise 3: Eclipse Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Exercise 4: Write the HelloWorld class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Exercise 5: Build the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Exercise 6: Run the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Student Exercises for Unit 3
Exercise 1: Calculate an Average . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1
Exercise 2: Determine a Maximum or Minimum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Exercise 3: Create the WestToEast Class (Optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5
Exercise 4: Debug the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
Student Exercises for Unit 4
Exercise 1: Create the ModAdd Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1
Exercise 2: Debug the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Student Exercises for Unit 5
Exercise 1: Create the ReverseArgs Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1
Exercise 2: Create the Calculator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Exercise 3: Create the Util Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Exercise 4: Create the Perform Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Student Exercises for Unit 6
Exercise 1: Implement Exception Handing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1
Exercise 2: Read and Write to Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1
Student Exercises for Unit 7
Exercise 1: Using an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1
Exercise 2: Using an Interface and Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Student Exercises for Unit 8
Exercise 1: Determine a Median . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1
Exercise 2: Use a LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1
Exercise 3: Use an ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
II IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Table of Contents
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Exercise 4: Create a Deck of Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
Exercise 5: Create a Hospital . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5
Student Exercises for Unit 9
Exercise 1: The Producer–Consumer Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-1
Student Exercises for Unit 10
Exercise 1: Create a Serializable Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-1
Exercise 2: Serialize an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-1
Exercise 3: Deserialize an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Exercise 4: Using RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Appendix A: Exercise Solutions
Unit 1 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1
No solutions are provided. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1
Unit 2 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1
Unit 3 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1
Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1
Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-3
Unit 4 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4
Unit 5 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5
Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5
Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6
Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-7
Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-8
Unit 6 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-10
Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-10
Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-11
Unit 7 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-13
Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-13
Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-14
Unit 8 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-21
Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-21
Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-22
Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-23
Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-24
Exercise 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-26
Unit 9 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-34
Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-34
Unit 10 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-36
Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-36
Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-37
Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-38
Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-39
•
•
•
•
•
1-1
Student Exercises for Unit 1
No student exercises are provided for this unit.
1-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 1
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
•
•
•
•
•
2-1
Student Exercises for Unit 2
Exercise 1: Create a Java Project
In this exercise, you will create a Java project that points to the JavaBasics directory. This
root directory will contain your source code. Your compiled code will also remain in this
directory.
___ 1. Open the Eclipse IDE, if it is not already open.
___ 2. Select the New option or navigate to File > New in the main menu.
___ 3. Select Project.
2-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 2
Exercise 1: Create a Java Project
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 4. Select Java Project and click Next.
___ 5. In the Project name field, type JavaBasics.
___ 6. Select Create project from existing source.
___ 7. Browse for the directory C:JavaBasics.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-3
•
•
•
•
•
Student Exercises for Unit 2
Exercise 2: Create the HelloWorld Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 8. Click Finish.
___ 9. The project named JavaBasics is created and can be accessed from the Package
Explorer tab. Expand the project. It is set up with the necessary JRE and .jar files.
Exercise 2: Create the HelloWorld Class
In this exercise you will use the Eclipse IDE to create the HelloWorld class. The
HelloWorld class will contain only a main() method with a statement to display the text
Hello World! and I am here! to the console.
The HelloWorld class will belong to the exercises.hello package.
The following examples show two possible outlines for the HelloWorld class.
2-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 2
Exercise 2: Create the HelloWorld Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
package exercises.hello;
public class HelloWorld {
public static void main(String[] args) {
// Display "Hello World! I am here!" to the console
}
}
// The following is an alternative outline:
package exercises.hello;
public class HelloWorld {
public static void main(String[] args) {
printHelloWorld();
}
public static void printHelloWorld() {
// Display "Hello World! I am here!" to the console
}
}
___ 1. Click the New drop-down menu, and select Class, or File > New > Class from the
main menu to access the New Java Class dialog box.
___ 2. Enter exercises.hello in the Package field.
___ 3. Enter HelloWorld in the Name field.
___ 4. Click the public static void main(String[] args) check box to select it.
Your screen should look like the following example.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-5
•
•
•
•
•
Student Exercises for Unit 2
Exercise 2: Create the HelloWorld Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 5. Click Finish.
___ 6. The class file HelloWorld.java is created. The file is listed in the Package
Explorer. A skeleton class with main() has been generated and is in the edit
window.
2-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 2
Exercise 3: Eclipse Features
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 7. Double-click the HelloWorld.java tab to expand the edit window. Double-click
the same tab to toggle back to the package view.
Exercise 3: Eclipse Features
___ 1. Eclipse contains context-sensitive help. To demonstrate this feature, try writing a
line of code inside the main() method, such as System.out. After typing
System.out, press Ctrl+Space for context-sensitive help.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-7
•
•
•
•
•
Student Exercises for Unit 2
Exercise 4: Write the HelloWorld class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 2. Complete a line of code and omit the semicolon on purpose. Eclipse will detect
that a missing semicolon is a syntax error, and that line of code will be flagged
with a red error symbol.
.
___ 3. Mistype more lines of code to demonstrate some helpful features of Eclipse.
Exercise 4: Write the HelloWorld class
___ 1. Write the HelloWorld class according to the outline illustrated in Exercise 2.
___ 2. Use the System.out.println() method to output text to the console.
___ 3. Save the file.
Exercise 5: Build the Project
___ 1. Right-click the JavaBasics project and select Build Project.
___ 2. If the Project > Build Automatically option is selected, clear the option.
___ 3. After the project is built, the errors are displayed on the Problems tab. Double-
click any error. The cursor is placed on the error line.
___ 4. After you fix the error, rebuild the project.
2-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 2
Exercise 6: Run the Application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Exercise 6: Run the Application
___ 1. Ensure that there are no compile errors after building the project.
___ 2. To run the application, select the HelloWorld.java file on the Package Explorer
tab. The file must have a main() to run.
___ 3. Navigate to Run > Run Configurations from the main menu.
___ 4. In the dialog box, select Java Application from the list.
___ 5. Click the New launch configuration icon to create a HelloWorld configuration.
The configuration includes the path to the main class.
___ 6. Click Apply.
___ 7. Click Run. Output is sent to the console.
___ 8. Select the Console tab to view the application output.
•
•
•
•
•
3-1
Student Exercises for Unit 3
Exercise 1: Calculate an Average
In this exercise you will write a class to calculate the average of a variable number of
arguments.
The average of a set of numeric values is determined by adding all of the values together
and dividing the calculated sum by the number of values. For example, the average of 10,
4, 8, 6, 5, 10, and 13 is 8:
(10+4+8+6+5+10+13)/7 = 56/7 = 8
The class must include a main() method. Within the body of the main() method, convert
each argument to a numeric data type, calculate the average, and output the result.
___ 1. Select File > New > Package to create the exercises.calc package using the
Eclipse IDE.
___ 2. Select the exercises.calc package and right-click to access the context menu.
___ 3. Select New > Class from the context menu and create the Average class. Select
the option to include a main() method when creating your class.
___ 4. Within the main() method, write the code to calculate an average of the program
arguments.
– The program arguments are stored in the variable args, which is an array of
Strings.
– The variable args[0] returns the first argument, args[1] returns the second
argument, and so on.
– The variable args.length returns an integer value that represents the number
of arguments.
– Use the static method Double.parseDouble(String s) to convert an argument
from a String data type to a numeric value.
– The following example shows one possible way to iterate through the
arguments:
for (String v : args) {
System.out.print(v + “ “);
}
System.out.println();
3-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 3
Exercise 1: Calculate an Average
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 5. Use the System.out.println() method to output the calculated average.
___ 6. Save and compile the Average class.
___ 7. Select the Average file in the Package Explorer. Click Run > Run
Configurations from the main menu.
___ 8. Create a new launch configuration.
___ 9. Select the Arguments tab.
___ 10. Type numeric arguments separated by white space to test the class.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-3
•
•
•
•
•
Student Exercises for Unit 3
Exercise 2: Determine a Maximum or Minimum
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 11. Run the Average class and verify the results.
Exercise 2: Determine a Maximum or
Minimum
In this exercise you will write a class to determine the maximum or minimum of two
numeric values.
The class should include a main() method. You will provide three arguments. The first
argument is max or min. The second and third arguments are numeric values.
If the first argument is max, print the greater of the numeric arguments to the console. If
the first argument is min, print the lesser of the numeric arguments to the console.
___ 1. Right-click the exercises.calc package.
___ 2. Select New > Class from the context menu and create the MaxOrMin class.
Select the option to include a main( ) method when creating your class.
___ 3. Within the main() method, write the code to print either the maximum or
minimum of the numeric values given as program arguments.
The program arguments are stored in the variable args, which is an array of
Strings.
The variable args[0] returns the first argument, args[1] returns the second
argument, and so on.
3-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 3
Exercise 2: Determine a Maximum or Minimum
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Hint: The following methods are useful for the exercise:
– Double.parseDouble(String s)
– The equalsIgnoreCase(String s) method from the String class
– The static Math.max() and Math.min( ) methods
___ 4. Use the System.out.println() method to output the maximum or minimum value.
___ 5. Save and compile the MaxOrMin class.
___ 6. Select the MaxOrMin file in the Package Explorer. From the main menu, select
Run > Run Configurations.
___ 7. Create a new launch configuration.
___ 8. Select the Arguments tab.
___ 9. Type max or min and two numeric arguments separated by white space to test the
class.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-5
•
•
•
•
•
Student Exercises for Unit 3
Exercise 3: Create the WestToEast Class (Optional)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 10. Run the MaxOrMin class and verify the results.
Exercise 3: Create the WestToEast Class
(Optional)
Coordinated Universal Time (UTC) is a time standard roughly equivalent to Greenwich
Mean Time (GMT). Conversion between time zones is such that the following relationship
is true and each side of the equation is equivalent to UTC:
Time in Zone A − UTC Offset for Zone A = Time in Zone B − UTC Offset for Zone B
The equation can be rewritten as:
Time in Zone B = Time in Zone A − UTC Offset for Zone A + UTC Offset for Zone B
Use the following equation to determine what time it is in Los Angeles (UTC offset = −08)
when it is 8:30 a.m. in New York City (UTC offset = -5):
Time in Los Angeles = 08:30 − (−05:00) + (−08:00) = 05:30
This exercise demonstrates a class that uses the classes in Java API, and it has enough
content for you to try the Eclipse debugging features. An outline for the class WestToEast
is partially provided for you. The program imports four Java classes that include data and
time functionality. Statements have been provided in the program; you can uncomment
them and inspect the output for guidance.
If you have previous Java or other object-oriented programming experience, try to
complete the exercise without using the solution. Otherwise, the solution is provided in the
Appendix.
3-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 3
Exercise 3: Create the WestToEast Class (Optional)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
The following example shows a possible outline for the WestToEast class:
package exercises.time;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
public class WestToEast {
public static void main(String[] args) {
// Base GMT offset: -8:00
SimpleTimeZone zone1 = new SimpleTimeZone(-8 * 60 * 60 *
1000, "America/Los_Angeles");
// Base GMT offset: -5:00
SimpleTimeZone zone2 = new SimpleTimeZone(-5 * 60 * 60 *
1000, "America/New_York");
// Create two GregorianCalendar objects
// with the East and West Coast
// time zone and the current date and time
Calendar calendar1 = new GregorianCalendar(zone1);
Calendar calendar2 = new GregorianCalendar(zone2);
Date time = new Date(); // Get current Date/Time
calendar1.setTime(time);
calendar2.setTime(time);
// System.out.println("Hour: "
// + calendar1.get(Calendar.HOUR));
// System.out.println("Minute: "
// + calendar1.get(Calendar.MINUTE));
// insert your code to calculate the East Coast time
// using the calendar1.get(Calendar.HOUR) and
// calendar1.get(Calendar.MINUTE) values
// print out the East Coast value to the console
}
}
___ 1. Create the WestToEast class in the exercises.time package using the Eclipse IDE.
___ 2. Copy the provided file or the code outline that precedes this exercise.
___ 3. Complete the class following the specifications as outlined.
___ 4. Create variables and use the Calendar.HOUR and Calendar.MINUTE values to
calculate the time in New York City, given the time in Los Angeles.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-7
•
•
•
•
•
Student Exercises for Unit 3
Exercise 4: Debug the Application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 5. Use the System.out.println() method to output the calculated value.
___ 6. Save and compile the WestToEast class.
___ 7. Select the WestToEast file in the Package Explorer. From the main menu, select
Run > Run Configurations.
___ 8. Run the WestToEast application and verify the results.
Exercise 4: Debug the Application
___ 1. Select the WestToEast class in the Package Explorer.
___ 2. Select Run > Debug Configurations from the main menu.
___ 3. In the dialog box, the WestToEast class is already displayed in the Java
Application list.
___ 4. Return to the Main tab, if necessary.
___ 5. Select the Stop in main option.
___ 6. Click Apply.
___ 7. Click Debug.
___ 8. Click Yes if the Confirm Perspective Switch message box is displayed.
___ 9. Eclipse opens the Debug perspective. Debug icons are available within this
perspective, in addition to a Variable tab to inspect variable values and a
Breakpoint tab. This debug session has stopped the program at the first statement
in main().
3-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 3
Exercise 4: Debug the Application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Familiarize yourself with the available debug icons on the Debug tab. Commonly
used icons are:
– Resume: Continue to the next breakpoint.
– Step Into: Step into the method that is called.
– Step Over: Execute current statement and move to the next statement.
– Step Return: Perform remaining statements in method and return to calling
method.
– Terminate: Halt the execution of the program.
___ 10. Right-click the outer edge of the WestToEast file and select Toggle Breakpoint
to set a breakpoint at a line of code in that file. Breakpoints suspend execution of
the program.
___ 11. Switch back to the Java perspective by clicking the Java tab (or navigate to
Window > Open Perspective > Java). Open the WestToEast file, if it is not
already open.
___ 12. Right-click the outer edge of the WestToEast file and select Toggle Breakpoint
to set a breakpoint at a line of code in that file. You can set breakpoints in either
the Debug or the Java perspective.
___ 13. Set breakpoints and step through the code using Resume, Step Into, Step Over,
and Step Return to familiarize yourself with the debug features.
•
•
•
•
•
4-1
Student Exercises for Unit 4
Exercise 1: Create the ModAdd Class
This exercise involves creating a class named ModAdd that belongs to the package
exercises.odd.
• The class ModAdd will receive two numeric arguments.
• Calculate the sum of the odd numbers that are multiples of 3 between those two
arguments, including the arguments that define the numeric limits for the
calculation.
• Calculate the sum with a for loop and a while loop.
• Use the modulus operator to determine if a number is a multiple of 3 or is an odd
number.
– A number is a multiple of 3 if num%3 equals zero.
– A number is a multiple of 2 if num%2 equals zero.
The following example shows a possible outline for the ModAdd class:
package exercises.odd;
public class ModAdd
{
// main program receives 2 arguments
public static void main(String[] args)
{
// Check if arguments are given
// If not, print error msg and System.exit(1);
//
// Get arguments and check if valid
// Calculate sum using for loop and print total
// Calculate sum using while loop and print total //
}
4-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 4
Exercise 1: Create the ModAdd Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 1. Create the ModAdd class using the Eclipse IDE.
___ 2. Write the ModAdd class following the specifications as outlined previously.
___ 3. Save and compile the ModAdd class.
___ 4. The following table contains some example calculations.
Range Odd Numbers that Are Multiples of 3 Calculated Sum
1 to 10 3,9 12
3 to 21 3,9,15,21 48
20 to 50 21,27,33,39,45 165
1 to 100 3,9,21,27,33,39,45,51,57,63,69....... 867
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 4-3
•
•
•
•
•
Student Exercises for Unit 4
Exercise 2: Debug the Application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 5. Select the ModAdd file in the Package Explorer. Click Run > Run
Configurations from the main menu.
___ 6. Select the Arguments tab and type program arguments.
___ 7. Run the ModAdd application and verify the results.
Exercise 2: Debug the Application
___ 1. Select the ModAdd class in the Package Explorer.
___ 2. Select Run > Debug Configurations from the main menu.
In the dialog box, the ModAdd is already displayed in the Java Application list.
___ 3. Select the Arguments tab if you want to type a different numeric range for the
Program arguments. Click Apply.
___ 4. Return to the Main tab.
___ 5. Select the Stop in main option.
___ 6. Click Apply.
___ 7. Click Debug.
___ 8. Click Yes if the Confirm Perspective Switch message box is displayed.
___ 9. Eclipse opens the Debug perspective. Debug icons are available within this
perspective, in addition to a Variable tab to inspect variable values and a
Breakpoint tab. This debug session has stopped the program at the first statement
in main().
4-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 4
Exercise 2: Debug the Application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 10. Right-click the outer edge of the ModAdd file and select Toggle Breakpoint to
set a breakpoint at a line of code in that file.
___ 11. Switch back to the Java perspective by clicking the Java tab (or click Window >
Open Perspective > Java). Open the ModAdd file, if it is not already open.
___ 12. You can set breakpoints in either the Debug or the Java perspective. Set
breakpoints and step through the code using Resume, Step Into, Step Over, and
Step Return.
•
•
•
•
•
5-1
Student Exercises for Unit 5
Exercise 1: Create the ReverseArgs Class
This exercise involves creating a class named ReverseArgs that belongs to the package
exercises.str. You will print out the argument list in reverse.
• The ReverseArgs class will receive two or more arguments.
• The ReverseArgs class will contain a method to reverse the arguments letter by
letter.
• The ReverseArgs class will contain a method to reverse the arguments word by
word.
The following example shows a possible outline for the ReverseArgs class:
package examples.str;
public class ReverseArgs {
public static void main(String args[]){
if(args.length < 2) {
// print usage statement
return;
}
StringBuilder strArguments = new StringBuilder();
// Build a string using the args[]
reverseArguments(strArguments);
System.out.println ("strArguments = " + strArguments);
// return strArguments to its original state
reverseArguments(strArguments);
System.out.println ("strArguments = " + strArguments);
reverseWords(strArguments);
System.out.println ("strArguments = " + strArguments);
}
5-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 5
Exercise 2: Create the Calculator Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
public static StringBuilder
reverseArguments(StringBuilder s) {
// reverse the argument list, letter by letter
// Use reverse() to reverse a string
return s;
}
public static StringBuilder reverseWords(StringBuilder
s) {
// reverse the argument list word by word
return s;
}
}
___ 1. Create the ReverseArgs class using the Eclipse IDE.
___ 2. Write the ReverseArgs class following the specifications as outlined in the
preceding example.
___ 3. Save and compile the ReverseArgs class.
___ 4. Verify the results.
Exercise 2: Create the Calculator Class
This exercise involves creating a class named Calculator that belongs to the package
exercises.calc.
• The class Calculator will receive three arguments: an operator and two operands.
• Calculate the result of the operator and the operands.
• The operator is not case-sensitive, and requires only the portion shown in bold in
the preceding table to be a valid operator.
Operator Operands
add operand1 + operand 2
subtract operand1 - operand 2
multiply operand1 * operand 2
divide operand1 / operand 2
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 5-3
•
•
•
•
•
Student Exercises for Unit 5
Exercise 2: Create the Calculator Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Examples of valid command-line arguments are:
Add 77 55
sub 3 8
Subtract 33 22
Multi 1 7
DIVIDE 33 12
• The String class methods are useful to find the operation.
The following example shows a possible outline for the Calculator class:
package exercises.calc;
public class Calculator
{
public void add(double o1, double o2)
{ }
public void sub(double o1, double o2)
{ }
public void mult(double o1, double o2)
{ }
public void div(double o1, double o2)
{ }
public static void main(String[] args)
{
// Check if 3 arguments are given
// Check if operation and operations are valid
// If not, print error msg and System.exit(1);
//
if(operation is "add")
add(op1, op2);
else if (operation is "sub")
sub(op1, op2);
....
}
___ 1. Create the Calculator class using the Eclipse IDE.
___ 2. Write the Calculator class following the specifications as outlined previously.
___ 3. Save and compile the Calculator class.
___ 4. Verify the results.
5-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 5
Exercise 3: Create the Util Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Exercise 3: Create the Util Class
This exercise involves creating a utility class called Util that contains static methods for the
add, subtract, multiply, and divide operations. The class belongs to the exercises.util
package.
• Overload the methods for each operation to allow for different data types, such as:
public static int add(int op1, int op2){....}
public static double add(double op1, double op2){....}
• Example usage statement:
double result = Util.sub(55.3, 22.1);
The following example shows a possible outline for the Util class:
package exercises.util;
public class Util
{
public static int add(int o1, int o2)
{
}
public static double add(double o1, double o2)
{
}
public static int sub(int o1, int o2)
{
}
public static double sub(double o1, double o2)
{
}
....
}
___ 1. Create the Util class using the Eclipse IDE.
___ 2. Write the Util class following the specifications as outlined previously.
___ 3. Save and compile the Util class.
___ 4. Verify the results.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 5-5
•
•
•
•
•
Student Exercises for Unit 5
Exercise 4: Create the Perform Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Exercise 4: Create the Perform Class
This exercise involves creating a class named Perform that belongs to the package
exercises.calc. The Perform class uses the Util class, which is in a different package.
• The class Perform will receive three arguments: an operator and two operands.
• The operands can be integer or double data types. If one operand is a double data
type, both are assumed to be of type double.
The following example shows a possible outline for the Perform class:
public class Perform
{
public static void main(String[] args)
{
// Check for arguments
// Convert arguments to numeric variables
String num1;
String num2;
// Assign operands arguments to Strings and
// Check if operands are int or double
// int data type does not have a decimal point
// double data type has a decimal point
if (num1.indexOf(".") != -1)
// string represents a double
else
// string represents an integer
// place operands into int or double variables
// call the correct operation with the operands
// if the operation is add:
Util.add(op1, op2);
....
}
}
___ 1. Create the Perform class using the Eclipse IDE.
___ 2. Write the Perform class following the specifications as outlined previously.
___ 3. Save and compile the Perform class.
___ 4. Verify the results.
5-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 5
Exercise 4: Create the Perform Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
•
•
•
•
•
6-1
Student Exercises for Unit 6
Exercise 1: Implement Exception Handing
This exercise involves making a copy of the Perform.java file, renaming it Do.java, and
adding exception handling.
• Throw an exception if parameters are not provided or if the operation is invalid.
• Use try-catch blocks to catch exceptions when parsing arguments.
___ 1. Copy the contents of Perform.java and rename the file and class Do.java.
___ 2. Add exception handling to the class.
___ 3. Save and compile the Do.java file.
___ 4. Verify the results with the cases in the following table.
Exercise 2: Read and Write to Text Files
This exercise involves reading and writing to a text file using the FileReader,
BufferedReader, FileWriter, and BufferedWriter classes.
A useful class for this exercise is java.util.Scanner, which can be used for parsing fields
from a file. Regular expressions in the String class provide a replacement for the
deprecated java.util.StringTokenizer class.
Arguments Expected Result at Runtime
No arguments Invalid case
Add 1.0 two.2 Second operand is not a number
abc 2 3 Invalid operation
Sub 77 22 Valid case
6-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 6
Exercise 2: Read and Write to Text Files
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
• A file containing lines of text, some of which are palindromes, has been provided
for you. A palindrome is a sentence or word that reads the same from right to left,
or left to right. The classic example is Madam, I’m Adam.
• Your code will examine each line of the text file and determine whether the line of
text is a palindrome. If the line is a palindrome, then the line will be written to a
new file.
• Handle IOException when necessary.
The following example shows a possible outline for the class:
public class Palindromes {
public static void main(String[] args) throws IOException
{
if (args.length != 2) {
System.out.println("Usage: Must have 2 parameters");
System.exit(1);
}
File inFile = new File(args[0]);
File outFile = new File(args[1]);
boolean exists = inFile.exists();
if (!exists) {
System.out.println("File " + inFile.getName()+ does not
exist");
System.exit(1);
}
try {
filter4Palindromes(inFile, outFile1);
} catch (IOException e) {
System.out.println(e);
System.exit(1);
}
}
public static void filter4Palindromes(File in, File out)
throws IOException {
BufferedReader reader = new BufferedReader(new
FileReader(in));
BufferedWriter writer = new BufferedWriter(new
FileWriter(out));
// create Strings and StringBuilder objects
// to manipulate lines of text
// loop through the lines of
// text while reader.readLine()) != null
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 6-3
•
•
•
•
•
Student Exercises for Unit 6
Exercise 2: Read and Write to Text Files
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
// if the line is a palindrome then write
// the palindrome to the output file
// close the reader
// close the writer }
___ 1. Create the Palindromes class using the Eclipse IDE.
___ 2. Write the Palindromes class following the specifications as shown in the outline.
___ 3. Save and compile the Palindromes class.
___ 4. Verify the results.
6-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 6
Exercise 2: Read and Write to Text Files
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
•
•
•
•
•
7-1
Student Exercises for Unit 7
Exercise 1: Using an Interface
This exercise uses an interface to demonstrate polymorphism. It involves creating an
interface named HowAreYou and writing three classes that implement that interface. Each
class will print “How are you?” in its own language.
• Throw an exception if parameters are not provided or if the operation is invalid.
• Use try-catch blocks to catch exceptions when parsing arguments.
___ 1. Using the Eclipse IDE, create an interface named HowAreYou.java that contains
a single method named sayHowAreYou().
___ 2. Create three class files that implement the HowAreYou interface, such as:
– EnglishHowAreYou.java
– ItalianHowAreYou.java
– FrenchHowAreYou.java
___ 3. Each of the three classes must implement the sayHowAreYou() method and print
“How are you?” to the console in the appropriate language.
___ 4. Create a class named SayHowAreYou that contains main().
___ 5. The SayHowAreYou class contains an instance of the HowAreYou interface, sets
the language to the three different implementing classes, and prints “How are
you?” to the console in three different languages.
The following example shows a possible outline for the driver class:
package exercises.HowRU;
public class SayHowAreYou {
public HowAreYou howAreYou;
public void setLanguage(HowAreYou howAreYou) {
this.howAreYou = howAreYou;
}
7-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
public void sayHowAreYou() {
this.howAreYou.sayHowAreYou();
}
public static void main(String[] args) {
SayHowAreYou howru = new SayHowAreYou();
// set the language to English and print out
// the message
// set the language to Italian and print out
// the message
// set the language to French and print out
// the message
}
}
___ 6. Save and compile the classes.
___ 7. Verify the results.
Exercise 2: Using an Interface and
Abstract Classes
This exercise involves writing an interface, abstract classes, and their subclasses. Both
inheritance and polymorphism are incorporated into the class design of this exercise.
You will create multiple instrument-type objects; each implements its own play() method.
How you choose to override the methods in the class hierarchy will determine which play()
method is called.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-3
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
The following diagram shows the top-level design specification.
The interface is named Instrument and contains three methods:
• mute()
• play()
• tune()
Four abstract classes implement the Instrument interface:
• BowType
• PluckType
• StrikeType
• WindType
7-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
In addition to implementing all of the methods contained in the Instrument interface, each
of these classes also includes its own constructor and a getName() method.
Multiple subclasses will extend the abstract classes and override the implementation of the
abstract class methods.
Each class will inherit all of the functionality of its superclass. In this case, the abstract
classes are the superclasses. The abstract classes contain the methods from the Instrument
interface, and any additional methods as outlined in the design illustration.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-5
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Next you will create the subclasses. The abstract class BowType has three subclasses:
• Violin
• Viola
• Cello
The abstract class PluckType has two subclasses:
• Guitar
• Bass
The abstract class StrikeType has two subclasses:
• Piano
• Drum
The abstract class WindType has one subclass:
• Saxophone
The complete specification is illustrated on the next page.
7-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-7
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
After all of the subclasses have been created, you will create a Quartet class that contains
four instruments and has at least one method: playMusic().
The Quartet class could be written to contain a createStringQuartet method, creating a
string quartet that contains two Violin objects, a Viola object, and a Cello object. Another
option is to create a jazz quartet with a Saxophone, Piano, Bass, and Drum object. A third
option is a rock quartet with two Guitar objects, a Bass object, and a Drum object.
The driver to verify these classes might be implemented like the following main() method:
package exercises.music;
public class MakeMusic {
public static void main(String[] args) {
Quartet qString = new Quartet();
qString.createStringQuartet();
qString.playMusic();
Quartet qJazz = new Quartet();
qJazz.createJazzQuartet();
qJazz.playMusic();
Quartet qRock = new Quartet();
qRock.createRockQuartet();
qJazz.playMusic();
}
}
7-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 1. In the exercises.music package, create an interface named Instrument.java that
contains three public methods:
– play()
– tune()
– mute()
___ 2. Create four abstract class files that implement the Instrument interface:
– BowType.java
– PluckType.java
– StrikeType.java
– WindType.java
___ 3. Each of the four classes must implement the methods from the Instrument
interface in addition to a constructor and a getName() method. The
implementation is to print the name of the corresponding class and method to the
console.
___ 4. Create eight subclasses:
– The Violin, Viola, and Cello classes extend the abstract class BowType.
– The Guitar and Bass classes extend the abstract class PluckType.
– The Piano and Drum classes extend the abstract class StrikeType.
– The Saxophone class extends the abstract class WindType.
The implementation for each method in the subclasses is to print the name of the
corresponding class and method to the console.
___ 5. Create a Quartet class in the same exercises.music package as the other classes
created thus far.
___ 6. Add a collection of four instruments to the Quartet class.You can implement the
collection with an array or use a collection class.
___ 7. Implement a playMusic() method that loops through the instruments and calls the
play() method of each one.
___ 8. Write a driver class that contains a main() method to test your implementation of
the class design.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-9
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
The following example shows a possible outline for the driver class:
public class MakeMusic {
public static void main(String[] args) {
Quartet qJazz = new Quartet();
qJazz.createJazzQuartet();
qJazz.playMusic();
}
}
___ 9. Save and compile the classes.
___ 10. Verify the results.
7-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 7
Exercise 2: Using an Interface and Abstract Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
•
•
•
•
•
8-1
Student Exercises for Unit 8
Exercise 1: Determine a Median
In this exercise you will write a class to determine the median of a variable number of
arguments. To find the median value, place the values in order and find the middle value.
If there is an even number of values, find the middle pair of values and calculate the average
of those two values.
___ 1. Create the new class Median in the exercises.calc package.
___ 2. Within the main() method, write the code to calculate the median of the program
arguments.
Hint: The java.util.Arrays.sort() method is useful for this exercise.
___ 3. Save and compile the Median class.
___ 4. Run the Median class and verify the results.
Exercise 2: Use a LinkedList
In this exercise you create a class that implements the LinkedList class and uses the
ListIterator to print a list in reverse.
• Throw any necessary IO exceptions.
• Use try-catch blocks to catch exceptions.
8-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 8
Exercise 2: Use a LinkedList
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 1. Create a class named LList.java that contains a main() method.
___ 2. The LList.java class takes one parameter, which is the name of a text file. You
can create a text file for testing or use the input file from the Palindrome exercise.
___ 3. Write a fillList() method that:
– Reads the input file
– Adds each line as an element to a LinkedList object
– Uses a ListIterator object to traverse the list in reverse
– Prints each line to the console
___ 4. Create an outline for the LList class. For example:
package exercises.list;
public class LList {
public static void main(String[] args) {
// check for input parameter
File inFile = new File(args[0]);
// Verify that the file exists
try {
fillList(inFile);
} catch (IOException e) {
// handle exception
}
}
public static void fillList(File in) throws IOException {
BufferedReader reader =
new BufferedReader(new FileReader(in));
LinkedList<String> lst = new LinkedList<String>();
String line = null;
while ((line=reader.readLine()) != null) {
lst.add(line);
}
System.out.println("Print list in reverse");
// Use a ListIterator object within a for loop and
// print the list in reverse
}
}
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-3
•
•
•
•
•
Student Exercises for Unit 8
Exercise 3: Use an ArrayList
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 5. Save and compile the class.
___ 6. Verify the results.
Exercise 3: Use an ArrayList
In this exercise you create a class that implements the ArrayList class and uses the
ListIterator to print a list.
___ 1. Create a copy of the LList class and name the copy AList.java.
___ 2. Rewrite AList.java to use an ArrayList class instead of a LinkedList class to
store the lines of text from the input file.
___ 3. Use an iterator in the fillList() method to traverse the collection. Print the contents
of the collection in a forward direction and in reverse.
___ 4. Save and compile the class.
___ 5. Verify the results.
Exercise 4: Create a Deck of Cards
In this exercise you will write a class to represent a deck of 52 cards. The class should
include the following items:
• A constructor that creates the deck of cards and stores it within an appropriate data
structure. The deck of cards should contain a sequence of 13 cards in four suits
(spades, clubs, hearts, and diamonds).
• A printDeck() method to print the deck of cards.
• A shuffleDeck() method to shuffle the deck of cards.
• A dealFromTop() method to deal five cards from the top of the deck.
• A dealFromBottom() method to deal five cards from the bottom of the deck.
___ 1. Create the new class Deck in the new exercises.cards package.
Hint: The java.util.Collections.shuffle() method is useful for this exercise.
8-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 8
Exercise 4: Create a Deck of Cards
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 2. Create a driver class called ShuffleNDeal in the exercises.cards package. Within
the main() method, the following outline can be used:
public class ShuffleNDeal {
public static void main(String[] args) {
Deck deck = new Deck();
deck.printDeck();
deck.shuffleDeck();
deck.dealFromTop(4);
deck.dealFromBottom(3);
deck.shuffleDeck();
deck.dealFromTop(2);
}
}
___ 3. Save and compile the Deck and ShuffleNDeal classes.
___ 4. Run the ShuffleNDeal class and verify the results.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-5
•
•
•
•
•
Student Exercises for Unit 8
Exercise 5: Create a Hospital
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Exercise 5: Create a Hospital
This exercise shows you how to coordinate and debug multiple classes that interact with
each other. You will incorporate all that you have learned so far and create classes that
represent a hospital setting. The hospital setting will be composed of different objects. Use
the object design outlined in this exercise or create your own.
• The hospital has:
– Doctors
– Patients
– Labs, such as an X-ray lab and a blood lab
• The doctors can:
– Request tests for their patients, such as an X-ray test and a blood test
– Get test results, such as X-ray test results or blood test results
8-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 8
Exercise 5: Create a Hospital
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
In this exercise, try to use:
– Inheritance (is-a relationship)
– Composition (has-a relationship)
– Abstract classes or interfaces
– Polymorphism
– Subclasses
– Private, protected, and public variables and methods
– Collection classes to store lists
– Exception handling
Lab, MedicalTest, and Result are abstract classes. The Hospital class contains an
XRayLab and BloodLab object, in addition to a list of Patient and Doctor objects.
The Patient objects contain a reference to their Doctor. The Doctor objects can request
tests and get results for their Patient objects.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-7
•
•
•
•
•
Student Exercises for Unit 8
Exercise 5: Create a Hospital
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
The following illustration outlines 13 classes that represent a hospital setting. Classes and
their variables and methods are outlined. This class design can be used to create a possible
solution, or you may design your own classes to represent a hospital.
8-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 8
Exercise 5: Create a Hospital
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
The Eclipse IDE offers multiple ways to view a class hierarchy, types, and class members.
The previous image contains detailed information regarding the class members.
The following graphic details the class hierarchy, specifically the CountyHospital class,
which extends Hospital and contains the main( ) method.
The main() method calls helper methods to populate the hospital with doctors and patients,
request tests for the labs, run the tests, and get the results.
This graphic also illustrates that Lab, MedicalTest, and Result are all abstract classes, as
denoted by the letter A.
You can use the classes presented in the graphics or produce your own class design to
represent a hospital setting.
Remember that the purpose of this exercise is to gain experience writing classes that
interact with one other. The classes make requests of other objects, and share data while
using the public, private, and protected access modifiers.
___ 1. Create the classes necessary to produce a hospital setting as described in the
preceding description.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-9
•
•
•
•
•
Student Exercises for Unit 8
Exercise 5: Create a Hospital
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 2. Save and compile the classes.
___ 3. Add print statements to your code and use the debugger to correct programming
and logic errors.
___ 4. Verify the results.
– Are lists of doctors and patients being maintained?
– Are tests objects being processed by the lab objects, and are results generated?
– Are the lab requests being maintained and processed?
While verifying the results, the console output might look something like the following
example.
8-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 8
Exercise 5: Create a Hospital
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
•
•
•
•
•
9-1
Student Exercises for Unit 9
Exercise 1: The Producer–Consumer
Classes
Threads that execute in parallel and share common resources must be synchronized at
certain points to ensure proper functioning of the system.
In this exercise you add code to a partially completed class. The code you add will
synchronize the data shared between the Producer and the Consumer classes so that the
two classes can work together.
The Producer-Consumer example is often used to illustrate thread synchronization
techniques. The Producer-Consumer classes were written to create a practical example.
The Producer and Consumer classes share a common resource: the SharedData class.
The Producer class contains an infinite loop that generates integer values in sequence and
places those integer values into the SharedData object. The Consumer class contains an
infinite loop that reads the integer values from the SharedData object.
The purpose of this exercise is to synchronize the classes so that consecutive integers are
not lost and duplicate integers are not retrieved.
The following example shows the contents of the Producer, Consumer, and SharedData
classes:
public class Producer implements Runnable
{
SharedData data;
int interval;
int identifier;
public Producer(SharedData data, int id, int interval) {
this.data=data;
this.interval=interval;
this.identifier=id;
}
public void run() {
int i;
for(i=0; ; i++) {
data.put(i);
System.out.println("Producer "+ identifier+ ": "+i);
try {
9-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 9
Exercise 1: The Producer–Consumer Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Thread.sleep((int) (Math.random()*interval));
} catch (InterruptedException e)
{System.out.println("Producer errorn");}
}
}
}
public class Consumer implements Runnable
{
SharedData data;
int interval;
int identifier;
public Consumer(SharedData data, int id, int interval) {
this.data=data;
this.interval=interval;
this.identifier=id;
}
public void run() {
for(;;) {
System.out.println(" Consumer "
+ identifier + ": "+data.get());
try {
Thread.sleep((int) (Math.random()*interval));
} catch (InterruptedException e)
{System.out.println("Consumer errorn");}
}
}
}
public class SharedData {
protected int data;
public void put(int data) {
this.data=data;
}
public int get() {
return this.data;
}
The ProducerConsumerDriver class acts as the driver and takes the following
parameters:
• ProducerNumber is the number of Producer threads.
• ConsumerNumber is the number of Consumer threads.
• producerPriority is the priority that will be assigned to the Producer thread or
threads.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-3
•
•
•
•
•
Student Exercises for Unit 9
Exercise 1: The Producer–Consumer Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
• consumerPriority is the priority that will be assigned to the Consumer thread or
threads.
• interval is the sleep() interval in milliseconds between consecutive writes or
reads from the Producer and Consumer thread or threads.
public class ProducerConsumerDriver {
public static void main(String[] args) {
SharedData data;
Thread Producers[];
Thread Consumers[];
int ProducerNumber;
int ConsumerNumber;
int producerPriority;
int consumerPriority;
int interval;
if (args.length < 5 ) {
// print usage to console
return;
}
ProducerNumber=Integer.parseInt(args[0]);
ConsumerNumber=Integer.parseInt(args[1]);
producerPriority = Integer.parseInt(args[2]));
consumerPriority = Integer.parseInt(args[3]);
interval=Integer.parseInt(args[4]);
data = new SharedData();
Producers = new Thread[ProducerNumber];
Consumers = new Thread[ConsumerNumber];
for(int i=0;i<ProducerNumber;i++){
Producers[i]=new Thread (new Producer(data, i,
interval));
Producers[i].setPriority(producerPriority);
Producers[i].start();
}
for(int i=0;i<ConsumerNumber;i++) {
Consumers[i]=new Thread (new Consumer(data, i,
interval));
Consumers[i].setPriority(consumerPriority);
Consumers[i].start();
}
}
}
Execution of the ProducerConsumerDriver class with the argument list 1 1 5 5 10
produces the following output:
9-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 9
Exercise 1: The Producer–Consumer Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Producer 0: 0
Producer 0: 1
Producer 0: 2
Producer 0: 3
Consumer 0: 3
Consumer 0: 3
Producer 0: 4
Consumer 0: 4
Producer 0: 5
Producer 0: 6
Producer 0: 7
Producer 0: 8
Consumer 0: 8
Consumer 0: 8
The output shows that the Consumer reads duplicate integers. The Producer writes
consecutive integers and only the last integer is retrieved by the Consumer. Because the
SharedData object is unsynchronized, there is no synchronization between the Producer
and the Consumer objects.
You can experiment with different arguments, such as 3 3 5 5 10, and inspect the output
from more than one Producer and Consumer thread. Without synchronization, integer
values are lost and others are read multiple times.
The Producer and Consumer classes contain infinite loops. You must terminate this
program manually in the Eclipse IDE by clicking the Terminate button. The Terminate
button is the red icon in the Console window.
To synchronize the SharedData class:
• Include a boolean flag to control data access and indicate when an integer has
been produced or consumed.
• Use the synchronized keyword to protect code segments that require mutual
exclusion. When methods are synchronized, the locking and waiting is handled by
Java. Only one thread at a time can be executing the method.
• Implement the wait() and notifyAll() methods.
• Synchronized threads call wait() and notifyAll() when they have modified
something so that the waiting thread can recheck the boolean flag. The waiting
thread can wait for a condition to change within a while loop.
while (conditionToProceed != true) {
wait();
.....
}
___ 1. Use the files provided for the Producer, Consumer, and
ProducerConsumerDriver classes.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-5
•
•
•
•
•
Student Exercises for Unit 9
Exercise 1: The Producer–Consumer Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 2. Write a SharedData class that ensures that the shared data is synchronized for
concurrent access by multiple threads.
The Producer, Consumer, and ProducerConsumerDriver classes shown in the
exercise description should remain unchanged but you must modify the
unsynchronized SharedData class.
___ 3. Save and compile the file.
___ 4. Verify your results. For a single Consumer and Producer thread, the output
should look like the following image.
The Terminate icon, which you must click to stop the program, is highlighted
with a circle in the image.
9-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 9
Exercise 1: The Producer–Consumer Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
•
•
•
•
•
10-1
Student Exercises for Unit 10
Exercise 1: Create a Serializable Object
In this exercise you create a class that is serializable and write the object to a text file.
• Throw any necessary IO exceptions.
• Use try-catch blocks to catch exceptions.
___ 1. Create a class named SerialObject.java that belongs to the examples.serial
package and implements the Serializable interface.
___ 2. Add variables to the SerialObject class. Try adding a transient variable, a
primitive, a collection type of object, or any other type of object. For example:
public class SerialObject implements Serializable {
transient int transValue;
int value;
String stringValue;
ArrayList<String> lst;
___ 3. Write a constructor for the SerialObject class that assigns values to the variables
to define their state.
Exercise 2: Serialize an Object
___ 1. Create a class named SerializeDriver.java that belongs to the examples.serial
package.
___ 2. Create an instance of SerialObject object and assign values to all of the variables.
___ 3. Populate any collection type of objects in the SerialObject object.
___ 4. Using FileOutputStream and ObjectOutputStream objects, write the state of a
SerialObject object to a file.
10-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 10
Exercise 3: Deserialize an Object
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Exercise 3: Deserialize an Object
___ 1. Create a class named DeserializeDriver.java that belongs to the examples.serial
package.
___ 2. Create a new instance of SerialObject in the DeserializeDriver class.
___ 3. Include code to read the serialized state of a SerialObject object from a file into
the new instance of SerialObject in your DeserializeDriver class.
– Use the file to which the serialized state was written in Exercise 2.
– Use FileInputStream and ObjectInputStream objects to read the file.
___ 4. Save and compile your code.
___ 5. Verify that the SerialObject variable values that were written to a file in Exercise
2 mirror the values that have been read into the new instance of SerialObject in
the DeserializeDriver class.
Exercise 4: Using RMI
In this exercise, you will compile files using rmic (RMI compiler) and test the programs.
Examine the four source files that have been provided to understand how they interact with
each other:
• Hello.java
• HelloRemote.java
• RMIServer.java
• RMIClient.java
An Ant build runs the rmic in Eclipse. Ant is a build tool distributed by the Apache
Software Foundation. A build.xml file supplies the necessary parameters to run the rmic
using the Ant Build option.
___ 1. If it does not exist in your project, create a package called exercises.helloRemote.
Copy the four .java files and the build.xml file into the package directory.
___ 2. Select the build.xml file.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-3
•
•
•
•
•
Student Exercises for Unit 10
Exercise 4: Using RMI
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 3. Right-click the External Tools icon.
___ 4. Select External Tools Configuration.
___ 5. Create a new launch configuration for the build.xml file.
___ 6. Select Browse Workspace for the Base Directory option. Select the project
folder.
10-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 10
Exercise 4: Using RMI
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 7. Click the JRE tab to verify that the correct Java SDK is available for use.
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-5
•
•
•
•
•
Student Exercises for Unit 10
Exercise 4: Using RMI
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
___ 8. Click Apply and Run.
___ 9. Verify that the class files were built, including the stub class file.
___ 10. Start the server and the client. If the default port number (1099) is in use, supply
another port number as a program argument.
___ 11. Verify the output.
10-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Student Exercises for Unit 10
Exercise 4: Using RMI
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
•
•
•
•
•
A-1
Appendix A: Exercise Solutions
Unit 1 Exercise Solutions
No solutions are provided.
Unit 2 Exercise Solutions
//
// Solution for HelloWorld Exercise
//
package exercises.hello;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.print("Hello World!n");
System.out.println("I am here!");
}
}
Unit 3 Exercise Solutions
Exercise 1
package exercises.calc;
public class Average {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No arguments to compute average");
return;
}
A-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 3 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
double total = 0;
double value = 0;
/* for(String v: args) {
value = Double.parseDouble(v);
total += value;
System.out.println("Added " + value + " to the total");
}
System.out.println("The sum of the arguments equals = "
+ total);
double average = total/args.length;
System.out.println("Calculated average is: " + average);
*/
for (int i=0; i<args.length; ++i) {
value = Double.parseDouble(args[i]);
total += value;
System.out.println("Added " + value + " to the total");
}
System.out.println("The sum of the arguments equals = "
+ total);
double average = total/args.length;
System.out.println("Calculated average is: " + average);
}
}
Exercise 2
package exercises.calc;
public class MaxOrMin {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: max|min number number");
return;
}
System.out.print("Program arguments: ");
for (String v:args)
System.out.print(v + " ");
System.out.println();
double value1 = Double.parseDouble(args[1]);
double value2 = Double.parseDouble(args[2]);
if (value1==value2) {
System.out.println("The values are equal.");
}
else if (args[0].equalsIgnoreCase("max")) {
System.out.println("The maximum value is: " +
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-3
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 3 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Math.max(value1,value2));
}
else if (args[0].equalsIgnoreCase("min")) {
System.out.println("The minimum value is: " +
Math.min(value1,value2));
}
else
System.out.println("Invalid argument");
}
}
Exercise 3
// Solution for WestToEast Exercise
package exercises.time;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
public class WestToEast {
public static void main(String[] args) {
// Base GMT offset: -8:00
SimpleTimeZone zone1 = new SimpleTimeZone(-8 * 60 * 60 * 1000,
"America/Los_Angeles");
// Base GMT offset: -5:00
SimpleTimeZone zone2 = new SimpleTimeZone(-5 * 60 * 60 * 1000,
"America/New_York");
// Define time period for daylight savings time
zone1.setStartRule(Calendar.MARCH, 1, Calendar.SUNDAY,
2 * 60 * 60 * 1000);
zone1.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY,
2 * 60 * 60 * 1000);
zone2.setStartRule(Calendar.MARCH, 1, Calendar.SUNDAY,
2 * 60 * 60 * 1000);
zone2.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY,
2 * 60 * 60 * 1000);
// Create two GregorianCalendar objects with the East and West
// Coast time zone and the current date and time
Calendar calendar1 = new GregorianCalendar(zone1);
Calendar calendar2 = new GregorianCalendar(zone2);
Date time = new Date(); // Get current Date/Time
calendar1.setTime(time); // convert current date/time to West
// Coast time zone
A-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 4 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
calendar2.setTime(time); // convert current date/time to East
// Coast time zone
// System.out.println("West Coast time: "
+ calendar1.get(Calendar.HOUR)
+ ":" + calendar1.get(Calendar.MINUTE));
// System.out.println("East Coast time: "
+ calendar2.get(Calendar.HOUR)
+ ":" + calendar2.get(Calendar.MINUTE));
int zone1TimeMinutes = (calendar1.get(Calendar.HOUR) * 60) +
calendar1.get(Calendar.MINUTE);
int zone2TimeMinutes = zone1TimeMinutes
- calendar1.get(Calendar.ZONE_OFFSET)/(60*1000)
+ calendar2.get(Calendar.ZONE_OFFSET)/(60*1000);
int zone2Hours = zone2TimeMinutes/60;
int zone2Mins = zone2TimeMinutes - (zone2Hours*60);
System.out.println("Calculated East Coast time: "
+ zone2Hours+ " hours and " + zone2Mins + " minutes");
}
}
Unit 4 Exercise Solutions
// Solution for ModAdd Exercise
package exercises.odd;
public class ModAdd
{
public static void main(String[] args) {
// two parameters are required
if(args.length < 2) {
System.out.println("Error: Requires two integer parameters");
return;
}
// get arguments
int from = Integer.parseInt(args[0]);
int to = Integer.parseInt(args[1]);
// check arguments
if(from >= to) {
System.out.println("Error: 1st argument must be less than 2nd");
return;
}
System.out.println("nUsing for loop:");
int sum = 0;
// for loop
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-5
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 5 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
// iterate for all numbers "from" - "to"
for(int i = from; i <= to; i++) {
// check if number is multiple of 3 and not even
if(i%3 == 0 && i%2 != 0) {
sum = sum + i;
}
}
System.out.println("Sum of odd numbers that are multiples of 3 from "
+ from + " to " + to + " is " + sum);
System.out.println("nUsing while loop:");
sum = 0; //reinitialize total
int i = from; // loop for all number "from" - "to"
while( i <= to) {
// check if number is multiple of 3 and not even
if(i%3 == 0 && i%2 != 0)
sum = sum + i;
i++;
}
System.out.println("Sum of odd numbers that are multiples of 3 from "
+ from + " to " + to + " is " + sum);
}
}
Unit 5 Exercise Solutions
Exercise 1
package examples.str;
public class ReverseArgs {
public static void main(String args[]){
if(args.length < 2) {
System.out.println("Usage: Requires at least two arguments");
return;
}
StringBuilder strArguments = new StringBuilder();
// Use either traditional for loop or the enhanced foreach
for ( String v : args) {
strArguments.append(v + " ");
}
A-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 5 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
reverseArguments(strArguments);
System.out.println ("Reversed letter by letter= " + strArguments);
// return strArguments to its original state
reverseArguments(strArguments);
System.out.println ("Original argument list = " + strArguments);
reverseWords(strArguments);
System.out.println ("Reversed word by word = " + strArguments);
}
public static StringBuilder reverseArguments(StringBuilder s) {
s = s.reverse();
return s;
}
public static StringBuilder reverseWords(StringBuilder s) {
String str = s.toString();
String[] words = str.split (" ");
s.delete(0, s.length());
for (int i=words.length; i > 0; )
s.append(words[--i] + " ");
return s;
}
}
Exercise 2
// Solution for Calculator Exercise
package exercises.calc;
public class Calculator
{
public void add(double o1, double o2) {
double result = o1 + o2;
System.out.println(o1 + " + " + o2 + " = " + result);
}
public void sub(double o1, double o2) {
double result = o1 - o2;
System.out.println(o1 + " - " + o2 + " = " + result);
}
public void mult(double o1, double o2) {
double result = o1 * o2;
System.out.println(o1 + " * " + o2 + " = " + result);
}
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-7
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 5 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
public void div(double o1, double o2) {
double result = o1 / o2;
System.out.println(o1 + " / " + o2 + " = " + result);
}
public static void main(String[] args) {
if(args.length < 3) {
System.out.println("Usage: add/sub/mult/div op1 op2");
return;
}
// get operation and change to uppercase
String operation = args[0].toUpperCase();
// get operands
double op1 = Double.parseDouble(args[1]);
double op2 = Double.parseDouble(args[2]);
// create instance of Calculator
Calculator calc = new Calculator();
// check for the uppercase operation
// and execute the appropriate method
if(operation.startsWith("ADD")) {
calc.add(op1,op2);
}
else if (operation.startsWith("SUB")) {
calc.sub(op1,op2);
}
else if (operation.startsWith("MULT")) {
calc.mult(op1,op2);
}
else if (operation.startsWith("DIV")) {
calc.div(op1,op2);
}
else {
System.out.println("Error: Invalid operation: "
+ operation + " It must be add/sub/mult/div");
}
}
}
Exercise 3
// Solution for Util Exercise
public class Util
{
public static double add(double o1, double o2) {
double result = o1 + o2;
return result;
A-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 5 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
}
public static int add(int o1, int o2) {
int result = o1 + o2;
return result;
}
public static double sub(double o1, double o2) {
double result = o1 - o2;
return result;
}
public static int sub(int o1, int o2) {
int result = o1 - o2;
return result;
}
public static double mult(double o1, double o2) {
double result = o1 * o2;
return result;
}
public static int mult(int o1, int o2) {
int result = o1 * o2;
return result;
}
public static double div(double o1, double o2) {
double result = o1 / o2;
return result;
}
public static int div(int o1, int o2) {
int result = o1 / o2;
return result;
}
}
Exercise 4
// Solution for Perform Exercise
package exercises.calc;
import exercises.util.*;
public class Perform
{
public static void main(String[] args) {
if(args.length < 3) {
System.out.println("Usage: add/sub/mult/div op1 op2");
return;
}
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-9
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 5 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
// Get the operation and convert to uppercase
String operation = args[0].toUpperCase();
// get operands
double op1 = 0;
double op2 = 0;
int i1 = 0;
int i2 = 0;
boolean isDouble = false;
if(args[1].indexOf(".") != -1 || args[2].indexOf(".") != -1) {
try {
op1 = Double.parseDouble(args[1]);
op2 = Double.parseDouble(args[2]);
isDouble = true;
}
catch (NumberFormatException e) {
e.printStackTrace();
}
}
else {
i1 = Integer.parseInt(args[1]);
i2 = Integer.parseInt(args[2]);
}
double answer = 0;
// check operation and execute the proper one
if(operation.startsWith("ADD")) {
if(isDouble)
answer = Util.add(op1,op2);
else
answer = Util.add(i1,i2);
}
else if (operation.startsWith("SUB")) {
if(isDouble)
answer = Util.sub(op1,op2);
else
answer = Util.sub(i1,i2);
}
else if (operation.startsWith("MULT")) {
if(isDouble)
answer = Util.mult(op1,op2);
else
answer = Util.mult(i1,i2);
}
else if (operation.startsWith("DIV")) {
if(isDouble)
answer = Util.div(op1,op2);
else
answer = Util.div(i1,i2);
}
else {
System.out.println("Error: Invalid operation: "
+ operation + " It must be add/sub/mult/div");
return;
}
A-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 6 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
System.out.println(operation
+ " " + args[1]
+ " " + args[2] + " = " + answer);
}
}
Unit 6 Exercise Solutions
Exercise 1
package exercises.calc;
import exercises.util.*;
public class Do {
public static void main(String[] args) throws Exception {
if(args.length < 3) {
System.out.println("Usage: add/sub/mult/div op1 op2");
throw new Exception("Too few parameters.");
}
// Get the operation and convert to uppercase
String operation = args[0].toUpperCase();
// get operands
double op1 = 0;
double op2 = 0;
int i1 = 0;
int i2 = 0;
boolean isDouble = false;
if(args[1].indexOf(".") != -1 || args[2].indexOf(".") != -1) {
try {
op1 = Double.parseDouble(args[1]);
op2 = Double.parseDouble(args[2]);
isDouble = true;
}
catch (NumberFormatException e) {
e.printStackTrace();
throw new Exception("Parameters " + args[1] + " and "
+ args[2] + " must be numeric");
}
}
else {
i1 = Integer.parseInt(args[1]);
i2 = Integer.parseInt(args[2]);
}
double answer = 0;
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-11
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 6 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
// check operation and execute the proper one
if(operation.startsWith("ADD")) {
if(isDouble)
answer = Util.add(op1,op2);
else
answer = Util.add(i1,i2);
}
else if (operation.startsWith("SUB")) {
if(isDouble)
answer = Util.sub(op1,op2);
else
answer = Util.sub(i1,i2);
}
else if (operation.startsWith("MULT")) {
if(isDouble)
answer = Util.mult(op1,op2);
else
answer = Util.mult(i1,i2);
}
else if (operation.startsWith("DIV")) {
if(isDouble)
answer = Util.div(op1,op2);
else
answer = Util.div(i1,i2);
}
else {
System.out.println("Error: Invalid operation: " +
operation + ". It must be add/sub/mult/div");
throw new Exception("Invalid operation: " + operation);
}
System.out.println(operation
+ " " + args[1]
+ " " + args[2] + " = " + answer);
}
}
Exercise 2
package exercises.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Palindromes {
A-12 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 6 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
public static void main(String[] args) throws IOException {
if (args.length != 3) {
System.out.println("Usage: Must have 3 parameters");
System.exit(1);
}
File inFile = new File(args[0]);
File outFile1 = new File(args[1]);
File outFile2 = new File(args[2]);
boolean exists = inFile.exists();
if (!exists) {
System.out.println("File " + inFile.getName() + "does not exists");
System.exit(1);
}
try {
filter4Palindromes(inFile, outFile1);
scan4Palindromes(inFile, outFile2);
} catch (IOException e) {
System.out.println(e);
System.exit(1);
}
}
public static void filter4Palindromes(File in, File out)
throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(in));
BufferedWriter writer = new BufferedWriter(new FileWriter(out));
String originalLine = null;
String reversedLine = null;
String trimmedLine = null;
while ((originalLine=reader.readLine()) != null) {
trimmedLine = originalLine.replaceAll(" ", "");
StringBuilder sbLine = new StringBuilder(trimmedLine);
reversedLine = sbLine.reverse().toString();
if (reversedLine.compareToIgnoreCase(trimmedLine) == 0 ) {
writer.write(originalLine);
writer.newLine(); // System dependent newline
}
}
reader.close(); // Close reader to unlock
writer.close(); // Close writer to unlock and flush
}
public static void scan4Palindromes(File in, File out)
throws IOException {
Scanner freader = new Scanner(in); // uses Scanner
BufferedWriter writer = new BufferedWriter(new FileWriter(out));
String originalLine = null;
String reversedLine = null;
String trimmedLine = null;
while (freader.hasNextLine()) {
originalLine = freader.nextLine();
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-13
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 7 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
trimmedLine = originalLine.replaceAll(" ", "");
StringBuilder sbLine = new StringBuilder(trimmedLine);
reversedLine = sbLine.reverse().toString();
if (reversedLine.compareToIgnoreCase(trimmedLine) == 0 ) {
writer.write(originalLine);
writer.newLine();
}
}
freader.close();
writer.close();
}
}
Unit 7 Exercise Solutions
Exercise 1
The following five files form the solution for Exercise 1:
package exercises.HowRU;
public interface HowAreYou {
public void sayHowAreYou();
}
package exercises.HowRU;
public class EnglishHowAreYou implements HowAreYou {
public void sayHowAreYou() {
System.out.println("How are you?");
}
}
package exercises.HowRU;
public class FrenchHowAreYou implements HowAreYou {
public void sayHowAreYou() {
System.out.println("Ca va?");
}
}
A-14 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 7 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
package exercises.HowRU;
public class ItalianHowAreYou implements HowAreYou {
public void sayHowAreYou() {
System.out.println("Come stai?");
}
}
package exercises.HowRU;
public class SayHowAreYou {
public HowAreYou howAreYou;
public void setLanguage(HowAreYou howAreYou) {
this.howAreYou = howAreYou;
}
public void sayHowAreYou() {
this.howAreYou.sayHowAreYou();
}
public static void main(String[] args) {
SayHowAreYou howru = new SayHowAreYou();
howru.setLanguage(new EnglishHowAreYou());
howru.sayHowAreYou();
howru.setLanguage(new ItalianHowAreYou());
howru.sayHowAreYou();
howru.setLanguage(new FrenchHowAreYou());
howru.sayHowAreYou();
}
}
Exercise 2
The following fifteen files form a possible solution for Exercise 2:
package exercises.music;
public interface Instrument {
public void play();
public void tune();
public void mute();
}
package exercises.music;
public abstract class BowType implements Instrument {
private String name;
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-15
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 7 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
protected BowType(String instrumentName) {
System.out.println("Entering BowType constructor");
name = new String(instrumentName);
System.out.println("Exiting BowType constructor");
}
protected String getName() {
return name;
}
public void mute() {
System.out.println("mute():abstract class BowType for " + getName() );
}
public void play() {
System.out.println("play():abstract class BowType for " + getName());
}
public void tune() {
System.out.println("tune():abstract class BowType for " + getName());
}
}
package exercises.music;
public abstract class PluckType implements Instrument {
private String name;
protected String getName() {
return name;
}
protected PluckType(String instrumentName) {
System.out.println("Entering BowType constructor");
name = new String(instrumentName);
System.out.println("Exiting BowType constructor");
}
public void mute() {
System.out.println("mute():abstract class PluckType" + getName());
}
public void play() {
System.out.println("play():abstract class PluckType" + getName());
}
public void tune() {
System.out.println("tune():abstract class PluckType" + getName());
}
}
A-16 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 7 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
package exercises.music;
public abstract class StrikeType implements Instrument {
private String name;
protected StrikeType(String instrumentName) {
System.out.println("Entering StrikeType constructor");
name = new String(instrumentName);
System.out.println("Exiting StrikeType constructor");
}
protected String getName() {
return name;
}
public void mute() {
System.out.println("mute():abstract class StrikeType" + getName());
}
public void play() {
System.out.println("play():abstract class StrikeType" + getName());
}
public void tune() {
System.out.println("tune():abstract class StrikeType" + getName());
}
}
package exercises.music;
public abstract class WindType implements Instrument {
private String name;
protected WindType(String instrumentName) {
System.out.println("Entering WindType constructor");
name = new String(instrumentName);
System.out.println("Exiting WindType constructor");
}
protected String getName() {
return name;
}
public void mute() {
System.out.println("mute():abstract class WindType" + getName());
}
public void play() {
System.out.println("play():abstract class WindType" + getName());
}
public void tune() {
System.out.println("tune():abstract class WindType" + getName());
}
}
©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-17
•
•
•
•
•
Appendix A: Exercise Solutions
Unit 7 Exercise Solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
package exercises.music;
public class Bass extends PluckType {
public Bass() {
super("Bass");
System.out.println("Exiting Bass constructor");
}
public String getName(){
System.out.println ("The Bass class inherits its name: "
+ super.getName() + " from its base class");
return super.getName();
}
}
package exercises.music;
public class Cello extends BowType {
public Cello() {
super("Cello");
System.out.println("Exiting Cello constructor");
}
public String getName(){
System.out.println ("The Cello class inherits its name: "
+ super.getName() + " from its base class");
return super.getName();
}
}
package exercises.music;
public class Drums extends StrikeType {
public Drums() {
super("Drums");
System.out.println("Exiting Drums constructor");
}
public String getName(){
System.out.println ("The Drums class inherits its name: "
+ super.getName() + " from its base class");
return super.getName();
}
}
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises
Java Customization Student Exercises

Weitere ähnliche Inhalte

Was ist angesagt?

Tems optimization and-log-file-analysis-in-gsm (1)
Tems optimization and-log-file-analysis-in-gsm (1)Tems optimization and-log-file-analysis-in-gsm (1)
Tems optimization and-log-file-analysis-in-gsm (1)mysritech
 
Faronics Power Save Enterprise User Guide
Faronics Power Save Enterprise User GuideFaronics Power Save Enterprise User Guide
Faronics Power Save Enterprise User GuideFaronics
 
Ecdl l2 project2013_sample
Ecdl l2 project2013_sampleEcdl l2 project2013_sample
Ecdl l2 project2013_sampleQassim Ahmed
 
Deployment guide series ibm tivoli composite application manager for web reso...
Deployment guide series ibm tivoli composite application manager for web reso...Deployment guide series ibm tivoli composite application manager for web reso...
Deployment guide series ibm tivoli composite application manager for web reso...Banking at Ho Chi Minh city
 
Group Exercise Instructor Certification Manual
Group Exercise Instructor Certification ManualGroup Exercise Instructor Certification Manual
Group Exercise Instructor Certification ManualJimmyGFlores
 
Complete guide-to-toeic-test---answer keys
Complete guide-to-toeic-test---answer keysComplete guide-to-toeic-test---answer keys
Complete guide-to-toeic-test---answer keysThangPham178
 
Aspnet.grid view
Aspnet.grid viewAspnet.grid view
Aspnet.grid viewibrahimkhan
 
Q T P Tutorial
Q T P  TutorialQ T P  Tutorial
Q T P Tutorialrosereddy
 
Nvidia CUDA Programming Guide 1.0
Nvidia CUDA Programming Guide 1.0Nvidia CUDA Programming Guide 1.0
Nvidia CUDA Programming Guide 1.0Muhaza Liebenlito
 
ImplementationOFDMFPGA
ImplementationOFDMFPGAImplementationOFDMFPGA
ImplementationOFDMFPGANikita Pinto
 
The road-to-learn-react
The road-to-learn-reactThe road-to-learn-react
The road-to-learn-reactimdurgesh
 
TargetSolutions - Course Descriptions Guide
TargetSolutions - Course Descriptions GuideTargetSolutions - Course Descriptions Guide
TargetSolutions - Course Descriptions Guiderichmiron
 
Pmp exam prepboothp
Pmp exam prepboothpPmp exam prepboothp
Pmp exam prepboothplookwah
 

Was ist angesagt? (19)

Tems optimization and-log-file-analysis-in-gsm (1)
Tems optimization and-log-file-analysis-in-gsm (1)Tems optimization and-log-file-analysis-in-gsm (1)
Tems optimization and-log-file-analysis-in-gsm (1)
 
Faronics Power Save Enterprise User Guide
Faronics Power Save Enterprise User GuideFaronics Power Save Enterprise User Guide
Faronics Power Save Enterprise User Guide
 
Final report
Final reportFinal report
Final report
 
Ecdl l2 project2013_sample
Ecdl l2 project2013_sampleEcdl l2 project2013_sample
Ecdl l2 project2013_sample
 
Deployment guide series ibm tivoli composite application manager for web reso...
Deployment guide series ibm tivoli composite application manager for web reso...Deployment guide series ibm tivoli composite application manager for web reso...
Deployment guide series ibm tivoli composite application manager for web reso...
 
Group Exercise Instructor Certification Manual
Group Exercise Instructor Certification ManualGroup Exercise Instructor Certification Manual
Group Exercise Instructor Certification Manual
 
Java
JavaJava
Java
 
Complete guide-to-toeic-test---answer keys
Complete guide-to-toeic-test---answer keysComplete guide-to-toeic-test---answer keys
Complete guide-to-toeic-test---answer keys
 
Fraser_William
Fraser_WilliamFraser_William
Fraser_William
 
Aspnet.grid view
Aspnet.grid viewAspnet.grid view
Aspnet.grid view
 
Q T P Tutorial
Q T P  TutorialQ T P  Tutorial
Q T P Tutorial
 
Nvidia CUDA Programming Guide 1.0
Nvidia CUDA Programming Guide 1.0Nvidia CUDA Programming Guide 1.0
Nvidia CUDA Programming Guide 1.0
 
Ax50 enus wn_app
Ax50 enus wn_appAx50 enus wn_app
Ax50 enus wn_app
 
ImplementationOFDMFPGA
ImplementationOFDMFPGAImplementationOFDMFPGA
ImplementationOFDMFPGA
 
The road-to-learn-react
The road-to-learn-reactThe road-to-learn-react
The road-to-learn-react
 
TargetSolutions - Course Descriptions Guide
TargetSolutions - Course Descriptions GuideTargetSolutions - Course Descriptions Guide
TargetSolutions - Course Descriptions Guide
 
Pmp exam prepboothp
Pmp exam prepboothpPmp exam prepboothp
Pmp exam prepboothp
 
Gdb
GdbGdb
Gdb
 
Report-V1.5_with_comments
Report-V1.5_with_commentsReport-V1.5_with_comments
Report-V1.5_with_comments
 

Ähnlich wie Java Customization Student Exercises

Student Manual _ ABT-CCP-143-TSM _ RSLogix 5000, Level 3 _ Project Development
Student Manual _ ABT-CCP-143-TSM _ RSLogix 5000, Level 3 _ Project DevelopmentStudent Manual _ ABT-CCP-143-TSM _ RSLogix 5000, Level 3 _ Project Development
Student Manual _ ABT-CCP-143-TSM _ RSLogix 5000, Level 3 _ Project DevelopmentMarco Enrique Ramos Castillo
 
S4 h 301 testyourprocesses_userguide
S4 h 301 testyourprocesses_userguideS4 h 301 testyourprocesses_userguide
S4 h 301 testyourprocesses_userguideLokesh Modem
 
Ibm tivoli workload scheduler for z os best practices end-to-end and mainfram...
Ibm tivoli workload scheduler for z os best practices end-to-end and mainfram...Ibm tivoli workload scheduler for z os best practices end-to-end and mainfram...
Ibm tivoli workload scheduler for z os best practices end-to-end and mainfram...Banking at Ho Chi Minh city
 
Aix student guide system administrations part 2 problem determination
Aix student guide system administrations part 2   problem determinationAix student guide system administrations part 2   problem determination
Aix student guide system administrations part 2 problem determinationYogesh Sharma
 
IEC programing manual
IEC programing manualIEC programing manual
IEC programing manualquanglocbp
 
Staad.pro2007 full course
Staad.pro2007 full courseStaad.pro2007 full course
Staad.pro2007 full courseRamil Artates
 
Visual basic2010bookletfinal
Visual basic2010bookletfinalVisual basic2010bookletfinal
Visual basic2010bookletfinalPaul Bolton
 
The Readiness Plan A Spotlight on Customer Success
The Readiness Plan A Spotlight on Customer SuccessThe Readiness Plan A Spotlight on Customer Success
The Readiness Plan A Spotlight on Customer SuccessDav Hol
 
Sg247692 Websphere Accounting Chargeback For Tuam Guide
Sg247692 Websphere Accounting Chargeback For Tuam GuideSg247692 Websphere Accounting Chargeback For Tuam Guide
Sg247692 Websphere Accounting Chargeback For Tuam Guidebrzaaap
 
Epf installation tutorial_user_manual
Epf installation tutorial_user_manualEpf installation tutorial_user_manual
Epf installation tutorial_user_manualsunskippy
 
Managing disk subsystems using ibm total storage productivity center sg247097
Managing disk subsystems using ibm total storage productivity center sg247097Managing disk subsystems using ibm total storage productivity center sg247097
Managing disk subsystems using ibm total storage productivity center sg247097Banking at Ho Chi Minh city
 
IMO Model Course 7.02 Edition 2014
IMO Model Course 7.02 Edition 2014IMO Model Course 7.02 Edition 2014
IMO Model Course 7.02 Edition 2014Chairil Anam
 
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...Banking at Ho Chi Minh city
 
Lab view basics_i[1]
Lab view basics_i[1]Lab view basics_i[1]
Lab view basics_i[1]quanghaixp
 
FATKID - A Finite Automata Toolkit - NF Huysamen
FATKID - A Finite Automata Toolkit - NF HuysamenFATKID - A Finite Automata Toolkit - NF Huysamen
FATKID - A Finite Automata Toolkit - NF HuysamenNico Huysamen
 
Guia de usuario arena
Guia de usuario arenaGuia de usuario arena
Guia de usuario arenaSadamii Rap
 
Certification guide series ibm tivoli netcool impact v4.0 implementation sg24...
Certification guide series ibm tivoli netcool impact v4.0 implementation sg24...Certification guide series ibm tivoli netcool impact v4.0 implementation sg24...
Certification guide series ibm tivoli netcool impact v4.0 implementation sg24...Banking at Ho Chi Minh city
 
AUTOMOTIVE ENGINE MAINTENANCE AND REPAIR
AUTOMOTIVE ENGINE MAINTENANCE AND REPAIRAUTOMOTIVE ENGINE MAINTENANCE AND REPAIR
AUTOMOTIVE ENGINE MAINTENANCE AND REPAIRAsia Smith
 
Open edX Building and Running a Course
Open edX Building and Running a CourseOpen edX Building and Running a Course
Open edX Building and Running a CourseAmish Gandhi
 

Ähnlich wie Java Customization Student Exercises (20)

Student Manual _ ABT-CCP-143-TSM _ RSLogix 5000, Level 3 _ Project Development
Student Manual _ ABT-CCP-143-TSM _ RSLogix 5000, Level 3 _ Project DevelopmentStudent Manual _ ABT-CCP-143-TSM _ RSLogix 5000, Level 3 _ Project Development
Student Manual _ ABT-CCP-143-TSM _ RSLogix 5000, Level 3 _ Project Development
 
S4 h 301 testyourprocesses_userguide
S4 h 301 testyourprocesses_userguideS4 h 301 testyourprocesses_userguide
S4 h 301 testyourprocesses_userguide
 
Ibm tivoli workload scheduler for z os best practices end-to-end and mainfram...
Ibm tivoli workload scheduler for z os best practices end-to-end and mainfram...Ibm tivoli workload scheduler for z os best practices end-to-end and mainfram...
Ibm tivoli workload scheduler for z os best practices end-to-end and mainfram...
 
Aix student guide system administrations part 2 problem determination
Aix student guide system administrations part 2   problem determinationAix student guide system administrations part 2   problem determination
Aix student guide system administrations part 2 problem determination
 
Introduction to BIRT
Introduction to BIRTIntroduction to BIRT
Introduction to BIRT
 
IEC programing manual
IEC programing manualIEC programing manual
IEC programing manual
 
Staad.pro2007 full course
Staad.pro2007 full courseStaad.pro2007 full course
Staad.pro2007 full course
 
Visual basic2010bookletfinal
Visual basic2010bookletfinalVisual basic2010bookletfinal
Visual basic2010bookletfinal
 
The Readiness Plan A Spotlight on Customer Success
The Readiness Plan A Spotlight on Customer SuccessThe Readiness Plan A Spotlight on Customer Success
The Readiness Plan A Spotlight on Customer Success
 
Sg247692 Websphere Accounting Chargeback For Tuam Guide
Sg247692 Websphere Accounting Chargeback For Tuam GuideSg247692 Websphere Accounting Chargeback For Tuam Guide
Sg247692 Websphere Accounting Chargeback For Tuam Guide
 
Epf installation tutorial_user_manual
Epf installation tutorial_user_manualEpf installation tutorial_user_manual
Epf installation tutorial_user_manual
 
Managing disk subsystems using ibm total storage productivity center sg247097
Managing disk subsystems using ibm total storage productivity center sg247097Managing disk subsystems using ibm total storage productivity center sg247097
Managing disk subsystems using ibm total storage productivity center sg247097
 
IMO Model Course 7.02 Edition 2014
IMO Model Course 7.02 Edition 2014IMO Model Course 7.02 Edition 2014
IMO Model Course 7.02 Edition 2014
 
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
 
Lab view basics_i[1]
Lab view basics_i[1]Lab view basics_i[1]
Lab view basics_i[1]
 
FATKID - A Finite Automata Toolkit - NF Huysamen
FATKID - A Finite Automata Toolkit - NF HuysamenFATKID - A Finite Automata Toolkit - NF Huysamen
FATKID - A Finite Automata Toolkit - NF Huysamen
 
Guia de usuario arena
Guia de usuario arenaGuia de usuario arena
Guia de usuario arena
 
Certification guide series ibm tivoli netcool impact v4.0 implementation sg24...
Certification guide series ibm tivoli netcool impact v4.0 implementation sg24...Certification guide series ibm tivoli netcool impact v4.0 implementation sg24...
Certification guide series ibm tivoli netcool impact v4.0 implementation sg24...
 
AUTOMOTIVE ENGINE MAINTENANCE AND REPAIR
AUTOMOTIVE ENGINE MAINTENANCE AND REPAIRAUTOMOTIVE ENGINE MAINTENANCE AND REPAIR
AUTOMOTIVE ENGINE MAINTENANCE AND REPAIR
 
Open edX Building and Running a Course
Open edX Building and Running a CourseOpen edX Building and Running a Course
Open edX Building and Running a Course
 

Kürzlich hochgeladen

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 

Kürzlich hochgeladen (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 

Java Customization Student Exercises

  • 1. IBM Enterprise IT and Asset Management 7.1: Java for Customization Student Exercises S150-3086-00 May 2009
  • 2. Copyright Notice Copyright © 2009 IBM Corporation, including this documentation and all software. All rights reserved. May only be used pursuant to a Tivoli Systems Software License Agreement, an IBM Soft- ware License Agreement, or Addendum for Tivoli Products to IBM Customer or License Agreement. No part of this publication may be reproduced, transmitted, transcribed, stored in a retrieval system, or translated into any computer language, in any form or by any means, electronic, mechanical, magnetic, optical, chemical, manual, or otherwise, without prior written permission of IBM Corpora- tion. IBM Corporation grants you limited permission to make hardcopy or other reproductions of any machine-readable documentation for your own use, provided that each such reproduction shall carry the IBM Corporation copyright notice. No other rights under copyright are granted without prior writ- ten permission of IBM Corporation. The document is not intended for production and is furnished “as is” without warranty of any kind. All warranties on this document are hereby disclaimed, including the warranties of merchantability and fitness for a particular purpose. Note to U.S. Government Users—Documentation related to restricted rights—Use, duplication or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corporation. Trademarks The following are trademarks of IBM Corporation or Tivoli Systems Inc.: IBM, Tivoli, AIX, Cross-Site, NetView, OS/2, Planet Tivoli, RS/6000, Tivoli Certified, Tivoli Enterprise, Tivoli Ready, TME. In Den- mark, Tivoli is a trademark licensed from Kjøbenhavns Sommer - Tivoli A/S. Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both. UNIX is a registered trademark of The Open Group in the United States and other countries. C-bus is a trademark of Corollary, Inc. in the United States, other countries, or both. Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Lotus is a registered trademark of Lotus Development Corporation. PC Direct is a trademark of Ziff Communications Company in the United States, other countries, or both and is used by IBM Corporation under license. ActionMedia, LANDesk, MMX, Pentium, and ProShare are trademarks of Intel Corporation in the United States, other countries, or both. SET and the SET Logo are trademarks owned by SET Secure Electronic Transaction LLC. For fur- ther information, see http://www.setco.org/aboutmark.html. Other company, product, and service names may be trademarks or service marks of others. Notices References in this publication to Tivoli Systems or IBM products, programs, or services do not imply that they will be available in all countries in which Tivoli Systems or IBM operates. Any reference to these products, programs, or services is not intended to imply that only Tivoli Systems or IBM prod- ucts, programs, or services can be used. Subject to valid intellectual property or other legally pro- tectable right of Tivoli Systems or IBM, any functionally equivalent product, program, or service can be used instead of the referenced product, program, or service. The evaluation and verification of operation in conjunction with other products, except those expressly designated by Tivoli Systems or IBM, are the responsibility of the user. Tivoli Systems or IBM may have patents or pending patent applications covering subject matter in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to the IBM Director of Licensing, IBM Corporation, North Castle Drive, Armonk, New York 10504-1785, U.S.A. Printed in Ireland.
  • 3. • • • • • I Table of Contents Student Exercises for Unit 1 No student exercises are provided for this unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1 Student Exercises for Unit 2 Exercise 1: Create a Java Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1 Exercise 2: Create the HelloWorld Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3 Exercise 3: Eclipse Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 Exercise 4: Write the HelloWorld class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 Exercise 5: Build the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 Exercise 6: Run the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 Student Exercises for Unit 3 Exercise 1: Calculate an Average . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1 Exercise 2: Determine a Maximum or Minimum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3 Exercise 3: Create the WestToEast Class (Optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5 Exercise 4: Debug the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7 Student Exercises for Unit 4 Exercise 1: Create the ModAdd Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1 Exercise 2: Debug the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3 Student Exercises for Unit 5 Exercise 1: Create the ReverseArgs Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1 Exercise 2: Create the Calculator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 Exercise 3: Create the Util Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4 Exercise 4: Create the Perform Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5 Student Exercises for Unit 6 Exercise 1: Implement Exception Handing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1 Exercise 2: Read and Write to Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1 Student Exercises for Unit 7 Exercise 1: Using an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1 Exercise 2: Using an Interface and Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2 Student Exercises for Unit 8 Exercise 1: Determine a Median . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1 Exercise 2: Use a LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1 Exercise 3: Use an ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
  • 4. II IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Table of Contents Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Exercise 4: Create a Deck of Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3 Exercise 5: Create a Hospital . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5 Student Exercises for Unit 9 Exercise 1: The Producer–Consumer Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-1 Student Exercises for Unit 10 Exercise 1: Create a Serializable Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-1 Exercise 2: Serialize an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-1 Exercise 3: Deserialize an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2 Exercise 4: Using RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2 Appendix A: Exercise Solutions Unit 1 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1 No solutions are provided. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1 Unit 2 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1 Unit 3 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1 Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1 Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2 Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-3 Unit 4 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4 Unit 5 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5 Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5 Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6 Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-7 Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-8 Unit 6 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-10 Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-10 Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-11 Unit 7 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-13 Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-13 Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-14 Unit 8 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-21 Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-21 Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-22 Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-23 Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-24 Exercise 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-26 Unit 9 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-34 Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-34 Unit 10 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-36 Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-36 Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-37 Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-38 Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-39
  • 5. • • • • • 1-1 Student Exercises for Unit 1 No student exercises are provided for this unit.
  • 6. 1-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 1 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 7. • • • • • 2-1 Student Exercises for Unit 2 Exercise 1: Create a Java Project In this exercise, you will create a Java project that points to the JavaBasics directory. This root directory will contain your source code. Your compiled code will also remain in this directory. ___ 1. Open the Eclipse IDE, if it is not already open. ___ 2. Select the New option or navigate to File > New in the main menu. ___ 3. Select Project.
  • 8. 2-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 2 Exercise 1: Create a Java Project Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 4. Select Java Project and click Next. ___ 5. In the Project name field, type JavaBasics. ___ 6. Select Create project from existing source. ___ 7. Browse for the directory C:JavaBasics.
  • 9. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-3 • • • • • Student Exercises for Unit 2 Exercise 2: Create the HelloWorld Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 8. Click Finish. ___ 9. The project named JavaBasics is created and can be accessed from the Package Explorer tab. Expand the project. It is set up with the necessary JRE and .jar files. Exercise 2: Create the HelloWorld Class In this exercise you will use the Eclipse IDE to create the HelloWorld class. The HelloWorld class will contain only a main() method with a statement to display the text Hello World! and I am here! to the console. The HelloWorld class will belong to the exercises.hello package. The following examples show two possible outlines for the HelloWorld class.
  • 10. 2-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 2 Exercise 2: Create the HelloWorld Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. package exercises.hello; public class HelloWorld { public static void main(String[] args) { // Display "Hello World! I am here!" to the console } } // The following is an alternative outline: package exercises.hello; public class HelloWorld { public static void main(String[] args) { printHelloWorld(); } public static void printHelloWorld() { // Display "Hello World! I am here!" to the console } } ___ 1. Click the New drop-down menu, and select Class, or File > New > Class from the main menu to access the New Java Class dialog box. ___ 2. Enter exercises.hello in the Package field. ___ 3. Enter HelloWorld in the Name field. ___ 4. Click the public static void main(String[] args) check box to select it. Your screen should look like the following example.
  • 11. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-5 • • • • • Student Exercises for Unit 2 Exercise 2: Create the HelloWorld Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 5. Click Finish. ___ 6. The class file HelloWorld.java is created. The file is listed in the Package Explorer. A skeleton class with main() has been generated and is in the edit window.
  • 12. 2-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 2 Exercise 3: Eclipse Features Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 7. Double-click the HelloWorld.java tab to expand the edit window. Double-click the same tab to toggle back to the package view. Exercise 3: Eclipse Features ___ 1. Eclipse contains context-sensitive help. To demonstrate this feature, try writing a line of code inside the main() method, such as System.out. After typing System.out, press Ctrl+Space for context-sensitive help.
  • 13. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-7 • • • • • Student Exercises for Unit 2 Exercise 4: Write the HelloWorld class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 2. Complete a line of code and omit the semicolon on purpose. Eclipse will detect that a missing semicolon is a syntax error, and that line of code will be flagged with a red error symbol. . ___ 3. Mistype more lines of code to demonstrate some helpful features of Eclipse. Exercise 4: Write the HelloWorld class ___ 1. Write the HelloWorld class according to the outline illustrated in Exercise 2. ___ 2. Use the System.out.println() method to output text to the console. ___ 3. Save the file. Exercise 5: Build the Project ___ 1. Right-click the JavaBasics project and select Build Project. ___ 2. If the Project > Build Automatically option is selected, clear the option. ___ 3. After the project is built, the errors are displayed on the Problems tab. Double- click any error. The cursor is placed on the error line. ___ 4. After you fix the error, rebuild the project.
  • 14. 2-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 2 Exercise 6: Run the Application Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Exercise 6: Run the Application ___ 1. Ensure that there are no compile errors after building the project. ___ 2. To run the application, select the HelloWorld.java file on the Package Explorer tab. The file must have a main() to run. ___ 3. Navigate to Run > Run Configurations from the main menu. ___ 4. In the dialog box, select Java Application from the list. ___ 5. Click the New launch configuration icon to create a HelloWorld configuration. The configuration includes the path to the main class. ___ 6. Click Apply. ___ 7. Click Run. Output is sent to the console. ___ 8. Select the Console tab to view the application output.
  • 15. • • • • • 3-1 Student Exercises for Unit 3 Exercise 1: Calculate an Average In this exercise you will write a class to calculate the average of a variable number of arguments. The average of a set of numeric values is determined by adding all of the values together and dividing the calculated sum by the number of values. For example, the average of 10, 4, 8, 6, 5, 10, and 13 is 8: (10+4+8+6+5+10+13)/7 = 56/7 = 8 The class must include a main() method. Within the body of the main() method, convert each argument to a numeric data type, calculate the average, and output the result. ___ 1. Select File > New > Package to create the exercises.calc package using the Eclipse IDE. ___ 2. Select the exercises.calc package and right-click to access the context menu. ___ 3. Select New > Class from the context menu and create the Average class. Select the option to include a main() method when creating your class. ___ 4. Within the main() method, write the code to calculate an average of the program arguments. – The program arguments are stored in the variable args, which is an array of Strings. – The variable args[0] returns the first argument, args[1] returns the second argument, and so on. – The variable args.length returns an integer value that represents the number of arguments. – Use the static method Double.parseDouble(String s) to convert an argument from a String data type to a numeric value. – The following example shows one possible way to iterate through the arguments: for (String v : args) { System.out.print(v + “ “); } System.out.println();
  • 16. 3-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 3 Exercise 1: Calculate an Average Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 5. Use the System.out.println() method to output the calculated average. ___ 6. Save and compile the Average class. ___ 7. Select the Average file in the Package Explorer. Click Run > Run Configurations from the main menu. ___ 8. Create a new launch configuration. ___ 9. Select the Arguments tab. ___ 10. Type numeric arguments separated by white space to test the class.
  • 17. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-3 • • • • • Student Exercises for Unit 3 Exercise 2: Determine a Maximum or Minimum Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 11. Run the Average class and verify the results. Exercise 2: Determine a Maximum or Minimum In this exercise you will write a class to determine the maximum or minimum of two numeric values. The class should include a main() method. You will provide three arguments. The first argument is max or min. The second and third arguments are numeric values. If the first argument is max, print the greater of the numeric arguments to the console. If the first argument is min, print the lesser of the numeric arguments to the console. ___ 1. Right-click the exercises.calc package. ___ 2. Select New > Class from the context menu and create the MaxOrMin class. Select the option to include a main( ) method when creating your class. ___ 3. Within the main() method, write the code to print either the maximum or minimum of the numeric values given as program arguments. The program arguments are stored in the variable args, which is an array of Strings. The variable args[0] returns the first argument, args[1] returns the second argument, and so on.
  • 18. 3-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 3 Exercise 2: Determine a Maximum or Minimum Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Hint: The following methods are useful for the exercise: – Double.parseDouble(String s) – The equalsIgnoreCase(String s) method from the String class – The static Math.max() and Math.min( ) methods ___ 4. Use the System.out.println() method to output the maximum or minimum value. ___ 5. Save and compile the MaxOrMin class. ___ 6. Select the MaxOrMin file in the Package Explorer. From the main menu, select Run > Run Configurations. ___ 7. Create a new launch configuration. ___ 8. Select the Arguments tab. ___ 9. Type max or min and two numeric arguments separated by white space to test the class.
  • 19. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-5 • • • • • Student Exercises for Unit 3 Exercise 3: Create the WestToEast Class (Optional) Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 10. Run the MaxOrMin class and verify the results. Exercise 3: Create the WestToEast Class (Optional) Coordinated Universal Time (UTC) is a time standard roughly equivalent to Greenwich Mean Time (GMT). Conversion between time zones is such that the following relationship is true and each side of the equation is equivalent to UTC: Time in Zone A − UTC Offset for Zone A = Time in Zone B − UTC Offset for Zone B The equation can be rewritten as: Time in Zone B = Time in Zone A − UTC Offset for Zone A + UTC Offset for Zone B Use the following equation to determine what time it is in Los Angeles (UTC offset = −08) when it is 8:30 a.m. in New York City (UTC offset = -5): Time in Los Angeles = 08:30 − (−05:00) + (−08:00) = 05:30 This exercise demonstrates a class that uses the classes in Java API, and it has enough content for you to try the Eclipse debugging features. An outline for the class WestToEast is partially provided for you. The program imports four Java classes that include data and time functionality. Statements have been provided in the program; you can uncomment them and inspect the output for guidance. If you have previous Java or other object-oriented programming experience, try to complete the exercise without using the solution. Otherwise, the solution is provided in the Appendix.
  • 20. 3-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 3 Exercise 3: Create the WestToEast Class (Optional) Course materials may not be reproduced in whole or in part without the prior written permission of IBM. The following example shows a possible outline for the WestToEast class: package exercises.time; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; public class WestToEast { public static void main(String[] args) { // Base GMT offset: -8:00 SimpleTimeZone zone1 = new SimpleTimeZone(-8 * 60 * 60 * 1000, "America/Los_Angeles"); // Base GMT offset: -5:00 SimpleTimeZone zone2 = new SimpleTimeZone(-5 * 60 * 60 * 1000, "America/New_York"); // Create two GregorianCalendar objects // with the East and West Coast // time zone and the current date and time Calendar calendar1 = new GregorianCalendar(zone1); Calendar calendar2 = new GregorianCalendar(zone2); Date time = new Date(); // Get current Date/Time calendar1.setTime(time); calendar2.setTime(time); // System.out.println("Hour: " // + calendar1.get(Calendar.HOUR)); // System.out.println("Minute: " // + calendar1.get(Calendar.MINUTE)); // insert your code to calculate the East Coast time // using the calendar1.get(Calendar.HOUR) and // calendar1.get(Calendar.MINUTE) values // print out the East Coast value to the console } } ___ 1. Create the WestToEast class in the exercises.time package using the Eclipse IDE. ___ 2. Copy the provided file or the code outline that precedes this exercise. ___ 3. Complete the class following the specifications as outlined. ___ 4. Create variables and use the Calendar.HOUR and Calendar.MINUTE values to calculate the time in New York City, given the time in Los Angeles.
  • 21. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-7 • • • • • Student Exercises for Unit 3 Exercise 4: Debug the Application Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 5. Use the System.out.println() method to output the calculated value. ___ 6. Save and compile the WestToEast class. ___ 7. Select the WestToEast file in the Package Explorer. From the main menu, select Run > Run Configurations. ___ 8. Run the WestToEast application and verify the results. Exercise 4: Debug the Application ___ 1. Select the WestToEast class in the Package Explorer. ___ 2. Select Run > Debug Configurations from the main menu. ___ 3. In the dialog box, the WestToEast class is already displayed in the Java Application list. ___ 4. Return to the Main tab, if necessary. ___ 5. Select the Stop in main option. ___ 6. Click Apply. ___ 7. Click Debug. ___ 8. Click Yes if the Confirm Perspective Switch message box is displayed. ___ 9. Eclipse opens the Debug perspective. Debug icons are available within this perspective, in addition to a Variable tab to inspect variable values and a Breakpoint tab. This debug session has stopped the program at the first statement in main().
  • 22. 3-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 3 Exercise 4: Debug the Application Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Familiarize yourself with the available debug icons on the Debug tab. Commonly used icons are: – Resume: Continue to the next breakpoint. – Step Into: Step into the method that is called. – Step Over: Execute current statement and move to the next statement. – Step Return: Perform remaining statements in method and return to calling method. – Terminate: Halt the execution of the program. ___ 10. Right-click the outer edge of the WestToEast file and select Toggle Breakpoint to set a breakpoint at a line of code in that file. Breakpoints suspend execution of the program. ___ 11. Switch back to the Java perspective by clicking the Java tab (or navigate to Window > Open Perspective > Java). Open the WestToEast file, if it is not already open. ___ 12. Right-click the outer edge of the WestToEast file and select Toggle Breakpoint to set a breakpoint at a line of code in that file. You can set breakpoints in either the Debug or the Java perspective. ___ 13. Set breakpoints and step through the code using Resume, Step Into, Step Over, and Step Return to familiarize yourself with the debug features.
  • 23. • • • • • 4-1 Student Exercises for Unit 4 Exercise 1: Create the ModAdd Class This exercise involves creating a class named ModAdd that belongs to the package exercises.odd. • The class ModAdd will receive two numeric arguments. • Calculate the sum of the odd numbers that are multiples of 3 between those two arguments, including the arguments that define the numeric limits for the calculation. • Calculate the sum with a for loop and a while loop. • Use the modulus operator to determine if a number is a multiple of 3 or is an odd number. – A number is a multiple of 3 if num%3 equals zero. – A number is a multiple of 2 if num%2 equals zero. The following example shows a possible outline for the ModAdd class: package exercises.odd; public class ModAdd { // main program receives 2 arguments public static void main(String[] args) { // Check if arguments are given // If not, print error msg and System.exit(1); // // Get arguments and check if valid // Calculate sum using for loop and print total // Calculate sum using while loop and print total // }
  • 24. 4-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 4 Exercise 1: Create the ModAdd Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 1. Create the ModAdd class using the Eclipse IDE. ___ 2. Write the ModAdd class following the specifications as outlined previously. ___ 3. Save and compile the ModAdd class. ___ 4. The following table contains some example calculations. Range Odd Numbers that Are Multiples of 3 Calculated Sum 1 to 10 3,9 12 3 to 21 3,9,15,21 48 20 to 50 21,27,33,39,45 165 1 to 100 3,9,21,27,33,39,45,51,57,63,69....... 867
  • 25. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 4-3 • • • • • Student Exercises for Unit 4 Exercise 2: Debug the Application Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 5. Select the ModAdd file in the Package Explorer. Click Run > Run Configurations from the main menu. ___ 6. Select the Arguments tab and type program arguments. ___ 7. Run the ModAdd application and verify the results. Exercise 2: Debug the Application ___ 1. Select the ModAdd class in the Package Explorer. ___ 2. Select Run > Debug Configurations from the main menu. In the dialog box, the ModAdd is already displayed in the Java Application list. ___ 3. Select the Arguments tab if you want to type a different numeric range for the Program arguments. Click Apply. ___ 4. Return to the Main tab. ___ 5. Select the Stop in main option. ___ 6. Click Apply. ___ 7. Click Debug. ___ 8. Click Yes if the Confirm Perspective Switch message box is displayed. ___ 9. Eclipse opens the Debug perspective. Debug icons are available within this perspective, in addition to a Variable tab to inspect variable values and a Breakpoint tab. This debug session has stopped the program at the first statement in main().
  • 26. 4-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 4 Exercise 2: Debug the Application Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 10. Right-click the outer edge of the ModAdd file and select Toggle Breakpoint to set a breakpoint at a line of code in that file. ___ 11. Switch back to the Java perspective by clicking the Java tab (or click Window > Open Perspective > Java). Open the ModAdd file, if it is not already open. ___ 12. You can set breakpoints in either the Debug or the Java perspective. Set breakpoints and step through the code using Resume, Step Into, Step Over, and Step Return.
  • 27. • • • • • 5-1 Student Exercises for Unit 5 Exercise 1: Create the ReverseArgs Class This exercise involves creating a class named ReverseArgs that belongs to the package exercises.str. You will print out the argument list in reverse. • The ReverseArgs class will receive two or more arguments. • The ReverseArgs class will contain a method to reverse the arguments letter by letter. • The ReverseArgs class will contain a method to reverse the arguments word by word. The following example shows a possible outline for the ReverseArgs class: package examples.str; public class ReverseArgs { public static void main(String args[]){ if(args.length < 2) { // print usage statement return; } StringBuilder strArguments = new StringBuilder(); // Build a string using the args[] reverseArguments(strArguments); System.out.println ("strArguments = " + strArguments); // return strArguments to its original state reverseArguments(strArguments); System.out.println ("strArguments = " + strArguments); reverseWords(strArguments); System.out.println ("strArguments = " + strArguments); }
  • 28. 5-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 5 Exercise 2: Create the Calculator Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. public static StringBuilder reverseArguments(StringBuilder s) { // reverse the argument list, letter by letter // Use reverse() to reverse a string return s; } public static StringBuilder reverseWords(StringBuilder s) { // reverse the argument list word by word return s; } } ___ 1. Create the ReverseArgs class using the Eclipse IDE. ___ 2. Write the ReverseArgs class following the specifications as outlined in the preceding example. ___ 3. Save and compile the ReverseArgs class. ___ 4. Verify the results. Exercise 2: Create the Calculator Class This exercise involves creating a class named Calculator that belongs to the package exercises.calc. • The class Calculator will receive three arguments: an operator and two operands. • Calculate the result of the operator and the operands. • The operator is not case-sensitive, and requires only the portion shown in bold in the preceding table to be a valid operator. Operator Operands add operand1 + operand 2 subtract operand1 - operand 2 multiply operand1 * operand 2 divide operand1 / operand 2
  • 29. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 5-3 • • • • • Student Exercises for Unit 5 Exercise 2: Create the Calculator Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Examples of valid command-line arguments are: Add 77 55 sub 3 8 Subtract 33 22 Multi 1 7 DIVIDE 33 12 • The String class methods are useful to find the operation. The following example shows a possible outline for the Calculator class: package exercises.calc; public class Calculator { public void add(double o1, double o2) { } public void sub(double o1, double o2) { } public void mult(double o1, double o2) { } public void div(double o1, double o2) { } public static void main(String[] args) { // Check if 3 arguments are given // Check if operation and operations are valid // If not, print error msg and System.exit(1); // if(operation is "add") add(op1, op2); else if (operation is "sub") sub(op1, op2); .... } ___ 1. Create the Calculator class using the Eclipse IDE. ___ 2. Write the Calculator class following the specifications as outlined previously. ___ 3. Save and compile the Calculator class. ___ 4. Verify the results.
  • 30. 5-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 5 Exercise 3: Create the Util Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Exercise 3: Create the Util Class This exercise involves creating a utility class called Util that contains static methods for the add, subtract, multiply, and divide operations. The class belongs to the exercises.util package. • Overload the methods for each operation to allow for different data types, such as: public static int add(int op1, int op2){....} public static double add(double op1, double op2){....} • Example usage statement: double result = Util.sub(55.3, 22.1); The following example shows a possible outline for the Util class: package exercises.util; public class Util { public static int add(int o1, int o2) { } public static double add(double o1, double o2) { } public static int sub(int o1, int o2) { } public static double sub(double o1, double o2) { } .... } ___ 1. Create the Util class using the Eclipse IDE. ___ 2. Write the Util class following the specifications as outlined previously. ___ 3. Save and compile the Util class. ___ 4. Verify the results.
  • 31. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 5-5 • • • • • Student Exercises for Unit 5 Exercise 4: Create the Perform Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Exercise 4: Create the Perform Class This exercise involves creating a class named Perform that belongs to the package exercises.calc. The Perform class uses the Util class, which is in a different package. • The class Perform will receive three arguments: an operator and two operands. • The operands can be integer or double data types. If one operand is a double data type, both are assumed to be of type double. The following example shows a possible outline for the Perform class: public class Perform { public static void main(String[] args) { // Check for arguments // Convert arguments to numeric variables String num1; String num2; // Assign operands arguments to Strings and // Check if operands are int or double // int data type does not have a decimal point // double data type has a decimal point if (num1.indexOf(".") != -1) // string represents a double else // string represents an integer // place operands into int or double variables // call the correct operation with the operands // if the operation is add: Util.add(op1, op2); .... } } ___ 1. Create the Perform class using the Eclipse IDE. ___ 2. Write the Perform class following the specifications as outlined previously. ___ 3. Save and compile the Perform class. ___ 4. Verify the results.
  • 32. 5-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 5 Exercise 4: Create the Perform Class Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 33. • • • • • 6-1 Student Exercises for Unit 6 Exercise 1: Implement Exception Handing This exercise involves making a copy of the Perform.java file, renaming it Do.java, and adding exception handling. • Throw an exception if parameters are not provided or if the operation is invalid. • Use try-catch blocks to catch exceptions when parsing arguments. ___ 1. Copy the contents of Perform.java and rename the file and class Do.java. ___ 2. Add exception handling to the class. ___ 3. Save and compile the Do.java file. ___ 4. Verify the results with the cases in the following table. Exercise 2: Read and Write to Text Files This exercise involves reading and writing to a text file using the FileReader, BufferedReader, FileWriter, and BufferedWriter classes. A useful class for this exercise is java.util.Scanner, which can be used for parsing fields from a file. Regular expressions in the String class provide a replacement for the deprecated java.util.StringTokenizer class. Arguments Expected Result at Runtime No arguments Invalid case Add 1.0 two.2 Second operand is not a number abc 2 3 Invalid operation Sub 77 22 Valid case
  • 34. 6-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 6 Exercise 2: Read and Write to Text Files Course materials may not be reproduced in whole or in part without the prior written permission of IBM. • A file containing lines of text, some of which are palindromes, has been provided for you. A palindrome is a sentence or word that reads the same from right to left, or left to right. The classic example is Madam, I’m Adam. • Your code will examine each line of the text file and determine whether the line of text is a palindrome. If the line is a palindrome, then the line will be written to a new file. • Handle IOException when necessary. The following example shows a possible outline for the class: public class Palindromes { public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("Usage: Must have 2 parameters"); System.exit(1); } File inFile = new File(args[0]); File outFile = new File(args[1]); boolean exists = inFile.exists(); if (!exists) { System.out.println("File " + inFile.getName()+ does not exist"); System.exit(1); } try { filter4Palindromes(inFile, outFile1); } catch (IOException e) { System.out.println(e); System.exit(1); } } public static void filter4Palindromes(File in, File out) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); BufferedWriter writer = new BufferedWriter(new FileWriter(out)); // create Strings and StringBuilder objects // to manipulate lines of text // loop through the lines of // text while reader.readLine()) != null
  • 35. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 6-3 • • • • • Student Exercises for Unit 6 Exercise 2: Read and Write to Text Files Course materials may not be reproduced in whole or in part without the prior written permission of IBM. // if the line is a palindrome then write // the palindrome to the output file // close the reader // close the writer } ___ 1. Create the Palindromes class using the Eclipse IDE. ___ 2. Write the Palindromes class following the specifications as shown in the outline. ___ 3. Save and compile the Palindromes class. ___ 4. Verify the results.
  • 36. 6-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 6 Exercise 2: Read and Write to Text Files Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 37. • • • • • 7-1 Student Exercises for Unit 7 Exercise 1: Using an Interface This exercise uses an interface to demonstrate polymorphism. It involves creating an interface named HowAreYou and writing three classes that implement that interface. Each class will print “How are you?” in its own language. • Throw an exception if parameters are not provided or if the operation is invalid. • Use try-catch blocks to catch exceptions when parsing arguments. ___ 1. Using the Eclipse IDE, create an interface named HowAreYou.java that contains a single method named sayHowAreYou(). ___ 2. Create three class files that implement the HowAreYou interface, such as: – EnglishHowAreYou.java – ItalianHowAreYou.java – FrenchHowAreYou.java ___ 3. Each of the three classes must implement the sayHowAreYou() method and print “How are you?” to the console in the appropriate language. ___ 4. Create a class named SayHowAreYou that contains main(). ___ 5. The SayHowAreYou class contains an instance of the HowAreYou interface, sets the language to the three different implementing classes, and prints “How are you?” to the console in three different languages. The following example shows a possible outline for the driver class: package exercises.HowRU; public class SayHowAreYou { public HowAreYou howAreYou; public void setLanguage(HowAreYou howAreYou) { this.howAreYou = howAreYou; }
  • 38. 7-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. public void sayHowAreYou() { this.howAreYou.sayHowAreYou(); } public static void main(String[] args) { SayHowAreYou howru = new SayHowAreYou(); // set the language to English and print out // the message // set the language to Italian and print out // the message // set the language to French and print out // the message } } ___ 6. Save and compile the classes. ___ 7. Verify the results. Exercise 2: Using an Interface and Abstract Classes This exercise involves writing an interface, abstract classes, and their subclasses. Both inheritance and polymorphism are incorporated into the class design of this exercise. You will create multiple instrument-type objects; each implements its own play() method. How you choose to override the methods in the class hierarchy will determine which play() method is called.
  • 39. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-3 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. The following diagram shows the top-level design specification. The interface is named Instrument and contains three methods: • mute() • play() • tune() Four abstract classes implement the Instrument interface: • BowType • PluckType • StrikeType • WindType
  • 40. 7-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. In addition to implementing all of the methods contained in the Instrument interface, each of these classes also includes its own constructor and a getName() method. Multiple subclasses will extend the abstract classes and override the implementation of the abstract class methods. Each class will inherit all of the functionality of its superclass. In this case, the abstract classes are the superclasses. The abstract classes contain the methods from the Instrument interface, and any additional methods as outlined in the design illustration.
  • 41. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-5 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Next you will create the subclasses. The abstract class BowType has three subclasses: • Violin • Viola • Cello The abstract class PluckType has two subclasses: • Guitar • Bass The abstract class StrikeType has two subclasses: • Piano • Drum The abstract class WindType has one subclass: • Saxophone The complete specification is illustrated on the next page.
  • 42. 7-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 43. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-7 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. After all of the subclasses have been created, you will create a Quartet class that contains four instruments and has at least one method: playMusic(). The Quartet class could be written to contain a createStringQuartet method, creating a string quartet that contains two Violin objects, a Viola object, and a Cello object. Another option is to create a jazz quartet with a Saxophone, Piano, Bass, and Drum object. A third option is a rock quartet with two Guitar objects, a Bass object, and a Drum object. The driver to verify these classes might be implemented like the following main() method: package exercises.music; public class MakeMusic { public static void main(String[] args) { Quartet qString = new Quartet(); qString.createStringQuartet(); qString.playMusic(); Quartet qJazz = new Quartet(); qJazz.createJazzQuartet(); qJazz.playMusic(); Quartet qRock = new Quartet(); qRock.createRockQuartet(); qJazz.playMusic(); } }
  • 44. 7-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 1. In the exercises.music package, create an interface named Instrument.java that contains three public methods: – play() – tune() – mute() ___ 2. Create four abstract class files that implement the Instrument interface: – BowType.java – PluckType.java – StrikeType.java – WindType.java ___ 3. Each of the four classes must implement the methods from the Instrument interface in addition to a constructor and a getName() method. The implementation is to print the name of the corresponding class and method to the console. ___ 4. Create eight subclasses: – The Violin, Viola, and Cello classes extend the abstract class BowType. – The Guitar and Bass classes extend the abstract class PluckType. – The Piano and Drum classes extend the abstract class StrikeType. – The Saxophone class extends the abstract class WindType. The implementation for each method in the subclasses is to print the name of the corresponding class and method to the console. ___ 5. Create a Quartet class in the same exercises.music package as the other classes created thus far. ___ 6. Add a collection of four instruments to the Quartet class.You can implement the collection with an array or use a collection class. ___ 7. Implement a playMusic() method that loops through the instruments and calls the play() method of each one. ___ 8. Write a driver class that contains a main() method to test your implementation of the class design.
  • 45. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-9 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. The following example shows a possible outline for the driver class: public class MakeMusic { public static void main(String[] args) { Quartet qJazz = new Quartet(); qJazz.createJazzQuartet(); qJazz.playMusic(); } } ___ 9. Save and compile the classes. ___ 10. Verify the results.
  • 46. 7-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 7 Exercise 2: Using an Interface and Abstract Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 47. • • • • • 8-1 Student Exercises for Unit 8 Exercise 1: Determine a Median In this exercise you will write a class to determine the median of a variable number of arguments. To find the median value, place the values in order and find the middle value. If there is an even number of values, find the middle pair of values and calculate the average of those two values. ___ 1. Create the new class Median in the exercises.calc package. ___ 2. Within the main() method, write the code to calculate the median of the program arguments. Hint: The java.util.Arrays.sort() method is useful for this exercise. ___ 3. Save and compile the Median class. ___ 4. Run the Median class and verify the results. Exercise 2: Use a LinkedList In this exercise you create a class that implements the LinkedList class and uses the ListIterator to print a list in reverse. • Throw any necessary IO exceptions. • Use try-catch blocks to catch exceptions.
  • 48. 8-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 8 Exercise 2: Use a LinkedList Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 1. Create a class named LList.java that contains a main() method. ___ 2. The LList.java class takes one parameter, which is the name of a text file. You can create a text file for testing or use the input file from the Palindrome exercise. ___ 3. Write a fillList() method that: – Reads the input file – Adds each line as an element to a LinkedList object – Uses a ListIterator object to traverse the list in reverse – Prints each line to the console ___ 4. Create an outline for the LList class. For example: package exercises.list; public class LList { public static void main(String[] args) { // check for input parameter File inFile = new File(args[0]); // Verify that the file exists try { fillList(inFile); } catch (IOException e) { // handle exception } } public static void fillList(File in) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); LinkedList<String> lst = new LinkedList<String>(); String line = null; while ((line=reader.readLine()) != null) { lst.add(line); } System.out.println("Print list in reverse"); // Use a ListIterator object within a for loop and // print the list in reverse } }
  • 49. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-3 • • • • • Student Exercises for Unit 8 Exercise 3: Use an ArrayList Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 5. Save and compile the class. ___ 6. Verify the results. Exercise 3: Use an ArrayList In this exercise you create a class that implements the ArrayList class and uses the ListIterator to print a list. ___ 1. Create a copy of the LList class and name the copy AList.java. ___ 2. Rewrite AList.java to use an ArrayList class instead of a LinkedList class to store the lines of text from the input file. ___ 3. Use an iterator in the fillList() method to traverse the collection. Print the contents of the collection in a forward direction and in reverse. ___ 4. Save and compile the class. ___ 5. Verify the results. Exercise 4: Create a Deck of Cards In this exercise you will write a class to represent a deck of 52 cards. The class should include the following items: • A constructor that creates the deck of cards and stores it within an appropriate data structure. The deck of cards should contain a sequence of 13 cards in four suits (spades, clubs, hearts, and diamonds). • A printDeck() method to print the deck of cards. • A shuffleDeck() method to shuffle the deck of cards. • A dealFromTop() method to deal five cards from the top of the deck. • A dealFromBottom() method to deal five cards from the bottom of the deck. ___ 1. Create the new class Deck in the new exercises.cards package. Hint: The java.util.Collections.shuffle() method is useful for this exercise.
  • 50. 8-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 8 Exercise 4: Create a Deck of Cards Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 2. Create a driver class called ShuffleNDeal in the exercises.cards package. Within the main() method, the following outline can be used: public class ShuffleNDeal { public static void main(String[] args) { Deck deck = new Deck(); deck.printDeck(); deck.shuffleDeck(); deck.dealFromTop(4); deck.dealFromBottom(3); deck.shuffleDeck(); deck.dealFromTop(2); } } ___ 3. Save and compile the Deck and ShuffleNDeal classes. ___ 4. Run the ShuffleNDeal class and verify the results.
  • 51. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-5 • • • • • Student Exercises for Unit 8 Exercise 5: Create a Hospital Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Exercise 5: Create a Hospital This exercise shows you how to coordinate and debug multiple classes that interact with each other. You will incorporate all that you have learned so far and create classes that represent a hospital setting. The hospital setting will be composed of different objects. Use the object design outlined in this exercise or create your own. • The hospital has: – Doctors – Patients – Labs, such as an X-ray lab and a blood lab • The doctors can: – Request tests for their patients, such as an X-ray test and a blood test – Get test results, such as X-ray test results or blood test results
  • 52. 8-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 8 Exercise 5: Create a Hospital Course materials may not be reproduced in whole or in part without the prior written permission of IBM. In this exercise, try to use: – Inheritance (is-a relationship) – Composition (has-a relationship) – Abstract classes or interfaces – Polymorphism – Subclasses – Private, protected, and public variables and methods – Collection classes to store lists – Exception handling Lab, MedicalTest, and Result are abstract classes. The Hospital class contains an XRayLab and BloodLab object, in addition to a list of Patient and Doctor objects. The Patient objects contain a reference to their Doctor. The Doctor objects can request tests and get results for their Patient objects.
  • 53. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-7 • • • • • Student Exercises for Unit 8 Exercise 5: Create a Hospital Course materials may not be reproduced in whole or in part without the prior written permission of IBM. The following illustration outlines 13 classes that represent a hospital setting. Classes and their variables and methods are outlined. This class design can be used to create a possible solution, or you may design your own classes to represent a hospital.
  • 54. 8-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 8 Exercise 5: Create a Hospital Course materials may not be reproduced in whole or in part without the prior written permission of IBM. The Eclipse IDE offers multiple ways to view a class hierarchy, types, and class members. The previous image contains detailed information regarding the class members. The following graphic details the class hierarchy, specifically the CountyHospital class, which extends Hospital and contains the main( ) method. The main() method calls helper methods to populate the hospital with doctors and patients, request tests for the labs, run the tests, and get the results. This graphic also illustrates that Lab, MedicalTest, and Result are all abstract classes, as denoted by the letter A. You can use the classes presented in the graphics or produce your own class design to represent a hospital setting. Remember that the purpose of this exercise is to gain experience writing classes that interact with one other. The classes make requests of other objects, and share data while using the public, private, and protected access modifiers. ___ 1. Create the classes necessary to produce a hospital setting as described in the preceding description.
  • 55. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-9 • • • • • Student Exercises for Unit 8 Exercise 5: Create a Hospital Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 2. Save and compile the classes. ___ 3. Add print statements to your code and use the debugger to correct programming and logic errors. ___ 4. Verify the results. – Are lists of doctors and patients being maintained? – Are tests objects being processed by the lab objects, and are results generated? – Are the lab requests being maintained and processed? While verifying the results, the console output might look something like the following example.
  • 56. 8-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 8 Exercise 5: Create a Hospital Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 57. • • • • • 9-1 Student Exercises for Unit 9 Exercise 1: The Producer–Consumer Classes Threads that execute in parallel and share common resources must be synchronized at certain points to ensure proper functioning of the system. In this exercise you add code to a partially completed class. The code you add will synchronize the data shared between the Producer and the Consumer classes so that the two classes can work together. The Producer-Consumer example is often used to illustrate thread synchronization techniques. The Producer-Consumer classes were written to create a practical example. The Producer and Consumer classes share a common resource: the SharedData class. The Producer class contains an infinite loop that generates integer values in sequence and places those integer values into the SharedData object. The Consumer class contains an infinite loop that reads the integer values from the SharedData object. The purpose of this exercise is to synchronize the classes so that consecutive integers are not lost and duplicate integers are not retrieved. The following example shows the contents of the Producer, Consumer, and SharedData classes: public class Producer implements Runnable { SharedData data; int interval; int identifier; public Producer(SharedData data, int id, int interval) { this.data=data; this.interval=interval; this.identifier=id; } public void run() { int i; for(i=0; ; i++) { data.put(i); System.out.println("Producer "+ identifier+ ": "+i); try {
  • 58. 9-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 9 Exercise 1: The Producer–Consumer Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Thread.sleep((int) (Math.random()*interval)); } catch (InterruptedException e) {System.out.println("Producer errorn");} } } } public class Consumer implements Runnable { SharedData data; int interval; int identifier; public Consumer(SharedData data, int id, int interval) { this.data=data; this.interval=interval; this.identifier=id; } public void run() { for(;;) { System.out.println(" Consumer " + identifier + ": "+data.get()); try { Thread.sleep((int) (Math.random()*interval)); } catch (InterruptedException e) {System.out.println("Consumer errorn");} } } } public class SharedData { protected int data; public void put(int data) { this.data=data; } public int get() { return this.data; } The ProducerConsumerDriver class acts as the driver and takes the following parameters: • ProducerNumber is the number of Producer threads. • ConsumerNumber is the number of Consumer threads. • producerPriority is the priority that will be assigned to the Producer thread or threads.
  • 59. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-3 • • • • • Student Exercises for Unit 9 Exercise 1: The Producer–Consumer Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. • consumerPriority is the priority that will be assigned to the Consumer thread or threads. • interval is the sleep() interval in milliseconds between consecutive writes or reads from the Producer and Consumer thread or threads. public class ProducerConsumerDriver { public static void main(String[] args) { SharedData data; Thread Producers[]; Thread Consumers[]; int ProducerNumber; int ConsumerNumber; int producerPriority; int consumerPriority; int interval; if (args.length < 5 ) { // print usage to console return; } ProducerNumber=Integer.parseInt(args[0]); ConsumerNumber=Integer.parseInt(args[1]); producerPriority = Integer.parseInt(args[2])); consumerPriority = Integer.parseInt(args[3]); interval=Integer.parseInt(args[4]); data = new SharedData(); Producers = new Thread[ProducerNumber]; Consumers = new Thread[ConsumerNumber]; for(int i=0;i<ProducerNumber;i++){ Producers[i]=new Thread (new Producer(data, i, interval)); Producers[i].setPriority(producerPriority); Producers[i].start(); } for(int i=0;i<ConsumerNumber;i++) { Consumers[i]=new Thread (new Consumer(data, i, interval)); Consumers[i].setPriority(consumerPriority); Consumers[i].start(); } } } Execution of the ProducerConsumerDriver class with the argument list 1 1 5 5 10 produces the following output:
  • 60. 9-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 9 Exercise 1: The Producer–Consumer Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Producer 0: 0 Producer 0: 1 Producer 0: 2 Producer 0: 3 Consumer 0: 3 Consumer 0: 3 Producer 0: 4 Consumer 0: 4 Producer 0: 5 Producer 0: 6 Producer 0: 7 Producer 0: 8 Consumer 0: 8 Consumer 0: 8 The output shows that the Consumer reads duplicate integers. The Producer writes consecutive integers and only the last integer is retrieved by the Consumer. Because the SharedData object is unsynchronized, there is no synchronization between the Producer and the Consumer objects. You can experiment with different arguments, such as 3 3 5 5 10, and inspect the output from more than one Producer and Consumer thread. Without synchronization, integer values are lost and others are read multiple times. The Producer and Consumer classes contain infinite loops. You must terminate this program manually in the Eclipse IDE by clicking the Terminate button. The Terminate button is the red icon in the Console window. To synchronize the SharedData class: • Include a boolean flag to control data access and indicate when an integer has been produced or consumed. • Use the synchronized keyword to protect code segments that require mutual exclusion. When methods are synchronized, the locking and waiting is handled by Java. Only one thread at a time can be executing the method. • Implement the wait() and notifyAll() methods. • Synchronized threads call wait() and notifyAll() when they have modified something so that the waiting thread can recheck the boolean flag. The waiting thread can wait for a condition to change within a while loop. while (conditionToProceed != true) { wait(); ..... } ___ 1. Use the files provided for the Producer, Consumer, and ProducerConsumerDriver classes.
  • 61. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-5 • • • • • Student Exercises for Unit 9 Exercise 1: The Producer–Consumer Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 2. Write a SharedData class that ensures that the shared data is synchronized for concurrent access by multiple threads. The Producer, Consumer, and ProducerConsumerDriver classes shown in the exercise description should remain unchanged but you must modify the unsynchronized SharedData class. ___ 3. Save and compile the file. ___ 4. Verify your results. For a single Consumer and Producer thread, the output should look like the following image. The Terminate icon, which you must click to stop the program, is highlighted with a circle in the image.
  • 62. 9-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 9 Exercise 1: The Producer–Consumer Classes Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 63. • • • • • 10-1 Student Exercises for Unit 10 Exercise 1: Create a Serializable Object In this exercise you create a class that is serializable and write the object to a text file. • Throw any necessary IO exceptions. • Use try-catch blocks to catch exceptions. ___ 1. Create a class named SerialObject.java that belongs to the examples.serial package and implements the Serializable interface. ___ 2. Add variables to the SerialObject class. Try adding a transient variable, a primitive, a collection type of object, or any other type of object. For example: public class SerialObject implements Serializable { transient int transValue; int value; String stringValue; ArrayList<String> lst; ___ 3. Write a constructor for the SerialObject class that assigns values to the variables to define their state. Exercise 2: Serialize an Object ___ 1. Create a class named SerializeDriver.java that belongs to the examples.serial package. ___ 2. Create an instance of SerialObject object and assign values to all of the variables. ___ 3. Populate any collection type of objects in the SerialObject object. ___ 4. Using FileOutputStream and ObjectOutputStream objects, write the state of a SerialObject object to a file.
  • 64. 10-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 10 Exercise 3: Deserialize an Object Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Exercise 3: Deserialize an Object ___ 1. Create a class named DeserializeDriver.java that belongs to the examples.serial package. ___ 2. Create a new instance of SerialObject in the DeserializeDriver class. ___ 3. Include code to read the serialized state of a SerialObject object from a file into the new instance of SerialObject in your DeserializeDriver class. – Use the file to which the serialized state was written in Exercise 2. – Use FileInputStream and ObjectInputStream objects to read the file. ___ 4. Save and compile your code. ___ 5. Verify that the SerialObject variable values that were written to a file in Exercise 2 mirror the values that have been read into the new instance of SerialObject in the DeserializeDriver class. Exercise 4: Using RMI In this exercise, you will compile files using rmic (RMI compiler) and test the programs. Examine the four source files that have been provided to understand how they interact with each other: • Hello.java • HelloRemote.java • RMIServer.java • RMIClient.java An Ant build runs the rmic in Eclipse. Ant is a build tool distributed by the Apache Software Foundation. A build.xml file supplies the necessary parameters to run the rmic using the Ant Build option. ___ 1. If it does not exist in your project, create a package called exercises.helloRemote. Copy the four .java files and the build.xml file into the package directory. ___ 2. Select the build.xml file.
  • 65. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-3 • • • • • Student Exercises for Unit 10 Exercise 4: Using RMI Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 3. Right-click the External Tools icon. ___ 4. Select External Tools Configuration. ___ 5. Create a new launch configuration for the build.xml file. ___ 6. Select Browse Workspace for the Base Directory option. Select the project folder.
  • 66. 10-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 10 Exercise 4: Using RMI Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 7. Click the JRE tab to verify that the correct Java SDK is available for use.
  • 67. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-5 • • • • • Student Exercises for Unit 10 Exercise 4: Using RMI Course materials may not be reproduced in whole or in part without the prior written permission of IBM. ___ 8. Click Apply and Run. ___ 9. Verify that the class files were built, including the stub class file. ___ 10. Start the server and the client. If the default port number (1099) is in use, supply another port number as a program argument. ___ 11. Verify the output.
  • 68. 10-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Student Exercises for Unit 10 Exercise 4: Using RMI Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 69. • • • • • A-1 Appendix A: Exercise Solutions Unit 1 Exercise Solutions No solutions are provided. Unit 2 Exercise Solutions // // Solution for HelloWorld Exercise // package exercises.hello; public class HelloWorld { public static void main(String[] args) { System.out.print("Hello World!n"); System.out.println("I am here!"); } } Unit 3 Exercise Solutions Exercise 1 package exercises.calc; public class Average { public static void main(String[] args) { if (args.length == 0) { System.out.println("No arguments to compute average"); return; }
  • 70. A-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Appendix A: Exercise Solutions Unit 3 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. double total = 0; double value = 0; /* for(String v: args) { value = Double.parseDouble(v); total += value; System.out.println("Added " + value + " to the total"); } System.out.println("The sum of the arguments equals = " + total); double average = total/args.length; System.out.println("Calculated average is: " + average); */ for (int i=0; i<args.length; ++i) { value = Double.parseDouble(args[i]); total += value; System.out.println("Added " + value + " to the total"); } System.out.println("The sum of the arguments equals = " + total); double average = total/args.length; System.out.println("Calculated average is: " + average); } } Exercise 2 package exercises.calc; public class MaxOrMin { public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: max|min number number"); return; } System.out.print("Program arguments: "); for (String v:args) System.out.print(v + " "); System.out.println(); double value1 = Double.parseDouble(args[1]); double value2 = Double.parseDouble(args[2]); if (value1==value2) { System.out.println("The values are equal."); } else if (args[0].equalsIgnoreCase("max")) { System.out.println("The maximum value is: " +
  • 71. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-3 • • • • • Appendix A: Exercise Solutions Unit 3 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. Math.max(value1,value2)); } else if (args[0].equalsIgnoreCase("min")) { System.out.println("The minimum value is: " + Math.min(value1,value2)); } else System.out.println("Invalid argument"); } } Exercise 3 // Solution for WestToEast Exercise package exercises.time; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; public class WestToEast { public static void main(String[] args) { // Base GMT offset: -8:00 SimpleTimeZone zone1 = new SimpleTimeZone(-8 * 60 * 60 * 1000, "America/Los_Angeles"); // Base GMT offset: -5:00 SimpleTimeZone zone2 = new SimpleTimeZone(-5 * 60 * 60 * 1000, "America/New_York"); // Define time period for daylight savings time zone1.setStartRule(Calendar.MARCH, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); zone1.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); zone2.setStartRule(Calendar.MARCH, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); zone2.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); // Create two GregorianCalendar objects with the East and West // Coast time zone and the current date and time Calendar calendar1 = new GregorianCalendar(zone1); Calendar calendar2 = new GregorianCalendar(zone2); Date time = new Date(); // Get current Date/Time calendar1.setTime(time); // convert current date/time to West // Coast time zone
  • 72. A-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Appendix A: Exercise Solutions Unit 4 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. calendar2.setTime(time); // convert current date/time to East // Coast time zone // System.out.println("West Coast time: " + calendar1.get(Calendar.HOUR) + ":" + calendar1.get(Calendar.MINUTE)); // System.out.println("East Coast time: " + calendar2.get(Calendar.HOUR) + ":" + calendar2.get(Calendar.MINUTE)); int zone1TimeMinutes = (calendar1.get(Calendar.HOUR) * 60) + calendar1.get(Calendar.MINUTE); int zone2TimeMinutes = zone1TimeMinutes - calendar1.get(Calendar.ZONE_OFFSET)/(60*1000) + calendar2.get(Calendar.ZONE_OFFSET)/(60*1000); int zone2Hours = zone2TimeMinutes/60; int zone2Mins = zone2TimeMinutes - (zone2Hours*60); System.out.println("Calculated East Coast time: " + zone2Hours+ " hours and " + zone2Mins + " minutes"); } } Unit 4 Exercise Solutions // Solution for ModAdd Exercise package exercises.odd; public class ModAdd { public static void main(String[] args) { // two parameters are required if(args.length < 2) { System.out.println("Error: Requires two integer parameters"); return; } // get arguments int from = Integer.parseInt(args[0]); int to = Integer.parseInt(args[1]); // check arguments if(from >= to) { System.out.println("Error: 1st argument must be less than 2nd"); return; } System.out.println("nUsing for loop:"); int sum = 0; // for loop
  • 73. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-5 • • • • • Appendix A: Exercise Solutions Unit 5 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. // iterate for all numbers "from" - "to" for(int i = from; i <= to; i++) { // check if number is multiple of 3 and not even if(i%3 == 0 && i%2 != 0) { sum = sum + i; } } System.out.println("Sum of odd numbers that are multiples of 3 from " + from + " to " + to + " is " + sum); System.out.println("nUsing while loop:"); sum = 0; //reinitialize total int i = from; // loop for all number "from" - "to" while( i <= to) { // check if number is multiple of 3 and not even if(i%3 == 0 && i%2 != 0) sum = sum + i; i++; } System.out.println("Sum of odd numbers that are multiples of 3 from " + from + " to " + to + " is " + sum); } } Unit 5 Exercise Solutions Exercise 1 package examples.str; public class ReverseArgs { public static void main(String args[]){ if(args.length < 2) { System.out.println("Usage: Requires at least two arguments"); return; } StringBuilder strArguments = new StringBuilder(); // Use either traditional for loop or the enhanced foreach for ( String v : args) { strArguments.append(v + " "); }
  • 74. A-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Appendix A: Exercise Solutions Unit 5 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. reverseArguments(strArguments); System.out.println ("Reversed letter by letter= " + strArguments); // return strArguments to its original state reverseArguments(strArguments); System.out.println ("Original argument list = " + strArguments); reverseWords(strArguments); System.out.println ("Reversed word by word = " + strArguments); } public static StringBuilder reverseArguments(StringBuilder s) { s = s.reverse(); return s; } public static StringBuilder reverseWords(StringBuilder s) { String str = s.toString(); String[] words = str.split (" "); s.delete(0, s.length()); for (int i=words.length; i > 0; ) s.append(words[--i] + " "); return s; } } Exercise 2 // Solution for Calculator Exercise package exercises.calc; public class Calculator { public void add(double o1, double o2) { double result = o1 + o2; System.out.println(o1 + " + " + o2 + " = " + result); } public void sub(double o1, double o2) { double result = o1 - o2; System.out.println(o1 + " - " + o2 + " = " + result); } public void mult(double o1, double o2) { double result = o1 * o2; System.out.println(o1 + " * " + o2 + " = " + result); }
  • 75. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-7 • • • • • Appendix A: Exercise Solutions Unit 5 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. public void div(double o1, double o2) { double result = o1 / o2; System.out.println(o1 + " / " + o2 + " = " + result); } public static void main(String[] args) { if(args.length < 3) { System.out.println("Usage: add/sub/mult/div op1 op2"); return; } // get operation and change to uppercase String operation = args[0].toUpperCase(); // get operands double op1 = Double.parseDouble(args[1]); double op2 = Double.parseDouble(args[2]); // create instance of Calculator Calculator calc = new Calculator(); // check for the uppercase operation // and execute the appropriate method if(operation.startsWith("ADD")) { calc.add(op1,op2); } else if (operation.startsWith("SUB")) { calc.sub(op1,op2); } else if (operation.startsWith("MULT")) { calc.mult(op1,op2); } else if (operation.startsWith("DIV")) { calc.div(op1,op2); } else { System.out.println("Error: Invalid operation: " + operation + " It must be add/sub/mult/div"); } } } Exercise 3 // Solution for Util Exercise public class Util { public static double add(double o1, double o2) { double result = o1 + o2; return result;
  • 76. A-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Appendix A: Exercise Solutions Unit 5 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. } public static int add(int o1, int o2) { int result = o1 + o2; return result; } public static double sub(double o1, double o2) { double result = o1 - o2; return result; } public static int sub(int o1, int o2) { int result = o1 - o2; return result; } public static double mult(double o1, double o2) { double result = o1 * o2; return result; } public static int mult(int o1, int o2) { int result = o1 * o2; return result; } public static double div(double o1, double o2) { double result = o1 / o2; return result; } public static int div(int o1, int o2) { int result = o1 / o2; return result; } } Exercise 4 // Solution for Perform Exercise package exercises.calc; import exercises.util.*; public class Perform { public static void main(String[] args) { if(args.length < 3) { System.out.println("Usage: add/sub/mult/div op1 op2"); return; }
  • 77. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-9 • • • • • Appendix A: Exercise Solutions Unit 5 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. // Get the operation and convert to uppercase String operation = args[0].toUpperCase(); // get operands double op1 = 0; double op2 = 0; int i1 = 0; int i2 = 0; boolean isDouble = false; if(args[1].indexOf(".") != -1 || args[2].indexOf(".") != -1) { try { op1 = Double.parseDouble(args[1]); op2 = Double.parseDouble(args[2]); isDouble = true; } catch (NumberFormatException e) { e.printStackTrace(); } } else { i1 = Integer.parseInt(args[1]); i2 = Integer.parseInt(args[2]); } double answer = 0; // check operation and execute the proper one if(operation.startsWith("ADD")) { if(isDouble) answer = Util.add(op1,op2); else answer = Util.add(i1,i2); } else if (operation.startsWith("SUB")) { if(isDouble) answer = Util.sub(op1,op2); else answer = Util.sub(i1,i2); } else if (operation.startsWith("MULT")) { if(isDouble) answer = Util.mult(op1,op2); else answer = Util.mult(i1,i2); } else if (operation.startsWith("DIV")) { if(isDouble) answer = Util.div(op1,op2); else answer = Util.div(i1,i2); } else { System.out.println("Error: Invalid operation: " + operation + " It must be add/sub/mult/div"); return; }
  • 78. A-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Appendix A: Exercise Solutions Unit 6 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. System.out.println(operation + " " + args[1] + " " + args[2] + " = " + answer); } } Unit 6 Exercise Solutions Exercise 1 package exercises.calc; import exercises.util.*; public class Do { public static void main(String[] args) throws Exception { if(args.length < 3) { System.out.println("Usage: add/sub/mult/div op1 op2"); throw new Exception("Too few parameters."); } // Get the operation and convert to uppercase String operation = args[0].toUpperCase(); // get operands double op1 = 0; double op2 = 0; int i1 = 0; int i2 = 0; boolean isDouble = false; if(args[1].indexOf(".") != -1 || args[2].indexOf(".") != -1) { try { op1 = Double.parseDouble(args[1]); op2 = Double.parseDouble(args[2]); isDouble = true; } catch (NumberFormatException e) { e.printStackTrace(); throw new Exception("Parameters " + args[1] + " and " + args[2] + " must be numeric"); } } else { i1 = Integer.parseInt(args[1]); i2 = Integer.parseInt(args[2]); } double answer = 0;
  • 79. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-11 • • • • • Appendix A: Exercise Solutions Unit 6 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. // check operation and execute the proper one if(operation.startsWith("ADD")) { if(isDouble) answer = Util.add(op1,op2); else answer = Util.add(i1,i2); } else if (operation.startsWith("SUB")) { if(isDouble) answer = Util.sub(op1,op2); else answer = Util.sub(i1,i2); } else if (operation.startsWith("MULT")) { if(isDouble) answer = Util.mult(op1,op2); else answer = Util.mult(i1,i2); } else if (operation.startsWith("DIV")) { if(isDouble) answer = Util.div(op1,op2); else answer = Util.div(i1,i2); } else { System.out.println("Error: Invalid operation: " + operation + ". It must be add/sub/mult/div"); throw new Exception("Invalid operation: " + operation); } System.out.println(operation + " " + args[1] + " " + args[2] + " = " + answer); } } Exercise 2 package exercises.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Palindromes {
  • 80. A-12 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Appendix A: Exercise Solutions Unit 6 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. public static void main(String[] args) throws IOException { if (args.length != 3) { System.out.println("Usage: Must have 3 parameters"); System.exit(1); } File inFile = new File(args[0]); File outFile1 = new File(args[1]); File outFile2 = new File(args[2]); boolean exists = inFile.exists(); if (!exists) { System.out.println("File " + inFile.getName() + "does not exists"); System.exit(1); } try { filter4Palindromes(inFile, outFile1); scan4Palindromes(inFile, outFile2); } catch (IOException e) { System.out.println(e); System.exit(1); } } public static void filter4Palindromes(File in, File out) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); BufferedWriter writer = new BufferedWriter(new FileWriter(out)); String originalLine = null; String reversedLine = null; String trimmedLine = null; while ((originalLine=reader.readLine()) != null) { trimmedLine = originalLine.replaceAll(" ", ""); StringBuilder sbLine = new StringBuilder(trimmedLine); reversedLine = sbLine.reverse().toString(); if (reversedLine.compareToIgnoreCase(trimmedLine) == 0 ) { writer.write(originalLine); writer.newLine(); // System dependent newline } } reader.close(); // Close reader to unlock writer.close(); // Close writer to unlock and flush } public static void scan4Palindromes(File in, File out) throws IOException { Scanner freader = new Scanner(in); // uses Scanner BufferedWriter writer = new BufferedWriter(new FileWriter(out)); String originalLine = null; String reversedLine = null; String trimmedLine = null; while (freader.hasNextLine()) { originalLine = freader.nextLine();
  • 81. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-13 • • • • • Appendix A: Exercise Solutions Unit 7 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. trimmedLine = originalLine.replaceAll(" ", ""); StringBuilder sbLine = new StringBuilder(trimmedLine); reversedLine = sbLine.reverse().toString(); if (reversedLine.compareToIgnoreCase(trimmedLine) == 0 ) { writer.write(originalLine); writer.newLine(); } } freader.close(); writer.close(); } } Unit 7 Exercise Solutions Exercise 1 The following five files form the solution for Exercise 1: package exercises.HowRU; public interface HowAreYou { public void sayHowAreYou(); } package exercises.HowRU; public class EnglishHowAreYou implements HowAreYou { public void sayHowAreYou() { System.out.println("How are you?"); } } package exercises.HowRU; public class FrenchHowAreYou implements HowAreYou { public void sayHowAreYou() { System.out.println("Ca va?"); } }
  • 82. A-14 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Appendix A: Exercise Solutions Unit 7 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. package exercises.HowRU; public class ItalianHowAreYou implements HowAreYou { public void sayHowAreYou() { System.out.println("Come stai?"); } } package exercises.HowRU; public class SayHowAreYou { public HowAreYou howAreYou; public void setLanguage(HowAreYou howAreYou) { this.howAreYou = howAreYou; } public void sayHowAreYou() { this.howAreYou.sayHowAreYou(); } public static void main(String[] args) { SayHowAreYou howru = new SayHowAreYou(); howru.setLanguage(new EnglishHowAreYou()); howru.sayHowAreYou(); howru.setLanguage(new ItalianHowAreYou()); howru.sayHowAreYou(); howru.setLanguage(new FrenchHowAreYou()); howru.sayHowAreYou(); } } Exercise 2 The following fifteen files form a possible solution for Exercise 2: package exercises.music; public interface Instrument { public void play(); public void tune(); public void mute(); } package exercises.music; public abstract class BowType implements Instrument { private String name;
  • 83. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-15 • • • • • Appendix A: Exercise Solutions Unit 7 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. protected BowType(String instrumentName) { System.out.println("Entering BowType constructor"); name = new String(instrumentName); System.out.println("Exiting BowType constructor"); } protected String getName() { return name; } public void mute() { System.out.println("mute():abstract class BowType for " + getName() ); } public void play() { System.out.println("play():abstract class BowType for " + getName()); } public void tune() { System.out.println("tune():abstract class BowType for " + getName()); } } package exercises.music; public abstract class PluckType implements Instrument { private String name; protected String getName() { return name; } protected PluckType(String instrumentName) { System.out.println("Entering BowType constructor"); name = new String(instrumentName); System.out.println("Exiting BowType constructor"); } public void mute() { System.out.println("mute():abstract class PluckType" + getName()); } public void play() { System.out.println("play():abstract class PluckType" + getName()); } public void tune() { System.out.println("tune():abstract class PluckType" + getName()); } }
  • 84. A-16 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009 • • • • • Appendix A: Exercise Solutions Unit 7 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. package exercises.music; public abstract class StrikeType implements Instrument { private String name; protected StrikeType(String instrumentName) { System.out.println("Entering StrikeType constructor"); name = new String(instrumentName); System.out.println("Exiting StrikeType constructor"); } protected String getName() { return name; } public void mute() { System.out.println("mute():abstract class StrikeType" + getName()); } public void play() { System.out.println("play():abstract class StrikeType" + getName()); } public void tune() { System.out.println("tune():abstract class StrikeType" + getName()); } } package exercises.music; public abstract class WindType implements Instrument { private String name; protected WindType(String instrumentName) { System.out.println("Entering WindType constructor"); name = new String(instrumentName); System.out.println("Exiting WindType constructor"); } protected String getName() { return name; } public void mute() { System.out.println("mute():abstract class WindType" + getName()); } public void play() { System.out.println("play():abstract class WindType" + getName()); } public void tune() { System.out.println("tune():abstract class WindType" + getName()); } }
  • 85. ©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-17 • • • • • Appendix A: Exercise Solutions Unit 7 Exercise Solutions Course materials may not be reproduced in whole or in part without the prior written permission of IBM. package exercises.music; public class Bass extends PluckType { public Bass() { super("Bass"); System.out.println("Exiting Bass constructor"); } public String getName(){ System.out.println ("The Bass class inherits its name: " + super.getName() + " from its base class"); return super.getName(); } } package exercises.music; public class Cello extends BowType { public Cello() { super("Cello"); System.out.println("Exiting Cello constructor"); } public String getName(){ System.out.println ("The Cello class inherits its name: " + super.getName() + " from its base class"); return super.getName(); } } package exercises.music; public class Drums extends StrikeType { public Drums() { super("Drums"); System.out.println("Exiting Drums constructor"); } public String getName(){ System.out.println ("The Drums class inherits its name: " + super.getName() + " from its base class"); return super.getName(); } }