Contacts – Part 1
From Java Bootcamp Resources
-> Module 2
-> 8. Exception Handling
-> Exception Handling Workbooks
, open the folder: contacts
.
Requirements.
Based on the requirements, there are two types of objects:
We can describe each contact using four fields: name
, age
, birth date
and phone number
.
The contact manager is identified by the contacts that it manages. It also performs the actions of adding/removing contacts.
The tasks in this workbook apply to the Contact
class.
Task 1 – Fields
Add the necessary fields to the Contact
class
. Protect each field using the private
keyword.
Task 2 – Research
The constructor will only receive three parameters: name
, phoneNumber
and birthDate
.
The birthDate
that gets passed will automatically determine the age
. Use the hints below to write code that mimics this process:
HINTS:
-
Research how to create an object of the
SimpleDateFormat
class. -
Use the
SimpleDateFormat
object toparse()
aDate
from thebirthDate
String
.- Assume the
birthDate
follows theMM/dd/yyyy
format.
- Assume the
-
Get the current time as a
Date
object. -
Find a method from the Date class that returns milliseconds since 1970 from each date.
-
Get the difference between both time units. This difference is the person's age in milliseconds.
-
Research how to use the
TimeUnit
class to convert from milliseconds to days. Then, divide by 365 to get the years. -
Typecast the result to
int
and update the age field.
IMPORTANT:
-
The
parse
method fromSimpleDateFormat
throws a checked exception. -
It's the caller's job to handle the failure. But, do not
try-catch
inside the constructor. -
Instead, throw the exception from the constructor so that whoever is calling it handles the failure.
Task 3 – Import Contact
At the very top , you'll notice the line: package models;
. This line specifies the folder that Contact
is in.
Inside Main.java
, write import <folder name>.<class name>;
to import the class
. Note, you can autocomplete this step in Visual Studio Code.
Task 4 – Test your code.
-
Inside
main()
,try
to create anew
object of theContact
class. -
If there's a failure,
catch
it and print its message. -
Add a
finally
block that prints:Process Complete
Example output for the birthday: "07/23/1912"
:
Task 5 – Research (again)
If the caller passes a month of 34347
, it should throw a ParseException
. But unless you tell the date formatter to not be "lenient", it will use heuristics and falsely interpret the input.
Example output for a month of 34347
:
So, research how to stop the formatter from being "lenient". The date String
must strictly adhere to the format MM/dd/yyyy
.
Hints:
-
In the documentation, look for a method that can specify whether date parsing should be lenient.
-
You may also look for a similar question on Stack-Overflow.
Final output:
>>: Unparseable date: "34347/23/1912"
>>: Process Complete