Java Reference
In-Depth Information
LISTING 11.2
continued
System.out.print ("Enter product code (XXX to quit): ");
code = scan.nextLine();
}
System.out.println ("# of valid codes entered: " + valid);
System.out.println ("# of banned codes entered: " + banned);
}
}
OUTPUT
Enter product code (XXX to quit): TRV2475A5R-14
Enter product code (XXX to quit): TRD1704A7R-12
Enter product code (XXX to quit): TRL2k74A5R-11
District is not numeric: TRL2k74A5R-11
Enter product code (XXX to quit): TRQ2949A6M-04
Enter product code (XXX to quit): TRV2105A2
Improper code length: TRV2105A2
Enter product code (XXX to quit): TRQ2778A7R-19
Enter product code (XXX to quit): XXX
# of valid codes entered: 4
# of banned codes entered: 2
The programming statements in the try block attempt to pull out the zone
and district information, and then determine whether it represents a banned
product code. If there is any problem extracting the zone and district informa-
tion, the product code is considered to be invalid and is not processed further.
For example, a StringIndexOutOfBoundsException could be thrown by either
the charAt or substring methods. Furthermore, a NumberFormatException
could be thrown by the parseInt method if the substring does not contain a
valid integer. A particular message is printed depending on which exception is
thrown. In either case, since the exception is caught and handled, processing
continues normally.
Note that, for each code examined, the integer valid is incremented only if no
exception is thrown. If an exception is thrown, control transfers immediately to
the appropriate catch clause. Likewise, the zone and district are tested by the if
statement only if no exception is thrown.
Search WWH ::




Custom Search