A lot of programming involves string manipulation. This lab explores tools to aid this process.
Oracle Java Tutorial links
- Search, parse and build strings.
- Search, parse, and replace strings by using regular expressions.
- Use string formatting.
For the following exercise, make use of the classes java.util.StringTokenizer, java.util.regex.Matcher and java.util.regex.Pattern wherever reasonable.
Postcodes in the UK have a specific format (Wikipedia entry). They contain two groups of letters and numbers separated by a single space. The acceptable formats are listed below (where A is a letter and 9 is a digit):
AA9A 9AA A9A 9AA A9 9AA A99 9AA AA9 9AA AA99 9AA
A valid postcode (for this exercise) is a string which conforms to the format above and where the letters may be upper or lower case. A canonical postcode is one which is valid, and contains only upper case letters.
Create a class CheckAddress in the package strings containing the following methods:
public static boolean isValidPostcode(String postcode) public static boolean isCanonicalPostcode(String postcode) public static String getCanonicalPostcode(String postcode)
The first two methods should return true if a postcode is valid and canonical respectively. The final method should return the canonical version if supplied a valid postcode, and the empty string if the supplied postcode is invalid.
Next, lets work with addresses. There are guidelines on how to address mail properly. For this assignment, an address is valid if:
- It contains at least a street address, a city and a postcode, in that order.
- The street address must be separated from the city by a comma (','), a line break ('\n') or both.
- The city may be separated from the postcode by a space, a comma, a line break or both comma and line break.
- There may be more than one address line before the city, each separated by a comma, a line break or both.
In addition, an address is considered canonical if:
- Only line breaks are used to separate lines, and there are no commas.
- The city and the postcode are each on separate lines.
- The postcode is canonical.
- The city is entirely upper case.
Add the following methods to your class
public static boolean isValidAddress(String address) public static boolean isCanonicalAddress(String address) public static String getCanonicalAddress(String address)
The first two methods should return true if an address is valid and canonical respectively. The final method should return the canonical version if supplied a valid address, and the empty string if the supplied address is invalid.
An automated test has been created for this exercise: CheckAddressTest.java.