Objectives

XML · Exception Handling · Validate User Input · ShopV5.0 · DVD3.0

Shop V5.0 - Exceptions

In this practical, you will continue working on Shop V5.0.

Adding Exception Handling

In the Driver class, put a try and catch block around each potential read of data that could throw an exception (nextLine() and next() are ok).

Revisit your lecture notes on this topic if you need guidance.

Run your program and test your user input to ensure that your exception handling is correctly implemented e.g. enter String data when a double or int is expected.

Menu Driven DVD Specification (Phase 3)

In this practical, you will create a new project and copy in the code from DVDLibraryV2.0. You will then extend the code to allow the user to save the DVDs to an XML file and to load the DVDs from an XML file.

  • Create a new project called DVDLibraryV3.0.

  • In your Windows Explorer / Mac Finder, copy the src java files from DVDLibraryV2.0 to the src folder in your new project, DVDLibraryV3.0.

  • NOTE: a copy of the completed DVDLibraryV2.0 is available here.

Setting up the Component for Serializing

Download the following XStream jar file and incorporate it into your DVDLibraryV3.0 project:

Library class

In the Library class:

  • add a load() method that throws an Exception. This method should read the contents of the dvd.xml file into the ArrayList of DVDs.

  • add a save() method that throws an Exception. This method should write the contents of the ArrayList of DVDs to the dvd.xml file.

Driver class - Save DVDs

Add a fifth option to the menu: 5) Save DVDs to dvds.xml.

Add a case 5 to the switch statement. Then, within a try and catch block, call the save() method you wrote in the Library class.

Driver class - Load DVDs

Add a sixth option to the menu: 6) Load DVDs from dvds.xml.

Add a case 6 to the switch statement. Then, within a try and catch block, call the load() method you wrote in the Library class.

Test your code

Run the project.

  • Test option 5 and make sure that your DVDs are stored to an XML file.

  • You should have a new XML file that looks something like this:

<object-stream>
  <list>
    <DVD>
      <title>The Matrix</title>
    </DVD>
    <DVD>
      <title>Sicario</title>
    </DVD>
    <DVD>
      <title>The Grinch</title>
    </DVD>
  </list>
</object-stream>

Exit your application and run it again.

  • Test option 6 and make sure that your DVDs are loaded back into your dvd ArrayList correctly.

Exceptions

Each time you read in an int in the Driver class, add a try and catch so that your program won't crash if you enter a non-numeric value.

Solutions

The solution to the ShopV5.0 exercise is here.

The solution to DVD phase 3 is here.