Time to get your hands dirty, and play a litle with exceptions.
First, create the following Exception class:
- StringTooLongException subclass of Exception
- Constructor that takes a single parameter "message"
(calls the superclass constructor passing this message)
Next, create a class MyScanner, with the following methods:
- Constructor, which takes as an input paramter a variable of type
Scanner and an integer maxStringLength
- boolean hasNext(), which returns true if the contained scanner
has a next token
- string nextString(), which calls nextLine() on the contained
Scanner. If the next line has a length longer than
the maxStringLength, throw a StringTooLongException. Otherwise,
return the next line
Finally, create a main program that:
- Creates a new scanner using System.in
- Creates a new MyScanner using this scanner and 10 (use a constant for the 10!)
- Goes through each line (using hasNext() and nextString())
printing out all lines whose length is less than or equal to 10.
Strings with a length > 10 should be skipped. You'll need to use
a try/catch for this!
If you have time, extend your main as follows:
- Main should first try to create a new scanner based on the
filename passed in as a command line parameter (that is,
args[0]). If no file exists, create a scanner using
System.in. You'll need to use try/catch for this!
- Creates a new MyScanner using this scanner, and a maximum string
length of 10 (this should be a constant!) (this is unchanged from
previous version of main)
- Goes through each line of the input file (using hasNext() and
nextString()), printing out all lines that have a length > 0 and
<= maximum string length. Strings that have a length == 0 or
> maximum string length should be skipped. You'll need to use
try/catch for this! (this is unchanged from
previous version of main)