+ All Categories
Home > Documents > Java Programming Exercises

Java Programming Exercises

Date post: 07-Apr-2018
Category:
Upload: keitouma
View: 239 times
Download: 1 times
Share this document with a friend

of 50

Transcript
  • 8/4/2019 Java Programming Exercises

    1/50

    Introduction to Java Programming Exercises

    Table of Contents

    Table of Contents ....................................................................................................................... 1

    Exercise 1 ................................................................................................................................... 3Goal....................................................................................................................................3Install the Java Development Kit (JDK)............................................................................3Add the JAVA_HOME and Modify the PATH Environment Variables...........................3Edit and Run a Simple Java Application............................................................................3

    Exercise 2 ................................................................................................................................... 5Goal....................................................................................................................................5Description of the Order Entry Area of the Business.........................................................5Understanding the Object-Oriented Principles...................................................................5Identifying Business Classes, Attributes, and Methods.....................................................5

    Exercise 3 ................................................................................................................................... 7

    Goal....................................................................................................................................7Understanding Objects, Classes, Methods, and Attributes................................................7Exploring Code..................................................................................................................7Questions About the Java Development Kit......................................................................8Creating Order Entry Class Files........................................................................................8Create and Compile the Application Class with a main() Method.....................................9

    Exercise 4 ................................................................................................................................. 11Goal..................................................................................................................................11Your Assignment..............................................................................................................11Create the OrderItem Class..............................................................................................11Modify the Order Class....................................................................................................11

    Modify the main() Method in the OrderEntry Class........................................................12Exercise 5 ................................................................................................................................. 14

    Goal..................................................................................................................................14Your Assignment..............................................................................................................14Create the Util Class.........................................................................................................14Modify the Order Class....................................................................................................16Test the Code by Using the OrderEntry Class..................................................................17

    Exercise 6 ................................................................................................................................. 18Goal..................................................................................................................................18Your Assignment..............................................................................................................18Refine the Customer Class...............................................................................................18

    Create Customer objects...................................................................................................18Refine the OrderItem Class..............................................................................................19Refine the Order Class.....................................................................................................19Modify OrderEntry to Associate a Customer to an Order................................................20

    Exercise 7 ................................................................................................................................. 21Goal..................................................................................................................................21Your Assignment..............................................................................................................21Modify the Customer Class..............................................................................................21Modify the Order Class....................................................................................................21Create the DataMan Class................................................................................................23Modify OrderEntry to Use DataMan...............................................................................23

    Exercise 8 ................................................................................................................................. 25

    Page 1

  • 8/4/2019 Java Programming Exercises

    2/50

    Introduction to Java Programming ExercisesGoal..................................................................................................................................25Your Assignment..............................................................................................................25Add Formatting Methods to the Util Class......................................................................25Use the Util Formatting Method in the Order Class........................................................26

    Use Formatting in the OrderItem Class............................................................................26Use the Util.getDate() Method to Set the Order Date......................................................26

    Exercise 9 ................................................................................................................................. 27Goal..................................................................................................................................27Your Assignment..............................................................................................................27Part 1: Installing Eclipse...................................................................................................27Part 2: Using Eclipse: Create a new workspace and project............................................27Part 3: Create a Workspace and Project for the Course Application Files.......................29Debugging Your Application Code..................................................................................30

    Exercise 10 ............................................................................................................................... 32Scenario............................................................................................................................32

    Goal..................................................................................................................................32Your Assignment..............................................................................................................32Define a New Company Class..........................................................................................33Define a New Individual Class as a Subclass of Customer..............................................34Modify the DataMan Class to Include Company and Individual Objects........................34Test Your New Classes in the OrderEntry Application...................................................34Refine the Util and Customer Classes and Test Results..................................................35

    Exercise 11 ............................................................................................................................... 37Goal..................................................................................................................................37Your Assignment..............................................................................................................37Modify DataMan to Keep the Customer Objects in an Array..........................................37

    Modify DataMan to Find a Customer by His or Her ID...................................................38Modify the Order Class to Hold a List of OrderItem Objects..........................................39Modify OrderItem to Handle Product Information..........................................................39Modify Order to Add Products into the OrderItem List...................................................40Modify Order to remove Products from the OrderItem List............................................41

    Exercise 12 ............................................................................................................................... 42Goal..................................................................................................................................42Your Assignment..............................................................................................................42Create an Abstract Class and Three Supporting Subclasses............................................42Modify DataMan to Provide a List of Products and a Finder Method.............................43Modify OrderItem to Hold Product Objects.....................................................................44Modify Order to Add Product Objects into OrderItem....................................................44Create and Implement the Taxable Interface....................................................................45

    Exercise 13 ............................................................................................................................... 48Goal..................................................................................................................................48Your Assignment..............................................................................................................48Create the NotFoundException Class...............................................................................48Throw Exceptions in DataMan Find Methods and Handle Them in OrderEntry............48

    Page 2

  • 8/4/2019 Java Programming Exercises

    3/50

    Introduction to Java Programming Exercises

    Exercise 1

    Goal

    The goal of this exercise is to install the Java Development Kit (JDK) and examine thedevelopment environment. You will set environment variables, and examine the JDKdirectory 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\installersdirectory.

    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 Variables1. 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_HOMEwith 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 werecorrectly 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 correctlyset.

    Edit and Run a Simple Java Application

    1. Navigate to the C:\JavaCourse\labs\hellodirectory and create a file called

    HelloWorld.java using your favorite text editor. (If you dont have one, you can

    Page 3

  • 8/4/2019 Java Programming Exercises

    4/50

    Introduction to Java Programming Exercisesinstall the Crimson Editor available in the C:\JavaCourse\installersdirectory.)

    2. In the editor, enter the following code, placing your name in the comments (after theAuthor: 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 editorrunning, in case compilation errors occur requiring you to edit the source to makecorrections.

    4. Compile the HelloWorld.java source file (file name capitalization is important.)

    a. In the Command Prompt, make sure the current directory isC:\JavaCourse\labs\hello. If not, issue the command: cdC:\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

  • 8/4/2019 Java Programming Exercises

    5/50

    Introduction to Java Programming Exercises

    Exercise 2

    Goal

    The goal of this exercise is to become familiar with object-oriented concepts, includingclasses, methods, and attributes. You will also learn how to read a UML class model showingthe 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 theywant from a list of products. Our customers must be included in our system. We keepinformation about our customers such as name, address, and telephone number. We alsoassign a unique customer ID to each new customer. For customers that are companies, wetrack 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 keeptrack of it and has information such as the customer who is responsible for the order, theorder date, shipping mode (air or ground), and an order status. Each order can have multipleline items. We currently limit our customers to 10 items per order. Each item on the order hasthe product being purchased, the price, the quantity, and the product category. A productcategory 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 whodistributes 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 informationabout the products on hand, and where they are located. We have many warehouses to holdall our products.

    Understanding the Object-Oriented Principles

    1. Define the following terms:

    a. Class

    b. Object

    c. Encapsulation

    d. Inheritancee. 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 thingsfrom 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 interestto the business.

    3. Identify a few attributes for each of the new classes. Remember that attributes may be

    for other classes.

    Page 5

  • 8/4/2019 Java Programming Exercises

    6/50

    Introduction to Java Programming Exercises4. 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) fromother classes. Modify your definitions to reflect the inheritance model.

    Page 6

  • 8/4/2019 Java Programming Exercises

    7/50

    Introduction to Java Programming Exercises

    Exercise 3

    Goal

    The goal of this exercise is to create, examine, and understand the Java code. You will createa class representing a command line application for the Order Entry system that contains theapplication 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 classfiles for your application. You will run some simple Java applications, fixing any errors thatoccur. You will also discriminate standard compiler errors and learn how and where to fixthem.

    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

  • 8/4/2019 Java Programming Exercises

    8/50

    Introduction to Java Programming Exercisesb. 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.javafile into a class file? How do you use this tool?

    5. After the HelloWorld.class has been generated by the compiler, how do you runthe 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 theapplication.

    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 Orderclasses. Save the code in the C:\JavaCourse\labs\OrderEntry\src\oedirectory 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 statementto return the attribute, and the other to accept a parameter value to set the attribute butleave the method body empty.

    Note: Use the Customer example shown later and the UML model createdpreviously as a guide.

    a. At the command prompt, change the directory toC:\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

  • 8/4/2019 Java Programming Exercises

    9/50

    Introduction to Java Programming Exercisese. 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 void setId(int newId) { }public void setName(String newName) { }public void setAddress(String newAddress) { }public void setPhone(String newPhone) { }

    public int getId() { return id; }

    public String getName() { return name; }public String getAddress() { return address; }public String getPhone() { return phone; }

    }

    Sample Order.java file:

    package oe;

    public class Order {int id;String orderDate;String shipDate;String shipMode;

    double orderTotal;

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

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

    }

    Create and Compile the Application Class with amain() Method

    8. Create a file called OrderEntry.java containing the main method, as shownbelow. 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.javawith the following command:

    Page 9

  • 8/4/2019 Java Programming Exercises

    10/50

    Introduction to Java Programming Exercisesjavac -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 thefollowing 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 oeand a dot, as follows, and then explain the result:

    java oe.OrderEntry

    Page 10

  • 8/4/2019 Java Programming Exercises

    11/50

    Introduction to Java Programming Exercises

    Exercise 4

    Goal

    The goal of this exercise is to declare and initialize variables, and use them with operators tocalculate new values. You will also be able to categorize the primitive data types and usethem in code, and learn how to modularize code in methods. The business area for thisexercise is the Order class and a new supporting class called OrderItem, showcasingsome 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 linenumber, quantity, and costs. You also create the methods to get and set the OrderItemvalues 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 creatingan Order and determining the order total, to which you add a tax amount to form the finalorder total.

    Create the OrderItemClass

    1. In the C:\JavaCourse\labs\OrderEntry\src\oedirectory, using theeditor, 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 theprice, 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 twoitems 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

  • 8/4/2019 Java Programming Exercises

    12/50

    Introduction to Java Programming ExercisesgetOrderTotal() 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 newkeyword in a subsequent lesson. For now, just accept that these are needed for thetask.

    3. Modify the method called getOrderTotal() to add the item totals to theorderTotal. The steps (a) through (d) guide you through this process.

    a. Declare two local variables called item1Total and item2Total, both of typedouble, to hold the item totals, respectively.

    b. Set the line number, price, and the quantity for each item object, by calling itsmethods, according to the following table:

    Item lineNo quantity unitPriceitem1 1 2 2.95item2 2 2 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 eachitem 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 isreturned from the method. Just use the orderTotal variable as itself as it isdeclared in the Order class.

    e. Save and compile the Order class.

    Modify themain() Method in the OrderEntry Class

    Modify the OrderEntry class to create an Order variable, and then request its total to besaved in a variable. Then calculate a tax on the total and it to the order total. Set a Booleanvariable 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, aBoolean 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

  • 8/4/2019 Java Programming Exercises

    13/50

    Introduction to Java Programming Exercises5. Determine the order total.

    a. Call the Order objects getOrderTotal() method and store the result in thevariable that is declared to hold its value.

    b. Display the order total before tax is added, by using theSystem.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 thetax 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, todetermine if the total cost exceeds the limit of $10.00 and print its Boolean value.Do not use any type ofif statement in this step.

    6. Save and compile OrderEntry. Test your logic by running the OrderEntry class.

    Page 13

  • 8/4/2019 Java Programming Exercises

    14/50

    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, calledUtil that provides methods to determine the number of days in a month, and handle leapyears. Then you modify the Order class to set the order date and derive an expected shipdate 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, andreturn 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 calledgetShipDate(). Determine the ship date for the order, based on the day it was ordered andhow many days it takes for shipping.

    Create the Util Class

    1. Create the Util class in the C:\JavaCourse\labs\OrderEntry\src\oedirectory, 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 integerparameter, and return a true Boolean value if it is a leap year, otherwise returnfalse. Use the Boolean operations && and || in a statement that returns true if theyear 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.javajava oe.Util

    2. Add another public static method to Util class called lastDayInMonth() thatreturns 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 aswitch statement on the month, remembering how many days are in each month

    with this reminder (if you need it):

    Page 14

  • 8/4/2019 Java Programming Exercises

    15/50

    Introduction to Java Programming ExercisesThere 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 azero if the month is invalid.

    b. Add code in the main() method to test your method by declaring two integervariables to hold a day and month in addition to the year (for example: 27 January2002). Then print the date, using System.out.println(), in D/M/Y formatlooking 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 integerrepresenting 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 aswitch statement and the following table as your guide:

    Region Character Days to ShipAmericas 'A' 3Europe/Africa 'E' 5Asia pacific 'P' 7

    b. Modify the main method to declare and set a variable to hold the number of daysto 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 orderdate 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 initializethe 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 andending at the last day of the month. For example:

    27/1/200228/1/200229/1/200230/1/200231/1/2002

    c. Modify the loop to terminate either at the last day of the month, or at the dayrepresenting the ship date for a region of Americas ('A'). Terminate the loop atthe earliest of date that occurs first. The output should produce the followingresults:

    27/1/200228/1/2002

    29/1/2002

    Page 15

  • 8/4/2019 Java Programming Exercises

    16/50

    Introduction to Java Programming Exercisesd. Compile and run the code.

    e. Test the example for the other regions, E for Europe/Africa, and P for AsiaPacific. 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 basedon 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 currentmonth. For example, if the order date is 29 August and the shipping will take three days, theexpected 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 declarethree integer instance variables to hold the order day, month, and year.

    b. In the setOrderDate()method, initialize the order day, month, and year tozero 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. Asubsequent 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/Yformat.

    d. In the Order class, add a method to return the ship date as a string in D/M/Yformat. The method uses the day, month, and year instance variable in the Orderclass, and a character parameter representing the region to ship the order to, todetermine 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 todetermine the number of days that are required to ship the order to the specifiedregion. To calculate the date of expected shipping:

    Page 16

  • 8/4/2019 Java Programming Exercises

    17/50

    Introduction to Java Programming Exercisesi. 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 dueDayand dueMonth appropriately. If the adjusted dueMonth indicates achange of year, then alter the dueMonth and dueYear appropriately.

    iv. Return the result string formed by concatenating the due day, month, andyear 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 theship date for one or more locations.

    6. Modify the OrderEntry class inC:\JavaCourse\labs\OrderEntry\src\oe.

    a. Before the end of the main() method, after existing code, set the order date bycalling 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 isreturned from the order.getShipDate() method, passing the regionvariable 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 outputshould look something like:

    Order Date: 27/1/2001Days till Shipping: 3Expected Ship Date: 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

  • 8/4/2019 Java Programming Exercises

    18/50

    Introduction to Java Programming Exercises

    Exercise 6

    Goal

    The goal of this exercise is to complete the basic functionality for existing method bodies ofthe Customer, Order, and OrderItem classes. You will then create customer and orderobjects, and manipulate them by using their public instance methods. You display theCustomer 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 buildingfor the remainder of the course. After creating one or more Customer objects, you willassociate a customer with an order. This will require changes to the Order class.

    Refine the Customer Class1. In the C:\JavaCourse\labs\OrderEntry\src\oedirectory, edit the

    Customer.java file.

    a. Make all instance variables private.

    b. Complete the public instance methods whose names have the form setXXX() foreach 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 thesemethods 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 objectby calling one method.

    a. To cover this deficiency, add a new public method called toString() to theclass, without parameters and returning a String containing the customers ID,name, address, and phone. The resultant string should be a simple concatenationof 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 aString representation of an object is needed. The toString() method is veryuseful to add to any class, and thus it is added to almost all the classes that youcreate.

    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 twocustomer objects.

    a. In the main() method ofOrderEntry.java, create two customer objects by

    Page 18

  • 8/4/2019 Java Programming Exercises

    19/50

    Introduction to Java Programming Exercisesusing the new operator, assigning each one to a different object reference (usecustomer1 and customer2).

    b. At the end of the main() method, initialize the state of each Customer object bycalling its public setXXX() methods to set the ID, name, address, and phone. Usethe table data below:

    Id Name Address Phone1 Gary Williams Houston, TX 713.555.87652 Lynn Munsinger Orlando, FL 407.695.2210

    c. Print the two customer objects created, under a printed heading ofCustomers: by calling the toString() method inside the argument of theSystem.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 toachieve 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 OrderItemClass

    4. Apply the encapsulation principles to the OrderItem class, and add a method todisplay the attributes of the OrderItem.

    a. Edit the OrderItem class and make each instance variable private.

    b. Add the public StringtoString() method to the OrderItem class thatreturns a concatenated string of its attributes lineNo, quantity, andunitPrice. Precede the unitPricewith 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 acustomer 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 instancevariable. Also make each instance variable of the Order class private.

    b. Add a private instance variable named customerwith data type based on theCustomer class, write a method called setCustomer() to associate a customerinstance to the customer variable, and write a method called getCustomer()to return the customer value.

    c. Add a public StringtoString() method to print the order ID, order date, andorder total (hint: use the getOrderTotal() method). Use the following format:

    Order #: 1 Date: 27/2/2001 Total: $13.96425

    Page 19

  • 8/4/2019 Java Programming Exercises

    20/50

    Introduction to Java Programming Exercisesd. Add a publicvoidshowOrder() method with no arguments to display the

    details of the order. The first line of output should show the order details, bycalling the toString() method from step 5(c). Then show the customer detailsfollowed 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 objectreference ofcustomer1 (orcustomer2).

    b. After setting the customer, call the showOrder() method of the order object.

    c. Save, compile, and run the OrderEntry class.

    Page 20

  • 8/4/2019 Java Programming Exercises

    21/50

    Introduction to Java Programming Exercises

    Exercise 7

    Goal

    The goal of this exercise is to gain experience with creating and using constructors, classmethods, 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 OrderEntryapplication. Part of the exercise is to understand method overloading by creating more thanone 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 andOrder objects when instantiated. Create the DataMan class to provide class (static)attributes of customer objects to be used by the OrderEntry application when it associatesa 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 toset the actual name, address, and phone properties. The no-arg constructor will beinvoked by the second constructor.

    a. Add a no-arg constructor to the Customer class, which is used to generate thenext unique ID for the customer object by first declaring a class variable, callednextCustomerId, 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 Stringarguments. This constructor should set the corresponding properties to thesevalues.

    d. In the first line of the second constructor, chain it to the first constructor byinvoking the no-arg constructor by using the this() keyword. This is done toensure 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 ofcustomer1 andcustomer2 object by using the second constructor of the customer (with threearguments). Remove (or comment out) all calls to setXXX() methods made withthe 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

  • 8/4/2019 Java Programming Exercises

    22/50

    Introduction to Java Programming Exercises2. First change the way in which you manage the order date information.

    a. Uncomment the orderDate variable that had been commented out in an earlierexercise, and make it a private variable.

    b. After the package statement at the top of the class, add the following importstatements (before the class declaration):

    import java.util.Date;import java.util.Calendar;

    c. Redefine the orderDate type to be Date instead ofString, and remove thethree 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 voidsetOrderDate() method that accepts aDate as its parameter and sets the orderDate variable accordingly.

    b. Change the getShipDate() method to use the Calendar class to calculate theship date. Replace the body ofgetShipDate() 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 theCalendar class methods, using the three input parameters. First, delete thefollowing date initialization code:

    day = 0;month = 0;year = 0;

    d. Also in the setOrderDate() method, replace the following three bold lines orcode:

    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 methods month argument, because theJava Calendar class starts numbering months from 0 for January through 11 forDecember. Consult the Java API documentation for details of the methods that areused in the Calendar class.

    4. Create a no-arg constructor to initialize the order number, date, and total.

    Page 22

  • 8/4/2019 Java Programming Exercises

    23/50

    Introduction to Java Programming Exercisesa. Create a class (privatestaticint) 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 theorderDate as follows:

    orderDate = new Date();

    c. Create a second constructor that accepts an order date argument as a Date, and aship mode as a String. Call the no-arg constructor from this constructor and usethe orderDate and shipMode instance variable using the arguments.

    d. Update the toString() method to include the shipMode in the return value ifit is not null.

    e. Save and compile the Order class, and run the OrderEntry class to verify thatthe code still runs unchanged but picks up the changes to the order.

    f. In OrderEntry create another order with the second Order constructor passinga java.util.Date object and overnight ship mode as parameters. Set theorder customer to customer2 and print the details. Recompile and runOrderEntry.

    Create the DataMan Class

    The DataMan class is used to create the data that will be used to test the application. Tostart, you will create the customer objects, and later modify them to maintain the product liststhat are available for ordering. This class is really a convenience class that simplifies ourapplication 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 calledC:\JavaCourse\labs\OrderEntry\src\oe. The class should not containconstructors.

    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 inthe 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 variablescustomer3 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 theDataMan class.

    a. Use the class name DataMan. as the prefix to all customer reference variables

    Page 23

  • 8/4/2019 Java Programming Exercises

    24/50

    Introduction to Java Programming Exercisescustomer1 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 noneed to create a DataMan object. In addition, the customer variables inDataMan 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 customer1with customer3 orcustomer4 from DataMan toconfirm that your code is using the customer objects from DataMan.

    Page 24

  • 8/4/2019 Java Programming Exercises

    25/50

    Introduction to Java Programming Exercises

    Exercise 8

    Goal

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

    Your Assignment

    You will create a method called toMoney() to return a currency formatted string for theorder 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 oforder details, such as, the order date and total.

    Add Formatting Methods to the Util Class1. 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 integersrepresenting the day, month, and year, and returns a java.util.Date objectrepresenting the specified date (month = 1 represents January on input.) Becausemany methods in the Date class that could have been used are deprecated, you usethe GregorianCalendar class to assist you with this task.

    a. Import the java.util.GregorianCalendarclass.

    b. Use the following for the method:

    public static Date getDate(int day, int month, int year) {

    Page 25

  • 8/4/2019 Java Programming Exercises

    26/50

    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 methodstoMoney() 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 viewthe changes to the displayed order details.

    c. Now import the java.text.MessageFormat class and use this class toformat 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 OrderItemClass

    5. In the OrderItem class, modify the toString() method to use theUtil.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 toview 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 theUtil.getDate() method to provide the value for the first argument in theconstructor. Choose the previous days date for the values of the day, month, and yeararguments 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 hasbeen set correctly.

    Page 26

  • 8/4/2019 Java Programming Exercises

    27/50

    Introduction to Java Programming Exercises

    Exercise 9

    Goal

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

    Your Assignment

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

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

    In part 3, you create a workspace called OrderEntry that will hold a single projectcalled OrderEntry that will contain the course application Java files. You run theapplication 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 theC:\JavaCourse\installersdirectory.

    b. Install the software into the directory C:\Java\jdk1.6.0_24.

    c. Update the WINDOWS environment variable JAVA_HOME to the abovedirectory.

    2. Install the WinRAR application.

    a. Double-click the file wrar380.exe in the C:\JavaCourse\installersdirectory.

    3. Install the Eclipse workbench.

    a. In the C:\JavaCourse\installersdirectory, right-click on the file

    eclipse-java-helios-win32.zipand 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 folderC:\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

  • 8/4/2019 Java Programming Exercises

    28/50

    Introduction to Java Programming Exerciseshow 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 existingworkspace. Since we have not created any workspace before, enterC:\JavaCourse\workspaces\Helloand 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 ofthe Eclipse window is Java EE, select Window | Open Perspective | Java. Wewill be working with plain Java applications and not Java Enterprise Edition (JavaEE) in this course. Eclipse supports multiple perspectives depending on what youare 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 | JavaProject. 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 followingitems to be entered and selected (leave each in their default states): the projectname, where to store the contents, the JRE to use, and the project layout (whetherto 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. Youwill 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 thecompiled .class files are stored. You can use the Windows Explorer to checkthat 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 greencircle.) 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 hasbeen 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 Eclipseautomatically create the main() method for the class. Press Finish.

    i. Eclipse creates a source file called Application1.javawhich appears underdefault package on the Package Explorer view. The generated source code for thenew 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

  • 8/4/2019 Java Programming Exercises

    29/50

    Introduction to Java Programming Exercisesk. 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 notsaved. Save you work by right-clicking anywhere in the source window andselecting 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 inthe source window. Where exactly is the file created and explain yourobservations?

    l. Run the application by either selecting Run | Run As | Java Application menuitem, or right-clicking the Application1.java and choosing Run As | Java

    Application.

    m. Eclipse automatically opens a Console view showing the results of the executionof 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 FilesIn this part of the exercises, you create a new workspace. Then you create a project in theworkspace 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 beC:\JavaCourse\workspaces\OrderEntry.

    c. Click OK to create the workspace directory.

    d. Select Window | Preferences | Java | Compiler and set the Compilercompliance level: to 1.4. Click OK to close the dialog box.

    7. Create a new project called OrderEntry in the new workspace and populate theproject with the existing Java files inC:\JavaCourse\labs\OrderEntry\src.

    a. Select File | New | Java Project menu item. (Or click the New Java Project buttonon the toolbar.) Enter the project name as OrderEntry and click Finish.

    b. Expand the OrderEntry project in the Package Explorer view. Right-click onthe src folder and select Import

    c. In the Import dialog box, expand General and click File System. This means weare importing files directly from the Windows file system. You can also importfrom an existing Eclipse project in another workspace or even from a JAR or ZIPfile (Archive File). Click Next.

    d. In the resulting Import dialog box, browse toC:\JavaCourse\labs\OrderEntry\src. Make sure you select the srcfolder 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. Youshould 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

  • 8/4/2019 Java Programming Exercises

    30/50

    Introduction to Java Programming Exercisesf. 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 fileshave errors in them, Eclipse will mark them with an error symbol (small red boxwith a white X in it.)

    g. Fix all the errors if any. You can edit each .java file by double-clicking the nameon 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 thefile 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 leftof the line until a green dot appears on the margin.

    c. Set two more breakpoints, one on the line associating a DataMan customer objectto the first order, and another on the line that is calling the method to show thesecond order details: order2.showOrder().

    d. In the Package Explorer, select the OrderEntry.java, right-click, and selectDebug As | Java Application. The dialog box Confirm Perspective Switch popsup. 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 codestops at your first breakpoint, as indicated by the highlighted line in the Editorview. The highlighted line indicates the next line to be executed when you resumedebugging. The Debug view shows the exact point in the main() method whereexecution stops (line X). The Variables view shows the current values of all thevariables in scope. The Breakpoints view shows all the breakpoints in the current

    source file. (You need to click the Breakpoints tab.) The Console view displaysthe 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 theline 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 samewindow as the Breakpoints view.

    h. Locate the order variable in the Variables view, expand it, and find thecustomer 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

  • 8/4/2019 Java Programming Exercises

    31/50

    Introduction to Java Programming Exercisesitem) to execute the order.setCustomer() method. Note that the changes tothe ordercustomer instance variable in the Variables view. Expand thecustomer instance variable to examine its contents.

    j. The highlighted line should now point to the line to display the first ordersdetails; that is, order.showOrder(). Click the Step Into (F5) button on thetoolbar (or select Run | Step Into menu item.) Eclipse displays the highlight onthe first line of the showOrder() method of the Order class.

    k. Expand the this variable. Press F6 (Step Over) for a few lines noticing theresults 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 theorder.showOrder() method.

    m. Continue selecting the Run | Resume menu (F8 key or click the toolbar button)until the program is completed (the Debug view saysOrderEntry [JavaApplication].)

    n. Remove the breakpoints from the OrderEntry.java source, by double-clicking 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 rightcorner of the Eclipse workbench.

    Page 31

  • 8/4/2019 Java Programming Exercises

    32/50

    Introduction to Java Programming Exercises

    Exercise 10

    Scenario

    In this exercise, you add a couple of new classes as subclasses. The new classes that areadded are Company and Individual and they inherit from the Customer class. Here is a UMLclass 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 middlesection specifies the attributes in the class, where underlined attributes represent classvariables. The lower section specifies the methods in the class. Notice the arrow on the lineconnecting Company and Individual to Customer. This is the UML notation forinheritance.

    Goal

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

    Your Assignment

    Add two classes, Company and Individual, which inherit from Customer. The ownersof 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

  • 8/4/2019 Java Programming Exercises

    33/50

    Introduction to Java Programming Exerciseshave decided to create subclasses for each of these types of items. Each of the items will havea few of their own methods and will override the toString() method ofCustomer.

    In Eclipse, continue to use your workspace and project (OrderEntry) from the previousexercise containing the files from the previous exercises,

    Define a New Company Class

    1. Define a Company class, which extends Customer, and includes the attributes andmethods 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, enterCompany in the Name field, and thenclick the Browse button to the right of the Superclass field. Type cus and see thematching list reduced. Select Customer - oe and press OK.

    c. In the Editor window forCompany.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 | GenerateGetters 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 togenerate the constructor as described in step 2(c). Skip step 2(c) if you manuallyenter 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 superclassconstructor 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 superconstructor to invoke: select Customer(String, String, String). Makesure both instance variables are selected. In the drop-down list box Insertion

    point: select After 'discount' and press OK. Notice that the constructoris inserted at the specified place.

    3. Override the toString() method forCompany to return the contact name anddiscount. Include in the return value the superclass details, and format as follows:

    (, %)

    Page 33

  • 8/4/2019 Java Programming Exercises

    34/50

  • 8/4/2019 Java Programming Exercises

    35/50

    Introduction to Java Programming Exercisesorder.setCustomer(DataMan.customer2);

    c. Hint: Use CTRL+F to show a search dialog box. Replace customer2withcustomer5 (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 customerdetails 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, orindividual objects represent different objects, unless the user is made aware of the meaning ofthe subtle differences in the displayed data. Therefore, you are asked to modify your code toexplicitly indicate the object type name in the text that is printed before the rest of objectdetails, as follows:

    [Customer] [Company] [Individual]

    If you manually add the square-bracketed text string before the return values of thetoString() methods in the respective classes, then it would produce a result thatconcatenates [Company] to [Customer], and [Individual] to [Customer] for thesubclasses ofCustomer. 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 itsgetClass() method, which is inherited from the java.lang.Object class. ThegetClass() method returns java.lang.Class object reference, through which you calla getName() method returning a String containing the fully qualified run-time objectname. For example, if you add this line to the Customer class:

    String myClassName = this.getClass().getName();

    the variable myClassNamewill contain a fully-qualified class name that includes thepackage name. The value that is stored in myClassNamewould be oe.Customer.

    To extract the class name only, you must strip off the package name and the dot that precedesthe class name. This can be done by using a lastIndexOf() method in the String classto locate the position of the last dot in the package name, and extract the remaining textthereafter. To do this, add the getClassName() method to the Util class, and call it fromthe toString() method in the Customer class.

    7. Open Util.java in the Code Editor.

    a. Add a publicstaticStringgetClassName() method to determine therun-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

  • 8/4/2019 Java Programming Exercises

    36/50

    Introduction to Java Programming Exercisesb. Save (and compile) Util.java. Note that Eclipse automatically recompiles

    other classes that are dependent on code in Util.java. Eclipse has a built-inclass 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 returnvalue 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 aparameter value this to the Util.getClassName() method? Explain whythe compiler accepts the syntax that is used.

    Page 36

  • 8/4/2019 Java Programming Exercises

    37/50

    Introduction to Java Programming Exercises

    Exercise 11

    Goal

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

    Your Assignment

    Continue to use Eclipse to build on the application classes from the previous practices. Youenhance the DataMan class to hold a method to construct an array ofCustomer objects,and then provide a method to find and return a Customer object for a given ID. The Orderclass 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 Array1. Modify the DataMan class to build an array of customers.

    a. Define a private static array ofCustomer objects named customers.

    b. Initialize the array to a null reference.

    2. Create a public static void method called buildCustomers() to populate the arrayof customers. The array should hold six objects using the fourCustomer objects, theCompany and Individual objects that you have already created.

    a. In the body of the method, first test if the customers variable is not null, andif so, then return from the method without doing anything because a non-null

    reference indicates that the customers array has been initialized. Ifcustomers is null, then you must create the array object to hold the sixcustomer 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, aftercreatingthe array object. Then, delete the static keyword and class name/type beforeeach customer variable name. Modify each variable to be the name of thearray 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 andinitialize the array ofcustomer 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

  • 8/4/2019 Java Programming Exercises

    38/50

    Introduction to Java Programming Exercises

    Modify DataMan to Find a Customer by His or Her ID

    3. Create a public static method called findCustomerById(intcustId), wherethe argument represents the ID of the Customer object to be found. If found, thenreturn the object reference for the matching Customer, otherwise return a nullreference value.

    a. Why is the customer array guaranteed to be initialized when thefindCustomerById() method is called? Thus, you can write code assumingthat the array is populated.

    b. Write a loop to scan through the customers array, obtaining each customerobject reference to compare the custId parameter value with the return valuefrom the getId() method of each customer. If there is a match, then return thecustomer object reference, otherwise return a null.

    c. Save (and compile) yourDataMan 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 changesmade to DataMan. The modifications that you make to OrderEntry.java fix thesyntax errors, and test the code that is added to the DataMan class.

    a. In the Code Editor forOrderEntry.java, locate and modify each line thatdirectly refers to the DataMan.customer variables that previously existed.

    Hint: You can quickly navigate to the error lines by double-clicking the errormessage line in the Problems view. You can also jump from one error to anotherin 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 callto: 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 commandline. Write a loop in the main() method to process the arguments converting each

    from a String into an int, using the Integer.parseInt() method. Useeach integer value in the DataMan.findCustomerById() method parameterto locate and display the customer details.

    d. Save and run the OrderEntry application to test your changes, with thefollowing command line arguments: 1 3 4 99 6

    Hint: Right-click on OrderEntry.java and select Run As | RunConfigurations In the Run Configurations dialog box, select OrderEntry(under Java Application), and click on the Arguments tab on the right pane. Enterthe list of numbers above in the Program arguments: entry field. Click Run.

    Page 38

  • 8/4/2019 Java Programming Exercises

    39/50

    Introduction to Java Programming Exercises

    Modify the Order Class to Hold a List ofOrderItemObjects

    Currently, the Order class has hard-coded creation of two OrderItem objects as instancevariables, 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 nowreplace the two OrderItem variables with an ArrayList that will contain theOrderItem objects. Therefore, you must create methods to add and remove OrderItemobjects to and from the ArrayList.

    5. Define an ArrayList of order items, and replace the OrderItem instancevariables, removing code dependent on the original OrderItem instance variables.

    a. Declare a new private instance variable called items as an ArrayList objectreference. Also, remove (or comment out) the declarations of the two instancevariables called item1 and item2, and the code that is using these variables.

    Use Eclipse to add the import statement forjava.util.ArrayList by right-

    clicking on the Editor window and selecting Source | Organize Imports orpressing CTRL+SHIFT+O.

    b. In the getOrderTotal() method, delete all lines except the return statementwhich returns the current value oforderTotal.

    c. In the showOrder() method, delete the two statements displaying the details ofthe 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 OrderItemto Handle Product Information

    6. Before you create the method to add an OrderItem object to the items list, youmust first modify the OrderItem class to hold the information about the product

    being ordered. Each OrderItem object will represent an order line item. Each orderline item contains information about a product that is ordered, its price, and quantitythat is ordered.

    a. Edit the OrderItem class and add a new instance variable called product.Declare the variable as a privateint, and generate or write thegetProduct() and setProduct() methods. Modify the toString() methodto add the product value between the lineNo and quantity.

    b. Create an OrderItem constructor to initialize the object by using values that aresupplied from the following two parameters: intproductId, doubleitemPrice.

    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

  • 8/4/2019 Java Programming Exercises

    40/50

    Introduction to Java Programming Exercises

    Modify Order to Add Products into the OrderItemList

    7. In the Order class, create a new publicvoid 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 dothis, create a loop to get each OrderItem element from the items list.

    Hint: Use the size() method of the ArrayList object to determine the numberof elements in the list. Use the getProduct() method of the OrderItem tocompare 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 thespecified product does not existin any OrderItem object into the list, thencreate 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 theline number for the OrderItem, by using the setLineNo() method, after anitem 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 theorder. Thus, you must also add the price of each product to orderTotal.

    Hint: Use the getUnitPrice() method from the OrderItem class. Becausethe 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 loopthrough the items list to display each OrderItem object by calling thetoString() method.

    Hint: Use the ArrayListiterator() method to get an Iterator over theArrayList as follows:

    Iterator iter = items.iterator();

    Use Eclipse to add the import statement forjava.util.Iterator by right-clicking on the Editor window and selecting Source | Organize Imports orpressing CTRL+SHIFT+O.

    d. Save (and compile) the Order class, and fix any syntax errors.

    e. Test your changes to the


Recommended