Java Programming Exercises | Constructor (Object Oriented ...

February 29, 2016 | Author: Anonymous | Category: Java
Share Embed


Short Description

Introduction to Java Programming Exercises. Exercise 2. Goal The goal of this exercise is to become familiar with object...

Description

Introduction to Java Programming Exercises

Table of Contents Table of Contents....................................................................................................................... 1 Exercise 1................................................................................................................................... 3 Goal....................................................................................................................................3 Install the Java Development Kit (JDK)............................................................................3 Add the JAVA_HOME and Modify the PATH Environment Variables...........................3 Edit and Run a Simple Java Application............................................................................3 Exercise 2................................................................................................................................... 5 Goal....................................................................................................................................5 Description of the Order Entry Area of the Business.........................................................5 Understanding the Object-Oriented Principles...................................................................5 Identifying Business Classes, Attributes, and Methods.....................................................5 Exercise 3................................................................................................................................... 7 Goal....................................................................................................................................7 Understanding Objects, Classes, Methods, and Attributes................................................7 Exploring Code..................................................................................................................7 Questions About the Java Development Kit......................................................................8 Creating Order Entry Class Files........................................................................................8 Create and Compile the Application Class with a main() Method.....................................9 Exercise 4................................................................................................................................. 11 Goal..................................................................................................................................11 Your Assignment..............................................................................................................11 Create the OrderItem Class..............................................................................................11 Modify the Order Class....................................................................................................11 Modify the main() Method in the OrderEntry Class........................................................12 Exercise 5................................................................................................................................. 14 Goal..................................................................................................................................14 Your Assignment..............................................................................................................14 Create the Util Class.........................................................................................................14 Modify the Order Class....................................................................................................16 Test the Code by Using the OrderEntry Class..................................................................17 Exercise 6................................................................................................................................. 18 Goal..................................................................................................................................18 Your Assignment..............................................................................................................18 Refine the Customer Class...............................................................................................18 Create Customer objects...................................................................................................18 Refine the OrderItem Class..............................................................................................19 Refine the Order Class.....................................................................................................19 Modify OrderEntry to Associate a Customer to an Order................................................20 Exercise 7................................................................................................................................. 21 Goal..................................................................................................................................21 Your Assignment..............................................................................................................21 Modify the Customer Class..............................................................................................21 Modify the Order Class....................................................................................................21 Create the DataMan Class................................................................................................23 Modify OrderEntry to Use DataMan...............................................................................23 Exercise 8................................................................................................................................. 25 Page 1

Introduction to Java Programming Exercises Goal..................................................................................................................................25 Your Assignment..............................................................................................................25 Add Formatting Methods to the Util Class......................................................................25 Use the Util Formatting Method in the Order Class........................................................26 Use Formatting in the OrderItem Class............................................................................26 Use the Util.getDate() Method to Set the Order Date......................................................26 Exercise 9................................................................................................................................. 27 Goal..................................................................................................................................27 Your Assignment..............................................................................................................27 Part 1: Installing Eclipse...................................................................................................27 Part 2: Using Eclipse: Create a new workspace and project............................................27 Part 3: Create a Workspace and Project for the Course Application Files.......................29 Debugging Your Application Code..................................................................................30 Exercise 10............................................................................................................................... 32 Scenario............................................................................................................................32 Goal..................................................................................................................................32 Your Assignment..............................................................................................................32 Define a New Company Class..........................................................................................33 Define a New Individual Class as a Subclass of Customer..............................................34 Modify the DataMan Class to Include Company and Individual Objects........................34 Test Your New Classes in the OrderEntry Application...................................................34 Refine the Util and Customer Classes and Test Results..................................................35 Exercise 11............................................................................................................................... 37 Goal..................................................................................................................................37 Your Assignment..............................................................................................................37 Modify DataMan to Keep the Customer Objects in an Array..........................................37 Modify DataMan to Find a Customer by His or Her ID...................................................38 Modify the Order Class to Hold a List of OrderItem Objects..........................................39 Modify OrderItem to Handle Product Information..........................................................39 Modify Order to Add Products into the OrderItem List...................................................40 Modify Order to remove Products from the OrderItem List............................................41 Exercise 12............................................................................................................................... 42 Goal..................................................................................................................................42 Your Assignment..............................................................................................................42 Create an Abstract Class and Three Supporting Subclasses............................................42 Modify DataMan to Provide a List of Products and a Finder Method.............................43 Modify OrderItem to Hold Product Objects.....................................................................44 Modify Order to Add Product Objects into OrderItem....................................................44 Create and Implement the Taxable Interface....................................................................45 Exercise 13............................................................................................................................... 48 Goal..................................................................................................................................48 Your Assignment..............................................................................................................48 Create the NotFoundException Class...............................................................................48 Throw Exceptions in DataMan Find Methods and Handle Them in OrderEntry............48

Page 2

Introduction to Java Programming Exercises

Exercise 1 Goal The goal of this exercise is to install the Java Development Kit (JDK) and examine the development environment. You will set environment variables, and examine the JDK directory structure. You will then write, compile, and run a simple Java application. Finally, you will run and examine the solution application for the course.

Install the Java Development Kit (JDK) 1. Open an Explorer window and navigate to the C:\JavaCourse\installers directory. 2. Double-click the file called jdk-6u24-windows-i586.exe to install the JDK. a. Install the software into the directory C:\Java\jdk1.6.0_24. b. During the installation accept the licensing agreement. c. Install all the following five components: i.

Program files

ii.

Native Header Interface files

iii.

Old Native Header Interface files

iv.

Demonstrations

v.

Java Source

Add the JAVA_HOME and Modify the PATH Environment Variables 1. Right-click the “My Computer” icon and select the “Properties” menu item. 2. Navigate to the “Advanced” tab, and click the “Environment Variables” button. 3. Under the “System Variables” section, click “New” button. 4. Add the variable JAVA_HOME with value C:\Java\jdk1.6.0_24. 5. Locate the “Path” variable and click “Edit” button. 6. At the front, add the directory for the Java executable files: “%JAVA_HOME%\bin;” 7. Click “OK” twice to close the dialog boxes. 8. Open a “Command Prompt” window to confirm that the environment variables were correctly set. a. Select Start | All Programs | Accessories | Command Prompt b. Issue the command: set c. Check that the “JAVA_HOME” and “Path” environment variables are correctly set.

Edit and Run a Simple Java Application 1. Navigate to the C:\JavaCourse\labs\hello directory and create a file called HelloWorld.java using your favorite text editor. (If you don’t have one, you can Page 3

Introduction to Java Programming Exercises install the Crimson Editor available in the C:\JavaCourse\installers directory.) 2. In the editor, enter the following code, placing your name in the comments (after the Author: label.) Also, make sure that the case of the code text after the comments is preserved, as Java is case-sensitive: /** * File: HelloWorld.java * Author: */ public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello, World!”); } }

3. Save the file, make sure the file is called HelloWorld.java, keeping the editor running, in case compilation errors occur requiring you to edit the source to make corrections. 4. Compile the HelloWorld.java source file (file name capitalization is important.) a. In the Command Prompt, make sure the current directory is C:\JavaCourse\labs\hello. If not, issue the command: cd C:\JavaCourse\labs\hello. b. Check that the source file is there. Issue the command: dir c. Compile the file using the command: javac HelloWorld.java d. What file is created if you successfully compiled the code? 5. Run the HelloWorld application. Again, capitalization is important. a. Run the program using the command: java HelloWorld b. What was displayed in the window?

Page 4

Introduction to Java Programming Exercises

Exercise 2 Goal The goal of this exercise is to become familiar with object-oriented concepts, including classes, methods, and attributes. You will also learn how to read a UML class model showing the business objects for the course application.

Description of the Order Entry Area of the Business The Order Entry component of the business is now becoming automated. In most respects, the process of ordering products is rather simple. The customers select the items that they want from a list of products. Our customers must be included in our system. We keep information about our customers such as name, address, and telephone number. We also assign a unique customer ID to each new customer. For customers that are companies, we track a contact person and provide for a discount on company purchases. We identify individual customers by their license numbers. The order is not very complicated. Each order has a unique number that we can use to keep track of it and has information such as the customer who is responsible for the order, the order date, shipping mode (air or ground), and an order status. Each order can have multiple line items. We currently limit our customers to 10 items per order. Each item on the order has the product being purchased, the price, the quantity, and the product category. A product category can be a composite category consisting of additional categories, or a leaf category. We track many things about our products, and the key things include the name, description, and the list price. Additionally, we would like to include a warranty period, the supplier who distributes the product, a catalog URL, to reference it on the Web, and a weight classification that is used when we calculate shipping costs. It is important for use to also track information about the products on hand, and where they are located. We have many warehouses to hold all our products.

Understanding the Object-Oriented Principles 1. Define the following terms: a. Class b. Object c. Encapsulation d. Inheritance e. Polymorphism

Identifying Business Classes, Attributes, and Methods 2. Identify some of the classes in the Order Entry business, limiting yourself to three. The process of identifying a class is to look for nouns that classify a group of things from the business description. Some nouns will describe the attributes of a class. Write a simple sentence or two describing each class to make sure that it is of interest to the business. 3. Identify a few attributes for each of the new classes. Remember that attributes may be for other classes. Page 5

Introduction to Java Programming Exercises 4. Define some behaviors (methods/operations) for each of the classes that you have found. 5. Look for classes that could inherit structure (attributes) and behavior (methods) from other classes. Modify your definitions to reflect the inheritance model.

Page 6

Introduction to Java Programming Exercises

Exercise 3 Goal The goal of this exercise is to create, examine, and understand the Java code. You will create a class representing a command line application for the Order Entry system that contains the application entry point in the form of a main() method. You will use the UML model from the previous lesson as a guide to creating additional class files for your application. You will run some simple Java applications, fixing any errors that occur. You will also discriminate standard compiler errors and learn how and where to fix them.

Understanding Objects, Classes, Methods, and Attributes 1. Define the following terms: a. Instance variable b. Instance method c. Method variable

Exploring Code 2. Examine code in this HelloWorld.java class, and answer the questions that follow: public class HelloWorld { private int age; private String address; private String telephone; public int getAge() { return age; } public void setAge(int newAge) { age = newAge; } public static void showMessage(String msg) { int messageNumber = 0;

}

}

messageNumber = messageNumber + 1; System.out.println(msg + ' ' + messageNumber);

public static void main(String[] args) { showMessage("Hello, World!"); }

3. Answer the following questions for the source code: a. What is the name of the class? Page 7

Introduction to Java Programming Exercises b. List the instance (non-static) methods? c. List the instance (non-static) variables. d. Name the method variables. e. Which are the class (static) methods and variables? f. Identify method parameter names. g. Which methods return values?

Questions About the Java Development Kit 4. What Java Development Kit tool can you use to compile the HelloWorld.java file into a class file? How do you use this tool? 5. After the HelloWorld.class has been generated by the compiler, how do you run the Java application from the command prompt?

Creating Order Entry Class Files Using the UML model from the previous lesson, create class files to be used in the application. 6. At the command prompt, change your current working directory to: C:\JavaCourse\labs\OrderEntry\src\oe 7. Using the editor, create a skeleton class file for the Customer and the Order classes. Save the code in the C:\JavaCourse\labs\OrderEntry\src\oe directory in a file with the same name as the class, and a .java extension. Make the classes public. Define the attributes (instance variables.) For each attribute, create two methods, one to get the attribute value requiring a simple return statement to return the attribute, and the other to accept a parameter value to set the attribute but leave the method body empty. Note: Use the Customer example shown later and the UML model created previously as a guide. a. At the command prompt, change the directory to C:\JavaCourse\labs\OrderEntry\src\oe b. Create the Customer.java file c. Ensure that the first line of the file contains the text: package oe; d. Save the file, and compile it by using the following command as a guide: javac -d C:\JavaCourse\labs\OrderEntry\bin Customer.java

Page 8

Introduction to Java Programming Exercises e. Where is the compiled .class file created? f. Repeat steps (b) to (d) for the Order.java file Sample Customer.java file: package oe; public class Customer { int id; String name; String address; String phone;

}

public public public public

void void void void

setId(int newId) { } setName(String newName) { } setAddress(String newAddress) { } setPhone(String newPhone) { }

public public public public

int getId() { return id; } String getName() { return name; } String getAddress() { return address; } String getPhone() { return phone; }

Sample Order.java file: package oe; public class Order { int id; String orderDate; String shipDate; String shipMode; double orderTotal;

}

public public public public public

void void void void void

setId(int newId) { } setOrderDate(String newOrderDate) { } setShipDate(String newShipDate) { } setShipMode(String newShipMode) { } setOrderTotal(double newOrderTotal) { }

public public public public public

int getId() { return id; } String getOrderDate() { return orderDate; } String getShipDate() { return shipDate; } String getShipMode() { return shipMode; } double getOrderTotal() { return orderTotal; }

Create and Compile the Application Class with a main() Method 8. Create a file called OrderEntry.java containing the main method, as shown below. Place the source file in the same source directory as all the other source files. This file is a skeleton that will be used for launching the course application. package oe; public class OrderEntry { public static void main(String[] args) { System.out.println("Order Entry Application"); } }

9. Save and compile OrderEntry.java with the following command: Page 9

Introduction to Java Programming Exercises

javac -d C:\JavaCourse\labs\OrderEntry\bin OrderEntry.java

10. Running the skeleton application: a. Execute the OrderEntry class file, as follows and explain the result: java OrderEntry

b. Modify the CLASSPATH to include the application classes directory, and enter the following command: set CLASSPATH=C:\JavaCourse\labs\OrderEntry\bin

c. Run the application again as in step (a). Explain the result. d. Finally, run the application but prefix the class name with its package name oe and a dot, as follows, and then explain the result: java oe.OrderEntry

Page 10

Introduction to Java Programming Exercises

Exercise 4 Goal The goal of this exercise is to declare and initialize variables, and use them with operators to calculate new values. You will also be able to categorize the primitive data types and use them in code, and learn how to modularize code in methods. The business area for this exercise is the Order class and a new supporting class called OrderItem, showcasing some basic collaboration to assist with computations for the order total.

Your Assignment You will create the OrderItem class to declare instance variables to hold the item line number, quantity, and costs. You also create the methods to get and set the OrderItem values and calculate the item total. You then modify the Order class to contain two OrderItems, set the item details, and then determine the sum of the item totals to calculate the order total. Finally, you use the main() method in the OrderEntry class to test your code by creating an Order and determining the order total, to which you add a tax amount to form the final order total.

Create the OrderItem Class 1. In the C:\JavaCourse\labs\OrderEntry\src\oe directory, using the editor, create the file called OrderItem.java. a. Make the first line of the class include the following: package oe;

b. Declare the following instance variables in the class: int lineNo; int quantity; double unitPrice;

c. Create a public get and set method for each of the instance variables, for example: public int getLineNo() { return lineNo; } public void setLineNo(int newLineNo) { lineNo = newLineNo; }

d. Create a method to return the item total based on the quantity multiplied by the price, by using the following signature: public double getItemTotal() { return ; }

e. Save the class and compile by using the following command: javac -d ..\..\bin OrderItem.java

Modify the Order Class You will now associate the Order and OrderItem by declaring instance variables for two items in the Order class. The data type for item variables is the class name OrderItem, showing you how a class name is used for variable data type declarations. This is analogous to the concept of using User-Defined Types (UDT). You will also complete the Page 11

Introduction to Java Programming Exercises getOrderTotal() method in the Order class to return the sum of the items. 2. In the Order class, declare two item instance variables as follows: OrderItem item1 = new OrderItem(); OrderItem item2 = new OrderItem();

This creates two OrderItem objects. You will learn the significance of the new keyword in a subsequent lesson. For now, just accept that these are needed for the task. 3. Modify the method called getOrderTotal() to add the item totals to the orderTotal. The steps (a) through (d) guide you through this process. a. Declare two local variables called item1Total and item2Total, both of type double, to hold the item totals, respectively. b. Set the line number, price, and the quantity for each item object, by calling its methods, according to the following table: Item item1 item2

lineNo 1 2

quantity 2 2

unitPrice 2.95 3.50

For example: item1.setLineNo(1); item1.setQuantity(2); item1.setUnitPrice(2.95);

c. Set each item total variables by calling the getItemTotal() method for each item variable, and display the item total as shown in the example: item1Total = item1.getItemTotal(); System.out.println("Item 1 total: " + item1Total);

d. Add the two item totals and store the result in the orderTotal before it is returned from the method. Just use the orderTotal variable as itself as it is declared in the Order class. e. Save and compile the Order class.

Modify the main() Method in the OrderEntry Class Modify the OrderEntry class to create an Order variable, and then request its total to be saved in a variable. Then calculate a tax on the total and it to the order total. Set a Boolean variable if the final total price (including the tax) exceeds a limit of $10.00. 4. Declare and create an Order object, and declare variables to hold the total order, a Boolean to test if the order exceeded a limit, and a variable for the tax rate. a. Declare the Order object variable as follows: Order order = new Order();

b. Declare a variable of type double to hold the order total. c. Declare a Boolean variable to track if the purchase exceeds the $10.00 limit. d. Declare and initialize another variable to hold an 8.25% tax rate. e. Declare a variable to hold the tax value. Page 12

Introduction to Java Programming Exercises 5. Determine the order total. a. Call the Order object’s getOrderTotal() method and store the result in the variable that is declared to hold its value. b. Display the order total before tax is added, by using the System.out.println() technique to display the contents of your variable. c. Calculate the tax of the order total and store in the tax value variable. Display the tax value calculated. d. Add the tax to the order total, and print the value. e. Set the Boolean variable, by using the relational and logical operators, to determine if the total cost exceeds the limit of $10.00 and print its Boolean value. Do not use any type of if statement in this step. 6. Save and compile OrderEntry. Test your logic by running the OrderEntry class.

Page 13

Introduction to Java Programming Exercises

Exercise 5 Goal The goal of this exercise is to make use of flow control constructs in a new class, called Util that provides methods to determine the number of days in a month, and handle leap years. Then you modify the Order class to set the order date and derive an expected ship date based on a shipping location.

Your Assignment In this exercise, you create the Util class to contain methods to check if a year is a leap year, and then determine the number of days in a month for a given year, handle leap years, and return the number of days to ship an order to a specified region. The Order class will be modified to set the order date and have a new method added called getShipDate(). Determine the ship date for the order, based on the day it was ordered and how many days it takes for shipping.

Create the Util Class 1. Create the Util class in the C:\JavaCourse\labs\OrderEntry\src\oe directory, and make sure that the first line ensures that the class is grouped in the oe package. a. Add a public static method called isLeapYear() that accepts a year integer parameter, and return a true Boolean value if it is a leap year, otherwise return false. Use the Boolean operations && and || in a statement that returns true if the year is a leap year according to the following rule: it is divisible by 4, and it is either not divisible by 100, or it is divisible by 400 b. Now add main() method to the class by using the following text: public static void main(String[] args) { }

c. Add the code to the main() method to test your leap year method as follows: int year = 1900; System.out.println("Year: " + year + " leap year? " + isLeapYear(year));

Check the results for the following years: 1900, 1964, 1967, 1984, 1996, 1997, 2000, and 2001. The leap years from the list are: 1964, 1984, 1996, and 2000. d. Save, compile, and test your code: javac –d ..\..\bin Util.java java oe.Util

2. Add another public static method to Util class called lastDayInMonth() that returns the number of days in the months, for a specified month and year. a. Declare the parameters and return values as integers. In the method body, use a switch statement on the month, remembering how many days are in each month with this reminder (if you need it): Page 14

Introduction to Java Programming Exercises “There are 30 days in September, April, June, and November. All the rest are 31, except for February, which has 28 or 29 if it is a leap year.” Note: Handle leap years by making use of the isLeapYear() method. Return a zero if the month is invalid. b. Add code in the main() method to test your method by declaring two integer variables to hold a day and month in addition to the year (for example: 27 January 2002). Then print the date, using System.out.println(), in D/M/Y format looking like: Date is: 27/1/2002 (and has 31 days in the month)

Repeat this test by using the date 20 February 2000. c. Save, compile, and run the Util class (as shown in step 1(d)). d. What happens if you choose the month with an invalid value, such as 13? 3. Write a public static method called getDaysToShip() that returns an integer representing the number of days to ship an order to a specified region. a. The region is supplied as a single case-sensitive character argument. Use a switch statement and the following table as your guide: Region Americas Europe/Africa Asia pacific

Character 'A' 'E' 'P'

Days to Ship 3 5 7

b. Modify the main method to declare and set a variable to hold the number of days to ship an order to a specified location to test the method, for example: int daysToShip = getDaysToShip('A');

Print the results. c. Save, compile, and run the Util class (as shown in step 1(d)). 4. Add a loop to the main() method of the Util class that starts at a specific order date and prints all the dates to the end of the month. Use the date: 27 January 2002. a. Use the day, month, and year variables that were previously declared to initialize the date and set the number of days in the month. b. Write the loop to print the date in D/M/Y format starting at the specified day and ending at the last day of the month. For example: 27/1/2002 28/1/2002 29/1/2002 30/1/2002 31/1/2002

c. Modify the loop to terminate either at the last day of the month, or at the day representing the ship date for a region of Americas ('A'). Terminate the loop at the earliest of date that occurs first. The output should produce the following results: 27/1/2002 28/1/2002 29/1/2002

Page 15

Introduction to Java Programming Exercises d. Compile and run the code. e. Test the example for the other regions, ‘E’ for Europe/Africa, and ‘P’ for Asia Pacific. Alter the start date to 10 February 2002 or any day that you like.

Modify the Order Class Modify the Order class to set the order date by using the setOrderDate() method, subject to some date validation. You also write a new method called getShipDate() to calculate the shipping date based on a character argument specifying the region to ship the order. In the solution to the ship date problem, you must handle the case if the expected ship period extends beyond the current month. For example, if the order date is 29 August and the shipping will take three days, the expected ship date should be 1 September. Therefore, • •

If the ship period crosses over to a new month, then increment the month. Also check if the ship period crosses over to a new year, and increment the year.

5. Modify the setOrderDate() method to accept three integer parameters for a day, month, and year (instead of a single string parameter) to set the order date. a. To store the date values comment out orderDate instance variable, and declare three integer instance variables to hold the order day, month, and year. b. In the setOrderDate() method, initialize the order day, month, and year to zero to indicate that it is invalid. Before setting these values based on the parameters perform the following validation checks: i.

The day is between 1 and the last day of the month (inclusive). Use the Util.lastDayInMonth() method to help with this test as follows: int daysInMonth; daysInMonth = Util.lastDayInMonth(month, year);

For now, accept that this is how you call a static method in a class. A subsequent lesson in the course will discuss this technique more formally. ii.

The month is from 1 to 12 (inclusive).

iii.

The year is not less than 1.

c. Modify the getOrderDate() method to return the date string set in D/M/Y format. d. In the Order class, add a method to return the ship date as a string in D/M/Y format. The method uses the day, month, and year instance variable in the Order class, and a character parameter representing the region to ship the order to, to determine the ship date. Use the following method signature: public String getShipDate(char region) { int daysToShip = Util.getDaysToShip(region); … }

The code above shows how to use the Util.getDaysToShip() method to determine the number of days that are required to ship the order to the specified region. To calculate the date of expected shipping: Page 16

i.

Introduction to Java Programming Exercises Declare three method variables to hold the due date (dueDay, dueMonth, dueYear).

ii.

Initialize dueDay to the order date plus the days to ship order, dueMonth and dueYear to the order month and year respectively.

iii.

If the dueDay is beyond the end of the month, then adjust the dueDay and dueMonth appropriately. If the adjusted dueMonth indicates a change of year, then alter the dueMonth and dueYear appropriately.

iv.

Return the result string formed by concatenating the due day, month, and year in D/M/Y format.

e. Save and compile the Order class.

Test the Code by Using the OrderEntry Class You finally modify the OrderEntry class, which contains an order to test the changes that are made to the Order class. You must set an order date, print the date, and determine the ship date for one or more locations. 6. Modify the OrderEntry class in C:\JavaCourse\labs\OrderEntry\src\oe. a. Before the end of the main() method, after existing code, set the order date by calling the order.setOrderDate() method. Set the date to 27 January 2001. b. Declare a character variable called region for the shipping region and set it to 'A'. c. Declare a String variable for the ship date, and assign it the value that is returned from the order.getShipDate() method, passing the region variable as the argument. d. Use the System.out.println() method to display your original order date, and the due date string, and the number of days to ship for the region. The output should look something like: Order Date: Days till Shipping: Expected Ship Date:

27/1/2001 3 30/1/2001

e. Save, compile, and run the OrderEntry class. f. Test the ship date calculation by using an order date of 27 February 2001. g. Try changing the region to ‘E’ and/or ‘P’ to check the results for the ship date.

Page 17

Introduction to Java Programming Exercises

Exercise 6 Goal The goal of this exercise is to complete the basic functionality for existing method bodies of the Customer, Order, and OrderItem classes. You will then create customer and order objects, and manipulate them by using their public instance methods. You display the Customer and Order information back to a command prompt.

Your Assignment In this exercise, you begin refining the application for the Order Processing business area. These classes continue to form the basis for the rest of the application that you are building for the remainder of the course. After creating one or more Customer objects, you will associate a customer with an order. This will require changes to the Order class.

Refine the Customer Class 1. In the C:\JavaCourse\labs\OrderEntry\src\oe directory, edit the Customer.java file. a. Make all instance variables private. b. Complete the public instance methods whose names have the form setXXX() for each of its attributes in turn. c. Check that the getXXX() methods return their appropriate attribute values. d. Note: The naming convention such as setId(), getName(), and so on for these methods makes the classes more intuitive and easier to use. 2. At the moment, there is no way to display most or all details for a Customer object by calling one method. a. To cover this deficiency, add a new public method called toString() to the class, without parameters and returning a String containing the customer’s ID, name, address, and phone. The resultant string should be a simple concatenation of the attributes that you want to display. For example: public String toString() { return property1 + " " + property2; }

Note: The toString() method is a special method that is called any time a String representation of an object is needed. The toString() method is very useful to add to any class, and thus it is added to almost all the classes that you create. b. Save the Customer class, and compile to remove any syntax errors by using: javac –d ..\..\bin Customer.java

Create Customer objects 3. You now modify the main() method in the OrderEntry class to create two customer objects. a. In the main() method of OrderEntry.java, create two customer objects by Page 18

Introduction to Java Programming Exercises using the new operator, assigning each one to a different object reference (use customer1 and customer2). b. At the end of the main() method, initialize the state of each Customer object by calling its public setXXX() methods to set the ID, name, address, and phone. Use the table data below: Id 1 2

Name Gary Williams Lynn Munsinger

Address Houston, TX Orlando, FL

Phone 713.555.8765 407.695.2210

c. Print the two customer objects created, under a printed heading of “Customers:” by calling the toString() method inside the argument of the System.out.println() method, for example: System.out.println("\nCustomers:"); System.out.println(customer1.toString()); …

Note: Alternatively, you can just print the customer object reference variable to achieve the same result. For example: System.out.println(customer1);

This latter technique is a feature of Java that is discussed in a subsequent lesson. d. Save the OrderEntry class, compile, and run the class to view the results.

Refine the OrderItem Class 4. Apply the encapsulation principles to the OrderItem class, and add a method to display the attributes of the OrderItem. a. Edit the OrderItem class and make each instance variable private. b. Add the public String toString() method to the OrderItem class that returns a concatenated string of its attributes lineNo, quantity, and unitPrice. Precede the unitPrice with a dollar symbol ($). c. Save the OrderItem class, and compile.

Refine the Order Class Here you complete the setXXX() methods in the Order classes, and add the association to a customer object. 5. Edit the Order class and complete the setId(), setShipMode(), setOrderTotal(), and setShipDate() method. a. In each method, assign the value of the argument to the appropriate instance variable. Also make each instance variable of the Order class private. b. Add a private instance variable named customer with data type based on the Customer class, write a method called setCustomer() to associate a customer instance to the customer variable, and write a method called getCustomer() to return the customer value. c. Add a public String toString() method to print the order ID, order date, and order total (hint: use the getOrderTotal() method). Use the following format: Order #: 1

Date: 27/2/2001

Page 19

Total: $13.96425

Introduction to Java Programming Exercises d. Add a public void showOrder() method with no arguments to display the details of the order. The first line of output should show the order details, by calling the toString() method from step 5(c). Then show the customer details followed by the two item details in the order. Check if the customer and items are associated to objects, for example: if (item1 != null) System.out.println(item1.toString());

Note: In the getOrderTotal() method, convert these lines into comments: System.out.println("Item 1 Total: " + item1Total); System.out.println("Item 2 Total: " + item2Total);

e. Save the changes to Order class and compile the class.

Modify OrderEntry to Associate a Customer to an Order 6. In the main() method of the OrderEntry class, associate one of the customer objects with the order object, and display the order details. a. Call the setCustomer() method of the order object passing in the object reference of customer1 (or customer2). b. After setting the customer, call the showOrder() method of the order object. c. Save, compile, and run the OrderEntry class.

Page 20

Introduction to Java Programming Exercises

Exercise 7 Goal The goal of this exercise is to gain experience with creating and using constructors, class methods, and attributes. You will also create a new class called DataMan that will be used to provide a data access layer for finding customers and products in the OrderEntry application. Part of the exercise is to understand method overloading by creating more than one constructor and/or method with the same name in the same class.

Your Assignment Create at least one or more suitable constructors to properly initialize the Customer and Order objects when instantiated. Create the DataMan class to provide class (static) attributes of customer objects to be used by the OrderEntry application when it associates a customer object to an order.

Modify the Customer Class The Customer class will have two constructors: 1. Create a no-arg constructor to provide default initialization, and another constructor to set the actual name, address, and phone properties. The no-arg constructor will be invoked by the second constructor. a. Add a no-arg constructor to the Customer class, which is used to generate the next unique ID for the customer object by first declaring a class variable, called nextCustomerId, as a private static integer initialized to zero. b. In the no-arg constructor, increment nextCustomerId, and use the setId() method with nextCustomerId to set the ID of the customer. c. Add a second constructor that accepts a name, address, and phone as String arguments. This constructor should set the corresponding properties to these values. d. In the first line of the second constructor, chain it to the first constructor by invoking the no-arg constructor by using the this() keyword. This is done to ensure that the ID of a customer is always set regardless of the constructor used. e. Save and compile the class: javac -d ..\..\bin Customer.java

f. Modify the OrderEntry class and simplify the creation of customer1 and customer2 object by using the second constructor of the customer (with three arguments). Remove (or comment out) all calls to setXXX() methods made with the customer1 and customer2 object references. Remember: The constructor allocates the customer ID. g. Save, compile, and run the OrderEntry class to check the results.

Modify the Order Class The Order class will also have two constructors: Page 21

Introduction to Java Programming Exercises 2. First change the way in which you manage the order date information. a. Uncomment the orderDate variable that had been commented out in an earlier exercise, and make it a private variable. b. After the package statement at the top of the class, add the following import statements (before the class declaration): import java.util.Date; import java.util.Calendar;

c. Redefine the orderDate type to be Date instead of String, and remove the three integer variables day, month, year that are replaced by orderDate. 3. Alter the methods that depend on the three integer date variables to use orderDate. a. Replace the return type and value of the getOrderDate() method as follows: public Date getOrderDate() { return orderDate; }

In addition, create an overloaded void setOrderDate() method that accepts a Date as its parameter and sets the orderDate variable accordingly. b. Change the getShipDate() method to use the Calendar class to calculate the ship date. Replace the body of getShipDate() with the following code: int daysToShip = Util.getDaysToShip(region); Calendar c = Calendar.getInstance(); c.setTime(orderDate); c.add(Calendar.DAY_OF_MONTH, daysToShip); return c.getTime().toString();

c. Alter the setOrderDate() method body to set the orderDate by using the Calendar class methods, using the three input parameters. First, delete the following date initialization code: day = 0; month = 0; year = 0;

d. Also in the setOrderDate() method, replace the following three bold lines or code: if ((m > 0 && m 0)) { day = d; month = m; year = y; }

with these three lines of code: Calendar c = Calendar.getInstance(); c.set(y, m - 1, d); orderDate = c.getTime();

Note: You must subtract one from the method’s month argument, because the Java Calendar class starts numbering months from 0 for January through 11 for December. Consult the Java API documentation for details of the methods that are used in the Calendar class. 4. Create a no-arg constructor to initialize the order number, date, and total. Page 22

Introduction to Java Programming Exercises a. Create a class (private static int) variable called nextOrderId and initialize it to 100 (representing the starting number for order IDs.) b. In the no-arg constructor, set the ID of the order to the value in nextOrderId. Then increment nextOrderId. Set the orderTotal to 0. Set the orderDate as follows: orderDate = new Date();

c. Create a second constructor that accepts an order date argument as a Date, and a ship mode as a String. Call the no-arg constructor from this constructor and use the orderDate and shipMode instance variable using the arguments. d. Update the toString() method to include the shipMode in the return value if it is not null. e. Save and compile the Order class, and run the OrderEntry class to verify that the code still runs unchanged but picks up the changes to the order. f. In OrderEntry create another order with the second Order constructor passing a java.util.Date object and “overnight” ship mode as parameters. Set the order customer to customer2 and print the details. Recompile and run OrderEntry.

Create the DataMan Class The DataMan class is used to create the data that will be used to test the application. To start, you will create the customer objects, and later modify them to maintain the product lists that are available for ordering. This class is really a convenience class that simplifies our application testing. However, after this class is completed, it can be changed to retrieve data from a database of the system without impacting our application. 5. Using the editor, create a new file called DataMan.java in the directory called C:\JavaCourse\labs\OrderEntry\src\oe. The class should not contain constructors. a. Ensure that the class belongs to the oe package. b. Create several new Customer objects as static (class) variables. To save time, copy and paste the two existing Customer objects from the main() method in the OrderEntry.java file. The code in DataMan should look like: static Customer customer1 = new Customer(“Gary Williams”, …); static Customer customer2 = new Customer(“Lynn Munsinger”, …);

Add a couple of customer objects of your own creation, calling the variables customer3 and customer4 respectively. c. Save and compile the DataMan.java class as follows: javac -d ..\..\bin DataMan.java

Modify OrderEntry to Use DataMan 6. Modify the main() method in OrderEntry to use customer objects from the DataMan class. a. Use the class name “DataMan.” as the prefix to all customer reference variables Page 23

Introduction to Java Programming Exercises customer1 and customer2. For example, change the code: order.setCustomer(customer1);

to become: order.setCustomer(DataMan.customer1);

Note: You are accessing a class variable using its class name; that is, there is no need to create a DataMan object. In addition, the customer variables in DataMan are visible to OrderEntry because they have default (package) access. b. Save, compile, and run the OrderEntry class to test if the code still works. Replace customer1 with customer3 or customer4 from DataMan to confirm that your code is using the customer objects from DataMan.

Page 24

Introduction to Java Programming Exercises

Exercise 8 Goal The goal of this exercise is to modify the Util class to provide generic methods to support formatting the order details, such as, presenting the total as a currency and controlling the date string format that is displayed. This should give you exposure in using some of the java.text formatting classes.

Your Assignment You will create a method called toMoney() to return a currency formatted string for the order total. You will also create a method called toDateString() that formats the date in a particular way. You will then modify the Order class to use these methods to alter display of order details, such as, the order date and total.

Add Formatting Methods to the Util Class 1. Create a static method called toMoney() that accepts an amount as a double and returns a String. a. Add the following import statement to the class: import java.text.DecimalFormat;

b. Add the following toMoney() method to the class, to format a double: public static String toMoney(double amount) { DecimalFormat df = new DecimalFormat("$###,###.00"); return df.format(amount); }

c. Save and compile the Util class. 2. Add a static toDateString() method to format a date: a. Add the following import statements to the class: import java.util.Date; import java.text.SimpleDateFormat;

b. Use the following code for your method: public static String toDateString(Date d) { SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy"); return df.format(d); }

c. Save and compile the Util class. 3. Create another static method called getDate() that accepts three integers representing the day, month, and year, and returns a java.util.Date object representing the specified date (month = 1 represents January on input.) Because many methods in the Date class that could have been used are deprecated, you use the GregorianCalendar class to assist you with this task. a. Import the java.util.GregorianCalendar class. b. Use the following for the method: public static Date getDate(int day, int month, int year) {

Page 25

Introduction to Java Programming Exercises

}

// Decrement month, Java interprets January as 0. GregorianCalendar gc = new GregorianCalendar(year, --month, day); return gc.getTime();

c. Save and compile the Util class.

Use the Util Formatting Method in the Order Class 4. In the Order class, modify the toString() method to use the Util class methods toMoney() and toDateString() to alter the display formats. a. In the toString() method, replace the return value with the following text: return "Order: " + id + " Date: " + Util.toDateString(orderDate) + " Shipped: " + shipMode + " (" + Util.toMoney(getOrderTotal()) + ')';

b. Save and compile the Order class, and then run the OrderEntry class to view the changes to the displayed order details. c. Now import the java.text.MessageFormat class and use this class to format the toString() return value, as follows: Object[] msgVals = {new Integer(id), Util.toDateString(orderDate), shipMode, Util.toMoney(getOrderTotal())}; return MessageFormat.format("Order: {0} Date: {1} " + "Shipped: {2} (Total: {3})", msgVals);

d. Save and compile the Order class, and then run the OrderEntry class to view the results of displayed order. The change to the displayed total should appear.

Use Formatting in the OrderItem Class 5. In the OrderItem class, modify the toString() method to use the Util.toMoney() method to alter the display format of item total. a. In the toString() method, replace the return statement with the following: return lineNo + " " + quantity + " " + Util.toMoney(unitPrice);

b. Save and compile the OrderItem class, and then run the OrderEntry class to view the changes to the order item total.

Use the Util.getDate() Method to Set the Order Date 6. In the OrderEntry class, alter the second order object creation statement to use the Util.getDate() method to provide the value for the first argument in the constructor. Choose the previous day’s date for the values of the day, month, and year arguments supplied to the Util.getDate() method. a. The call to the constructor should look like: Order order2 = new Order(Util.getDate(7, 3, 2002), "overnight");

b. Save, compile, and run the OrderEntry class to confirm that the order date has been set correctly. Page 26

Introduction to Java Programming Exercises

Exercise 9 Goal In this exercise, you explore using the Eclipse IDE to create a workspace and project to manage your Java files during the development process. You practice how to create one or more Java applications and classes by using the rapid code generation features, such as, the code editor and debugger.

Your Assignment •

In part 1, you install Eclipse and create a shortcut to the Eclipse executable in order to make it easy to start the Eclipse workbench.



In part 2, you explore Eclipse default rapid code generation features by creating a new workspace, and then create a Java project which will contain a simple command line application.



In part 3, you create a workspace called OrderEntry that will hold a single project called OrderEntry that will contain the course application Java files. You run the application and test it by using the debugger.

Part 1: Installing Eclipse Install Eclipse and create a shortcut icon on the Windows Desktop. 1. Install the Java 6 SDK. a. Double-click the file jdk-6u24-windows-i586.exe in the C:\JavaCourse\installers directory. b. Install the software into the directory C:\Java\jdk1.6.0_24. c. Update the WINDOWS environment variable JAVA_HOME to the above directory. 2. Install the WinRAR application. a. Double-click the file wrar380.exe in the C:\JavaCourse\installers directory. 3. Install the Eclipse workbench. a. In the C:\JavaCourse\installers directory, right-click on the file eclipse-java-helios-win32.zip and select “Extract files…” b. For the destination path, enter (or browse to) C:\Java, and press OK. 4. Create the Eclipse shortcut on the Desktop. a. Using the Windows Explorer, navigate to the folder C:\Java\eclipse. b. Right-click on the file eclipse.exe and select “Create Shortcut”. c. Rename the resulting shortcut to “Eclipse” and cut-and-paste it to the Desktop.

Part 2: Using Eclipse: Create a new workspace and project Launch Eclipse from the desktop icon just created, or ask your instructor for instructions on Page 27

Introduction to Java Programming Exercises how to start Eclipse. 4. Launch Eclipse using a new workspace and create a new project. a. Double-click the Eclipse icon. The Workspace Launcher dialog box is displayed. This dialog allows you to create a new workspace or open to an existing workspace. Since we have not created any workspace before, enter C:\JavaCourse\workspaces\Hello and press OK. b. Eclipse will restart with the new workspace created. Click the right-most icon (named Workbench) on the Welcome screen to show the workbench. If the title of the Eclipse window is “Java EE”, select Window | Open Perspective | Java. We will be working with plain Java applications and not Java Enterprise Edition (Java EE) in this course. Eclipse supports multiple perspectives depending on what you are working on. Each perspective will show the most common views for that particular task. c. The first thing to do is to create a new Java project. Select File | New | Java Project. Alternatively, you can click the New Java Project button on the toolbar (an open folder with a blue J on it.) d. When the New Java Project dialog box is displayed, you will notice the following items to be entered and selected (leave each in their default states): the project name, where to store the contents, the JRE to use, and the project layout (whether to put the source and class files together or separately.) e. Enter the project name as Hello and press Finish. f. In the Package Explorer view, you will see the new project named Hello listed. Expand the project by clicking the plus sign to the left of the project name. You will see a folder called src displayed. This is where all Java source files are kept. There is also a bin folder created but Eclipse hides it. This is where the compiled .class files are stored. You can use the Windows Explorer to check that the folder is really there. 5. Create a new command line application. g. Click the Hello project on the Package Explorer if it is not already highlighted. Select File | New | Class to display the New Java Class dialog box. Alternatively, you can click the New Java Class button on the toolbar (a white C in a green circle.) You can also right-click on the project name and select New | Class. h. The New Java Class dialog box opens up. You can see that the Source folder has been entered for you. Leave the Package empty for now. Enter the class name (remember that a class name must start with a capital letter) as Application1. Click the checkbox labeled “public static void main(…)” to let Eclipse automatically create the main() method for the class. Press Finish. i. Eclipse creates a source file called Application1.java which appears under default package on the Package Explorer view. The generated source code for the new class should be visible in an editor window. j. In the editor window, in the main() method, delete the line starting with “// TODO” and enter the following code: System.out.println("Hello Eclipse World!");

Page 28

Introduction to Java Programming Exercises k. If you look at the file name on the tab at the top of the editor window, you can see an asterisk to the left of the name. This means the file have been changed but not saved. Save you work by right-clicking anywhere in the source window and selecting Save. You can also press CTRL+S. Eclipse will save and automatically compile the source file and will highlight any errors at the appropriate places in the source window. Where exactly is the file created and explain your observations? l. Run the application by either selecting Run | Run As | Java Application menu item, or right-clicking the Application1.java and choosing Run As | Java Application. m. Eclipse automatically opens a Console view showing the results of the execution of the application. Where are the .class files, and what command did Eclipse use to run the application code?

Part 3: Create a Workspace and Project for the Course Application Files In this part of the exercises, you create a new workspace. Then you create a project in the workspace and at the same time populate the project with the Java files that you created in the previous lessons. 6. Create a new empty workspace called OrderEntry. a. Select File | Switch workspace | Other… b. Change the workspace directory name to be C:\JavaCourse\workspaces\OrderEntry. c. Click OK to create the workspace directory. d. Select Window | Preferences | Java | Compiler and set the “Compiler compliance level:” to 1.4. Click OK to close the dialog box. 7. Create a new project called OrderEntry in the new workspace and populate the project with the existing Java files in C:\JavaCourse\labs\OrderEntry\src. a. Select File | New | Java Project menu item. (Or click the New Java Project button on the toolbar.) Enter the project name as OrderEntry and click Finish. b. Expand the OrderEntry project in the Package Explorer view. Right-click on the src folder and select Import… c. In the Import dialog box, expand General and click File System. This means we are importing files directly from the Windows file system. You can also import from an existing Eclipse project in another workspace or even from a JAR or ZIP file (Archive File). Click Next. d. In the resulting Import dialog box, browse to C:\JavaCourse\labs\OrderEntry\src. Make sure you select the src folder and not oe. Click OK to close and redisplay the Import dialog box. e. In the left pane, expand the src folder and click on the oe folder under it. You should see the list of .java files listed in the right pane. Click the Select All button to select all the .java files listed. Click Finish. Page 29

Introduction to Java Programming Exercises f. In the Package Explorer, expand the Order Entry project, the src folder and the oe package. Confirm that all the files have been imported. If any of your files have errors in them, Eclipse will mark them with an error symbol (small red box with a white X in it.) g. Fix all the errors if any. You can edit each .java file by double-clicking the name on the package Explorer view. Make sure there are no error markers around. h. Run the OrderEntry application by either selecting Run | Run As | Java Application menu item, or right-clicking the OrderEntry.java and choosing Run As | Java Application. View the output results in the Console view.

Debugging Your Application Code 8. Run the OrderEntry application in Debug mode. a. Open the OrderEntry.java file in the code editor, by double-clicking the file name, or right-clicking the file name and choosing Open or pressing F3 while the file name is selected. b. Set a breakpoint on the following line that prints the Customer heading: System.out.println("\nCustomers:");

Note: To set the breakpoint on this line, double-click on the graded bar to the left of the line until a green dot appears on the margin. c. Set two more breakpoints, one on the line associating a DataMan customer object to the first order, and another on the line that is calling the method to show the second order details: order2.showOrder(). d. In the Package Explorer, select the OrderEntry.java, right-click, and select Debug As | Java Application. The dialog box Confirm Perspective Switch pops up. Click the checkbox “Remember my decision” and press “Yes”. e. Eclipse opens the Debug perspective with five open views: Debug, Variables, Editor (OrderEntry.java), Outline, and Console. The execution of the code stops at your first breakpoint, as indicated by the highlighted line in the Editor view. The highlighted line indicates the next line to be executed when you resume debugging. The Debug view shows the exact point in the main() method where execution stops (line X). The Variables view shows the current values of all the variables in scope. The Breakpoints view shows all the breakpoints in the current source file. (You need to click the Breakpoints tab.) The Console view displays the output results that are generated by the application (so far.) f. In the Debug view, press the Resume (F8) button on the toolbar (or select Run | Resume menu item.) The highlight in the Editor view advances and highlights the line with the next breakpoint that is detected in the code execution sequence. g. Click the Variables tab if the view is not visible, since it is sharing the same window as the Breakpoints view. h. Locate the order variable in the Variables view, expand it, and find the customer instance variable of the order. What is its current value? i. Click the Step Over (F6) button on the toolbar (or select Run | Step Over menu Page 30

Introduction to Java Programming Exercises item) to execute the order.setCustomer() method. Note that the changes to the order customer instance variable in the Variables view. Expand the customer instance variable to examine its contents. j. The highlighted line should now point to the line to display the first order’s details; that is, order.showOrder(). Click the Step Into (F5) button on the toolbar (or select Run | Step Into menu item.) Eclipse displays the highlight on the first line of the showOrder() method of the Order class. k. Expand the this variable. Press F6 (Step Over) for a few lines noticing the results being displayed in the Variables view (and the Console view.) l. Then step out of the method by choosing the Run | Step Return (or press F7 (Step Return), or click the toolbar icon.) Eclipse returns control to the main() method on the next executable line following the call to the order.showOrder() method. m. Continue selecting the Run | Resume menu (F8 key or click the toolbar button) until the program is completed (the Debug view says OrderEntry [JavaApplication].) n. Remove the breakpoints from the OrderEntry.java source, by doubleclicking each breakpoint entry (green dot) in the margin for each line with a breakpoint. o. Switch back to the Java perspective by selecting Window | Open Perspective | Java or clicking the Java Perspective button on the toolbar at the upper right corner of the Eclipse workbench.

Page 31

Introduction to Java Programming Exercises

Exercise 10 Scenario In this exercise, you add a couple of new classes as subclasses. The new classes that are added are Company and Individual and they inherit from the Customer class. Here is a UML class diagram to show the relationship between Customer, Company, and Individual. Each box represents a class. The name of the class appears at the top of each box. The middle section specifies the attributes in the class, where underlined attributes represent class variables. The lower section specifies the methods in the class. Notice the arrow on the line connecting Company and Individual to Customer. This is the UML notation for inheritance.

Goal The goal of this exercise is to understand how to create subclasses in Java, and use polymorphism with inheritance through the Company and Individual subclasses of the Customer class. Refine the subclasses and override some methods and add some new attributes, making use of the Class Editor in Eclipse.

Your Assignment Add two classes, Company and Individual, which inherit from Customer. The owners of Acme Video have decided to expand their business and begin selling to companies as well as individuals. Because companies have slightly different attributes than individuals, you Page 32

Introduction to Java Programming Exercises have decided to create subclasses for each of these types of items. Each of the items will have a few of their own methods and will override the toString() method of Customer. In Eclipse, continue to use your workspace and project (OrderEntry) from the previous exercise containing the files from the previous exercises,

Define a New Company Class 1. Define a Company class, which extends Customer, and includes the attributes and methods that are defined in the object model on the first page of this exercise. a. Right-click on the package oe and select New | Class. b. In the New Java Class dialog box, enter Company in the Name field, and then click the Browse button to the right of the Superclass field. Type cus and see the matching list reduced. Select Customer - oe and press OK. c. In the Editor window for Company.java, enter the following private attributes: private String contact; private int discount;

d. Save the file. e. In the Outline view, right-click on the Company and select Source | Generate Getters and Setters… f. In the Generate Getters and Setters dialog box, select both attributes and click OK. Notice that the getters and setters for the attributes are now in the source file. 2. Alter the Company constructor to have arguments. a. Add the following constructor with arguments: public Company(String name, String address, String phone, String contact, int discount) {… }

You can manually enter the constructor skeleton to the class, or use Eclipse to generate the constructor as described in step 2(c). Skip step 2(c) if you manually enter the code. b. Use the arguments to initialize the object state (including the superclass state). Hint: Use the super(…) syntax to pass values to an appropriate superclass constructor to initialize the superclass attributes. For example: super(name, address, phone); this.contact = contact; …

c. In the Outline view, right-click the class name Company. Select Source | Generate Constructor using Fields… In the drop-down list box “Select super constructor to invoke:” select “Customer(String, String, String)”. Make sure both instance variables are selected. In the drop-down list box “Insertion point:” select “After 'discount'” and press OK. Notice that the constructor is inserted at the specified place. 3. Override the toString() method for Company to return the contact name and discount. Include in the return value the superclass details, and format as follows: (, %)

Page 33

Introduction to Java Programming Exercises a. You can manually enter the toString() method signature to the class, or use Eclipse to generate the toString() method signature as described in step 3(b). Skip step 3(b) if you manually enter the method. b. In the Outline view, right-click the class name Company. Select Source | Override/Implement Methods… From the list, select toString() then click OK. Scroll down to the end of the source code in the Company class to view the results. c. Add the return statement and save the Company class file.

Define a New Individual Class as a Subclass of Customer 4. Define an Individual class extending Customer, and include the attributes and methods that are defined in the object model on the first page of this exercise. a. Add the licNo attribute as a String, and create the get and set methods to retrieve or modify the attribute value. b. Add a constructor to accept four arguments for the name, address, phone, and the license number. Hint: Refer to step 2(c) above. c. Complete the constructor body initialization by assigning the arguments to the appropriate instance variables in the Individual class and its superclass. d. Override the toString() method that is defined in the superclass, and append the license number enclosed in brackets to the superclass information. e. Save the Individual class file.

Modify the DataMan Class to Include Company and Individual Objects You will add two new class variables to the DataMan class, one for a Company object, and the other for an Individual. 5. Open DataMan in the Code Editor and add two new class variables called customer5 and customer6. a. Create a Company variable called customer5, and initialize it by using the Company constructor. For example: static Company customer5 = new Company("XYBASE", "Kelana…", "78850003", "Suhaimee…", 20);

b. Create an Individual variable called customer6, and initialize it by using the constructor from the Individual class. c. Save the DataMan class file.

Test Your New Classes in the OrderEntry Application Modify the OrderEntry code that assigns a customer object to each of the two order objects in the main() method. 6. Open OrderEntry.java in the Code Editor. a. Locate the line assigning customer2 or customer3 with the first order object. b. For example, find: Page 34

Introduction to Java Programming Exercises

order.setCustomer(DataMan.customer2);

c. Hint: Use CTRL+F to show a search dialog box. Replace customer2 with customer5 (the company in DataMan.) d. Save (and compile) the code, and if successful, explain why. e. Now replace customer4 in order2.setCustomer() argument with customer6 (the individual in DataMan.) f. Save and run the OrderEntry application. What is displayed in the customer details for each order? g. Explain the results that you see.

Refine the Util and Customer Classes and Test Results It is not obvious to the casual user that data that is printed for a customer, company, or individual objects represent different objects, unless the user is made aware of the meaning of the subtle differences in the displayed data. Therefore, you are asked to modify your code to explicitly indicate the object type name in the text that is printed before the rest of object details, as follows: [Customer] [Company] [Individual]

If you manually add the square-bracketed text string before the return values of the toString() methods in the respective classes, then it would produce a result that concatenates [Company] to [Customer], and [Individual] to [Customer] for the subclasses of Customer. Therefore, the solution is to use inherited code called from the Customer class that dynamically determines the run-time object type name. You can determine the run-time object type name of any Java object by calling its getClass() method, which is inherited from the java.lang.Object class. The getClass() method returns java.lang.Class object reference, through which you call a getName() method returning a String containing the fully qualified run-time object name. For example, if you add this line to the Customer class: String myClassName = this.getClass().getName();

the variable myClassName will contain a fully-qualified class name that includes the package name. The value that is stored in myClassName would be oe.Customer. To extract the class name only, you must strip off the package name and the dot that precedes the class name. This can be done by using a lastIndexOf() method in the String class to locate the position of the last dot in the package name, and extract the remaining text thereafter. To do this, add the getClassName() method to the Util class, and call it from the toString() method in the Customer class. 7. Open Util.java in the Code Editor. a. Add a public static String getClassName() method to determine the run-time object type name, and returns only the class name. public static String getClassName(Object o) { String className = o.getClass().getName(); return className.substring(className.lastIndexOf('.') + 1); }

Page 35

Introduction to Java Programming Exercises b. Save (and compile) Util.java. Note that Eclipse automatically recompiles other classes that are dependent on code in Util.java. Eclipse has a built-in class dependency checking mechanism. 8. Open Customer.java in the Code Editor. a. Prefix a call to the Util.getClassName() method before the rest of the return value data in the toString() method as follows: return "[" + Util.getClassName(this) + "] " + id + …;

b. Save (and compile) Customer.java. c. Run the OrderEntry application to view the results. d. In the above code, what does the “this” represent? And, why do you pass a parameter value “this” to the Util.getClassName() method? Explain why the compiler accepts the syntax that is used.

Page 36

Introduction to Java Programming Exercises

Exercise 11 Goal The goal of this exercise is to gain experience with Java array objects, and work with collection classes like the java.util.ArrayList class. You will also work with command-line arguments.

Your Assignment Continue to use Eclipse to build on the application classes from the previous practices. You enhance the DataMan class to hold a method to construct an array of Customer objects, and then provide a method to find and return a Customer object for a given ID. The Order class is modified to contain a list of order items, requiring a method to add items into the list, and (optionally) another to remove the items.

Modify DataMan to Keep the Customer Objects in an Array 1. Modify the DataMan class to build an array of customers. a. Define a private static array of Customer objects named customers. b. Initialize the array to a null reference. 2. Create a public static void method called buildCustomers() to populate the array of customers. The array should hold six objects using the four Customer objects, the Company and Individual objects that you have already created. a. In the body of the method, first test if the customers variable is not null, and if so, then return from the method without doing anything because a non-null reference indicates that the customers array has been initialized. If customers is null, then you must create the array object to hold the six customer objects that are already created. b. Now move (cut and paste) the definitions of the four existing Customer objects, the Company, and the Individual into the body of this method, after creating the array object. Then, delete the static keyword and class name/type before each customer variable name. Modify each variable to be the name of the array variable followed by brackets enclosing an array element number. Remember, array elements start with zero. For example, replace: static Customer customer1 = new Customer(…);

with: customers[0] = new Customer(…);

The example here assigns the customer object to the first element of the array. Repeat this for each customer object references in the code. c. Create a static block that invokes the buildCustomers() method to create and initialize the array of customer objects, when the DataMan class is loaded. d. Save (and compile) the DataMan class. Fix any errors in the DataMan class, if any. Page 37

Introduction to Java Programming Exercises

Modify DataMan to Find a Customer by His or Her ID 3. Create a public static method called findCustomerById(int custId), where the argument represents the ID of the Customer object to be found. If found, then return the object reference for the matching Customer, otherwise return a null reference value. a. Why is the customer array guaranteed to be initialized when the findCustomerById() method is called? Thus, you can write code assuming that the array is populated. b. Write a loop to scan through the customers array, obtaining each customer object reference to compare the custId parameter value with the return value from the getId() method of each customer. If there is a match, then return the customer object reference, otherwise return a null. c. Save (and compile) your DataMan class, only fixing the syntax errors that are reported for the DataMan class. 4. You now fix the syntax errors in the OrderEntry class as a result of the changes made to DataMan. The modifications that you make to OrderEntry.java fix the syntax errors, and test the code that is added to the DataMan class. a. In the Code Editor for OrderEntry.java, locate and modify each line that directly refers to the DataMan.customer variables that previously existed. Hint: You can quickly navigate to the error lines by double-clicking the error message line in the Problems view. You can also jump from one error to another in the Editor window by clicking the up arrow (Next Annotation) or the down arrow (Previous Annotation) in the toolbar. Replace each occurrence of the DataMan.customer text with a method call to: DataMan.findCustomerById(n). For example, replace: System.out.println(DataMan.customer1.toString());

with: System.out.println(DataMan.findCustomerById(1).toString());

b. Save and run the OrderEntry application to test your changes. c. Modify OrderEntry.java to accept a list of customer IDs on the command line. Write a loop in the main() method to process the arguments converting each from a String into an int, using the Integer.parseInt() method. Use each integer value in the DataMan.findCustomerById() method parameter to locate and display the customer details. d. Save and run the OrderEntry application to test your changes, with the following command line arguments: 1 3 4 99 6 Hint: Right-click on OrderEntry.java and select Run As | Run Configurations… In the Run Configurations dialog box, select OrderEntry (under Java Application), and click on the Arguments tab on the right pane. Enter the list of numbers above in the “Program arguments:” entry field. Click Run.

Page 38

Introduction to Java Programming Exercises

Modify the Order Class to Hold a List of OrderItem Objects Currently, the Order class has hard-coded creation of two OrderItem objects as instance variables, and the details of each OrderItem object is set in the getOrderTotal() method. This is impractical for the intended behavior of the Order class. You must now replace the two OrderItem variables with an ArrayList that will contain the OrderItem objects. Therefore, you must create methods to add and remove OrderItem objects to and from the ArrayList. 5. Define an ArrayList of order items, and replace the OrderItem instance variables, removing code dependent on the original OrderItem instance variables. a. Declare a new private instance variable called items as an ArrayList object reference. Also, remove (or comment out) the declarations of the two instance variables called item1 and item2, and the code that is using these variables. Use Eclipse to add the import statement for java.util.ArrayList by rightclicking on the Editor window and selecting Source | Organize Imports or pressing CTRL+SHIFT+O. b. In the getOrderTotal() method, delete all lines except the return statement which returns the current value of orderTotal. c. In the showOrder() method, delete the two statements displaying the details of the two items. Add the following line as the last line: System.out.println("Items:");

d. In the Order no-arg constructor, add a line to create the item list, as follows: items = new ArrayList(10);

e. Save (and compile) your changes to the Order class.

Modify OrderItem to Handle Product Information 6. Before you create the method to add an OrderItem object to the items list, you must first modify the OrderItem class to hold the information about the product being ordered. Each OrderItem object will represent an order line item. Each order line item contains information about a product that is ordered, its price, and quantity that is ordered. a. Edit the OrderItem class and add a new instance variable called product. Declare the variable as a private int, and generate or write the getProduct() and setProduct() methods. Modify the toString() method to add the product value between the lineNo and quantity. b. Create an OrderItem constructor to initialize the object by using values that are supplied from the following two parameters: int productId, double itemPrice. Initialize the item quantity variable to 1. Note: The OrderItem class will not provide a no-arg constructor. c. Save (and compile) the OrderItem class. Page 39

Introduction to Java Programming Exercises

Modify Order to Add Products into the OrderItem List 7. In the Order class, create a new public void method called addOrderItem() that accepts one parameter: an integer called product, representing the ID of the product being ordered. This method must perform the following tasks: a. Search the items list for an OrderItem containing the supplied product. To do this, create a loop to get each OrderItem element from the items list. Hint: Use the size() method of the ArrayList object to determine the number of elements in the list. Use the getProduct() method of the OrderItem to compare the product value to an existing product value in the order item. If the product, with the specified ID, is found in an OrderItem element from the list, then increment the quantity by using the setQuantity() method. If the specified product does not exist in any OrderItem object into the list, then create a new OrderItem object by using the constructor that will accept the product, and a price. Then add the new OrderItem object into the list. Most important: Because line item numbers are set relative to their order, set the line number for the OrderItem, by using the setLineNo() method, after an item is added to the list. The line number is set using the size of the list (size() method), because the elements are added to the end of the list by default. For now, assume that all products have a price of $5.00. b. The orderTotal value will now be calculated as each product is added to the order. Thus, you must also add the price of each product to orderTotal. Hint: Use the getUnitPrice() method from the OrderItem class. Because the orderTotal is now updated as each product is added to the order, the getOrderTotal() method can simply return the orderTotal value. Note: This may already be done due to the previous changes to the method. c. Modify the showOrder() method to use an Iterator technique to loop through the items list to display each OrderItem object by calling the toString() method. Hint: Use the ArrayList iterator() method to get an Iterator over the ArrayList as follows: Iterator iter = items.iterator();

Use Eclipse to add the import statement for java.util.Iterator by rightclicking on the Editor window and selecting Source | Organize Imports or pressing CTRL+SHIFT+O. d. Save (and compile) the Order class, and fix any syntax errors. e. Test your changes to the OrderItem and Order classes by modifying the OrderEntry class to add products 101 and 102 to the first order object. For example, before the call to showOrder(), enter the bold lines below: order.setCustomer(DataMan.findByCustomerId(5)); order.addOrderItem(101); order.addOrderItem(102); order.addOrderItem(101);

Page 40

Introduction to Java Programming Exercises

order.showOrder();

f. Save and run the OrderEntry class. Confirm that your results are accurate. For example, check that the order total is reported as $15.00.

Modify Order to remove Products from the OrderItem List 8. Create public void method called removeOrderItem() accepting the product ID as an integer. This method must perform the following tasks: a. In a loop on the items list, locate the OrderItem object with the specified product ID. If an OrderItem is found, the decrement the quantity ordered. If the quantity amount becomes zero, then remove the OrderItem object from the items list. Hint: You will need a variable to remember the index of the OrderItem in the list to remove it. Most important: You will need to write a loop to renumber the line item numbers for each OrderItem object left in the order list, starting from the index of the order item that is just removed. Remember that all index numbers for objects in a list start at zero. b. Modify the method to update the orderTotal by subtracting the unit price of the product removed. c. Save (and compile) the changes. d. Test the method by modifying the OrderEntry class by removing product 101 and product 102 from the first order, after you show the order details. Then call the method to show the order details after the products have been removed. e. Save and run the OrderEntry class to confirm the results.

Page 41

Introduction to Java Programming Exercises

Exercise 12 Goal The goal of this exercise is to learn how to create and use an abstract class and how to create and use an interface.

Your Assignment The OrderItem class currently only tracks a product as an integer. This is insufficient for the business, which must know the name, description, and retail price of each product. To meet this requirement you create an abstract class called Product, and define three concrete subclasses called Software, Hardware, and Manual. To support the business requirement of computing a sales tax on the hardware products, you create an interface called Taxable that is implemented by the Hardware subclass. To test your changes you must modify: •

DataMan to build a list of Product objects, and provide a method to find a product by its ID.



Modify OrderItem to hold an object reference for a Product, and not an integer for ID of product, and also change Order to find a Product by its ID value.



Save and run OrderEntry class to test the changes.

Create an Abstract Class and Three Supporting Subclasses 1. Add a public abstract class called Product to OrderEntry project. Note: Remember to check the “abstract” checkbox in the New Java Class dialog box. a. Declare the following attributes and their getter and getter methods. Hint: Use Eclipse to rapidly generate the getters and getters. private private private private private

static int nextProductId = 2000; int id; String name; String description; double retailPrice;

b. Define a public no-arg constructor that assigns the nextProductId to the ID of a new product object, before incrementing nextProductId. c. Override the toString() method (hint: use Eclipse to generate the skeleton) to return the ID, name, and retailPrice. Prefix with the class name by using getClassName(this) from the Util class. Also, format retailPrice with Util.toMoney(). d. Save (and compile) the Product class. e. Use Eclipse (its New Java Class dialog and the code editor) to create three concrete subclasses of the Product class, each with attributes and initial values that are listed in the table below (generate/add the appropriate getter and setter methods): Subclass Software

Attributes String license = "30 Day Trial";

Page 42

Hardware Manual

Introduction to Java Programming Exercises

int warrantyPeriod = 6; String publisher = "Oradev Press";

f. Modify the no-arg constructor for Software, Hardware, and Manual subclasses so that the new constructors accept three parameters (product name, description, and price). Use this code example for the Software class as a guide: public Software(String name, String desc, double price) { setName(name); setDescription(desc); setRetailPrice(price); }

g. Save (and compile) all your new subclasses.

Modify DataMan to Provide a List of Products and a Finder Method Use the new class definitions in the DataMan class to build an inventory of products. 2. In DataMan, create an object to hold a collection of products. a. Create a private static inner class called ProductMap that extends HashMap. Hint: In the New Java Class dialog box, check the checkbox “Enclosing type:” to create an inner class inside DataMan. Also make sure you select the “private” radio button and “static” check box. b. In the ProductMap inner class, create the following method to add product objects to the collection. The ID is the key, and object reference is the value: public void add(Product p) { String key = Integer.toString(p.getId()); put(key, p); // use inherited put() method }

c. Declare a private static ProductMap variable called products; for example: private static ProductMap products;

d. Save (and compile) your DataMan class. What is the compiled class name of the inner class? (Hint: Use Windows Explorer to check the bin directory.) 3. Create a method to populate the ProductMap map object with a product object. a. Create the method called buildProducts() as follows: public static void buildProducts() { if (products != null) return; products = new ProductMap(); products.add(new Product()); }

b. Save (and compile) your code. Explain the compilation error that is listed for the line adding the Product to the products map. c. Fix the compilation error by adding concrete subclasses of the Product class. Replace the line of code products.add(new Product()) with the following text. products.add(new products.add(new products.add(new products.add(new

Hardware("SDRAM – 128MB", null, 299.0)); Hardware("GP 800x600", null, 48.0)); Software("Spreadsheet-SSP/V2.0", null, 45.0)); Software("Word Processor-SWP/V4.5", null, 65.0));

Page 43

Introduction to Java Programming Exercises

products.add(new Manual("Manual-Vision OS/2x +", null, 125.0));

Note: The descriptions are null for the moment. This code will be replaced later to populate the products from data in a file by using Java I/O classes. d. Save (and compile) the DataMan class. Your compilation should work this time. e. In the static block of DataMan, call the buildProducts() method. f. Add the following method called findProductsById() to return a Product object matching a supplied ID. public static Product findProductById(int id) { String key = Integer.toString(id); return (Product) products.get(key); }

Note: Because products is a HashMap, you simply find the product object by using its key; that is, the ID of the product. g. Save (and compile) the changes to the DataMan class. h. Test the DataMan code, and additional classes, by printing the product that is found by its ID. Add the following line to OrderEntry class at the end of main(): System.out.println("Product is: " + DataMan.findProductById(2001));

i. Save (and compile) and run the OrderEntry application to test the code.

Modify OrderItem to Hold Product Objects 4. Replace usages of the product variable as an int type with the Product class. a. In OrderItem.java, change the type declaration for the product instance variable to be Product instead of int. b. Replace the two-argument constructor with a single argument called newProduct whose type is Product; that is, remove productId and itemPrice parameters. c. Change the body of the constructor to store the newProduct in the product variable, and set the unitPrice to be the value that is returned by calling the getRetailPrice() method of the product object. d. Modify getProduct() method to return Product instead of an int, and change setProduct() method to accept a Product instead of an int. e. Alter the toString() method to display the item total instead of the unitPrice. Hint: Use the getItemTotal() method. f. Save (and compile) your code changes. Only eliminate the syntax errors from the OrderItem class. Errors that are reported for the Order class are corrected in the next step of this exercise.

Modify Order to Add Product Objects into OrderItem Alter the Order class to use the Product objects instead of an int value. Page 44

Introduction to Java Programming Exercises 5. Make the following changes to the addOrderItem() method: a. Rename the parameter to be productId, and in the for loop, replace: productFound = (item.getProduct() == product);

with: productFound = (item.getProduct().getId() == productId);

Hint: Use Eclipse to help you rename every occurrence of the parameter name. Highlight the word product and press SHIFT+ALT+R. Change product to productId and press ENTER. b. In the else clause of the if statement, call findProductById() from DataMan by using the productId value. If a product object is found, then create the OrderItem using with the product object, otherwise do nothing. For example: item = new OrderItem(product, 5.0); items.add(item);

becomes: Product p = DataMan.findProductById(productId); if (p != null) { item = new OrderItem(p); items.add(item); }

6. Make the following changes to the removeOrderItem() method. a. Rename the parameter to be productId, and in the for loop replace the following line: productFound = (item.getProduct() == product);

with: productFound = (item.getProduct().getId() == productId);

b. First, save (and compile) the Product class, and then save (and compile) the changes to the Order class. 7. Test the changes that are made to your code supporting the Product class and its subclasses, by modifying OrderEntry class to use the new product ID values. a. Because the ID of Product objects (or its subclasses) start at 2000, edit the file OrderEntry.java, replacing the argument values in all the calls to the order.addOrderItem() method, as shown in the following table: Replace 101 102

With 2001 2002

b. Save (and compile) and run the OrderEntry application, and check the changes to the printed items. Check that the price calculations are still correct.

Create and Implement the Taxable Interface 8. Create an interface called Taxable. a. Right-click on the package oe on the Package Explorer and select New Interface Page 45

Introduction to Java Programming Exercises from the pop-up menu. Enter Taxable for the name and click Finish. b. In the Code Editor, add the following variable and method definitions to the interface: double TAX_RATE = 0.10; double getTax(double amount);

Note: Remember, all variables are implicitly public static final, and methods are all implicitly public. The implementer of the interface should multiply the amount, such as a price, by the TAX_RATE and return the result as a double. c. Save (and compile) the interface. 9. Edit the Hardware class to implement the Taxable interface. a. Add the bold text to the class definition to implement the interface, as shown: public class Hardware extends Product implements Taxable {

b. Save (and compile) the Hardware class and explain the error. c. Add the following method to complete the implementation of the interface. public double getTax(double amount) { return amount * TAX_RATE; }

Note: Use Eclipse to create the method skeleton by putting the cursor on the underlined class name Hardware and selecting “Add unimplemented methods” on the pop-up menu. d. Save (and compile) the Hardware class. 10. Change the OrderItem class to obtain the tax for each item. a. Add a public double getTax() method to determine if the Product in the item is taxable. If the Product is taxable, then return the tax amount for the item total (use getItemTotal() method), otherwise return 0.0. b. Modify the toString() method to display the tax amount for the item, if and only if the product is taxable. Use the getTax() method that you created, and format the value with Util.toMoney(). c. To view the changes, save the OrderItem class and run the OrderEntry application. 11. Modify the Order class to display the tax, and order total including the tax. a. In the showOrder() method, add a local double variable called taxTotal initialized to 0.0 that accumulates the total tax for the order. b. Modify the for loop using the Iterator to call the getTax() method for each item, and add the value to taxTotal. Hint: To do this you will have to cast the return value of iter.next() to OrderItem. c. Add three System.out.println() statements after the loop, one to print the Page 46

Introduction to Java Programming Exercises taxTotal, the second to print the orderTotal including taxTotal, and the last, without parameter to print a blank line. Use the method Util.toMoney() to format the totals. d. To view the results, save the Order class and run the OrderEntry application.

Page 47

Introduction to Java Programming Exercises

Exercise 13 Goal The goal of this exercise is to learn how to create you own exception classes, throw an exception object by using your own class, and handle the exceptions.

Your Assignment Our application does not appropriately handle situations when an invalid customer ID is applied to the DataMan.findCustomerById() method, or an invalid product ID is given to DataMan.findProductById() method. In both cases, a null value is returned. Your tasks are to: •

Create a user-defined (checked) exception called oe.NotFoundException.



Modify DataMan.findCustomerById() to throw the exception when an invalid customer ID is provided.



Modify the DataMan.findProductById() method to throw the exception if the given product ID is not valid, that is, not found.

Create the NotFoundException Class 1. In the OrderEntry project, create a new class called oe.NotFoundException. a. Right-click on the package oe in the Package Explorer. Select New | Class from the pop-up menu. Enter the class name as NotFoundException and make it a subclass of java.lang.Exception. Also make sure you check “Constructors from superclass”. b. Delete all the constructors generated except for the one with a String parameter. If the parameter name is not message, change the parameter name to message. Hint: Use Eclipse to help you here. Highlight the parameter name and press SHIFT+ALT+R (or right-click, select Refactor | Rename). Type message and press ENTER. You can see that all occurrences of the parameter name in the constructor are changed. c. Save (and compile) the NotFoundException class.

Throw Exceptions in DataMan Find Methods and Handle Them in OrderEntry 2. Edit DataMan.java, and modify the findCustomerById() method to throw the NotFoundException when the given customer ID is not found in the array. a. At the end of the for loop, if the local customer object reference is null, that is, the customer is not found, then throw an exception object, using the following error message structure in the constructor argument: "Customer with ID " + custId + " does not exist"

b. Save (and compile) the DataMan class. Explain the error. c. Fix the error by modifying the method declaration to propagate the exception. d. Save (and compile) the DataMan class again. What errors do you get this time? Page 48

Introduction to Java Programming Exercises Explain the errors? e. Fix the compilation errors by handling the exceptions with a try-catch block in the OrderEntry class. For simplicity, use one try-catch block to handle all the calls to the DataMan.findCustomerById() methods. Alternatively, if desired, then handle each call in its own try-catch block. try { // calls to findCustomerById() here… } catch (NotFoundException ex) { // handle the exception here… }

In the catch block, you can use the exception’s inherited methods to display error information. Use the following two ways to display error information: •

ex.getMessage() to return the error message text as a String



ex.printStackTrace() to display the exception, message, and the stack trace

Note: Use Eclipse to help you generate the try-catch block by putting the cursor on the first statement and selecting “Surround with try/catch” on the pop-up menu. Move the rest of the statements in error inside the try-catch block. f. Save (and compile) and run the OrderEntry application. Test your code with the errors. 3. Now modify the findProductById() method in the DataMan class to throw NotFoundException when the supplied product ID is not found in the product map. a. The findProductById() method calls get(key) to find a product from the items HasMap. If get(key) returns a null, throw a NotFoundException by using the following error message, otherwise return the product object found: "Product with id " + id + " is not found"

b. Modify the findProductById() declaration to propagate the exception. Use Eclipse to help you generate the required declaration by putting the cursor on the statement and selecting “Add throws declaration” on the pop-up menu. c. Save (and compile) DataMan, and explain the error reported. d. In the Order class, modify the addOrderItem() method to propagate the exception. Hint: Use Eclipse as in step (b) above. e. Save (and compile) the Order class, and explain why it compiles successfully. f. In OrderEntry.java, use a value of 9999 as the product ID, in the first call to order.addOrderItem(2001). Save (and compile) and run OrderEntry. Explain why the application terminates immediately after adding product 9999. g. In Order.java, remove throws NotFoundException from the end of the addOrderItem() method declaration. Write a try-catch block to handle the exception in this method. Use Eclipse as described in step 2(e). Hint: You will need to return from the method in the catch block, to ensure the itemTotal is not affected. Page 49

Introduction to Java Programming Exercises h. Save (and compile) the Order class, and run the OrderEntry application. Explain the difference in output results. i. In OrderEntry, replace product ID 9999 with 2001. Save (and compile) and run OrderEntry.

Page 50

View more...

Comments

Copyright © 2017 DATENPDF Inc.