Week 6 : File I/O and Exception Handling solution


Original Work


5/5 - (2 votes)

Question 1

Create a file numbers.txt as follows:


(a) Create a class MyFileManager having the main() loop. Using the BufferedReader class and the try-catch-finally block, read the contents of numbers.txt.

(b) Inject an exception by giving the name of a non-existent file e.g. foo.txt. Remember to release resources in the finally block.

(c) Write a user-defined exception – call it NegativeNumberException – to reject negative numbers while reading a file.

Create a class MyValidator that validates input. [Hint: validateNumbers(…) throws NegativeNumberException] The exception handling should be such that the programme continues reading the file even after encountering a negative number.

(d) We have discussed in class that exception handling should not be used for input validation.
Modify the validateNumbers(…) method from part (c) to use input validation for handling negative numbers gracefully.

Question 2 – Triangle Class, Take 3

Refer to the javadocs for the java.lang.Comparable interface.

In Lab #5 Question 1, we focused on the return value, i.e. “a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.”

Now, provide the full implementation of the specification by throwing the NullPointerException and the ClassCastException.

Question 3
Create a Flight class and a Flight Manager class as follows:

The FlightManager will

read the file 2015.silkair.csv to obtain a list of Flight instances,
sort the Flight instances according to Flight Number, and
write the sorted Flight Numbers to the file sorted.silkair.csv
print the file sort.silkair.csv