The objectives of this lab are to use a package structure for the Shop app and also to write re-usable utilies. We will also experiment with Wrapper classes and parsing.
In Eclipse, create a new project called ShopV6.0.
Right-click on the src folder and select New, followed by Package. Enter “models” as the package name:
Create two more packages: “controllers” and “utils”.
Copy the ShopV5.0 files into the ShopV6.0 project to the locations specified in the screen shot below.
When we have copied all the existing code to this new format, you can see above that we have errors! The problem is that the Product class cannot be found in the MenuController and the Store classes (because they are stored in a different package).
In both MenuController and Store, import models.product;
The errors should now be gone
In Eclipse, open ShopV6.0 (if it isn't open already).
In the utils package, create a new class called ScannerInput.
Cut the validNextDouble and validNextInt methods from MenuController and paste them into ScannerInput.
Change the accessor modifier for these methods from private to public. Make each method static.
Add a local Scanner object for each method and import the Scanner class.
Your ScannerInput class should look something like this:
Now that we have the ScannerInput class created, our MenuController class no longer compiles; it doesn't recognise our validNextInt and validNextDouble methods anymore.
To fix this, add this line of code to the import section of MenuController:
import static utils.ScannerInput.*;
Run the app to make sure that all works ok.
When testing the app, you might notice that our dummy reads for emptying the buffer are now causing a problem!
We can get rid of these now and, as we are creating a new Scanner object for each int and double read, we don’t have to worry about emptying our buffers anymore!
In Eclipse, open ShopV6.0 (if it isn't open already).
In the utils package, open the class called ScannerInput.
Rewrite the validNextInt and validNextDouble methods to use Wrapper classes and parsers, as shown in the screen shot below: