L09

Due by the end of Tuesday, 16 March 2021


SUBMIT   /   CHECK

Today's Activities

Programming Activity 1
Download the file ReadNumbers.java. Compile and run the program. It asks you to enter integers. The program defines the array to hold up to 5 integers, so we first try to limit ourselves to enter 5 things.

For example, mix some double numbers to crash the program:

Enter integers below: a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5.5
This will give you the error message:
Exception in thread "main" java.util.InputMismatchException

Modify the program to catch this specific exception (InputMismatchException) so that whenever the program sees an invalid value, it first prints out an error message to the console, and it assigns -1 to that array element. Of course, if the value entered is valid, you must use that value.

Sample output:

Enter integers below: a[0] = 1 a[1] = 2.2 The value was invalid. -1 is assigned to a[1] a[2] = 3 a[3] = four The value was invalid. -1 is assigned to a[3] a[4] = 5f The value was invalid. -1 is assigned to a[4] You entered: [1, -1, 3, -1, -1]

HINT: You will probably need to "flush" Scanner buffer using nextLine() in the catch-block to avoid the unwanted outcome.

Programming Activity 2
Create an exception class NegativeDimensionException. Have it extend IllegalArgumentException.
Programming Activity 3
Download the class Rectangle so that it throws a NegativeDimensionException if the client ever tries to give a Rectangle a negative length or width.
NOTE: We have already seen Rectangle classes that throw exceptions. The only difference is that this time we are throwing an exception from a user-defined class. Do not let that throw you!

But do notice that this time we are allowing zero-sided Rectangles.

Test your revision using the program TestRectangle.

If you've got it right, you should see output very much like this:

Rectangle: (5.0 x 1.5) Exception: NegativeDimensionException: width (-1.5) Rectangle: (5.0 x 0.0) Rectangle: (5.0 x 3.0) Rectangle: (1.5 x 7.0) Exception: NegativeDimensionException: length (-1.5) Rectangle: (0.0 x 7.0) Rectangle: (3.0 x 7.0) Exception: NegativeDimensionException: width (-1.5) Exception: NegativeDimensionException: length (-1.5) Rectangle: (0.0 x 3.0)

Submit this/these files:

You will be graded on the following:

  1. ReadNumbers has had try-block(s) added; it compiles and runs
  2. ReadNumbers catches InputMismatchException
  3. ... prints warning message and stores -1 in proper location
  4. ... continues with loop
  5. ... valid values stored as before
  6. NegativeDimensionException extends IllegalArgumentException
  7. ... has correct constructors
  8. Rectangle throws NegativeDimensionException whenever width set negative
  9. ... and whenever height set negative
  10. ... and never thrown inappropriately
  11. ... each exception thrown has an appropriate message
  12. All code meets the usual style and design criteria

SUBMIT   /   CHECK