//An instance of this class provided methods to parse // a standard format US address //PUBLIC INTERFACE // Constructor // AddressParser(String address) // Accessor : Example // String getAddress() : 11200 SW 8 Street, Miami, Florida 33199 // Other Methods // String number() : 11200 // String street() : SW 8 Street // String city() : Miami // String state() : FL // String zipCode() : 33199 public class AddressParser { //Instance Variable private final String address; //Constructor public AddressParser(String address) { validate(address); this.address = address.trim(); } //Accessor public String getAddress() { return this.address; } //************************ Parsing Methods ************************ // number(), street(), city(), state(), zipCode() // All return a String value //(Internal use) Class Constants private static final char SPACE = ' '; private static final char COMMA = ','; //********************* Constructor Helper ************************ // Partial validation/check for standard US address format // AddressException thrown if an invalid format is detected private static void validate(String address) { address = address.trim(); if (address.length() < 16) throw new AddressException("Invalid Length"); //Indexes of first space and comma int space1 = address.indexOf(SPACE); int comma1 = address.indexOf(COMMA); if (space1 < 0 || comma1 < 0) //No space or no comma throw new AddressException("Invalid Address Format"); //Indexes of last space and comma int space2 = address.lastIndexOf(SPACE); int comma2 = address.lastIndexOf(COMMA); if (comma2 == comma1 || space2 == space1) //Only 1 space or 1 comma throw new AddressException("Invalid Address Format"); if (space1 > comma1 || comma2 > space2) //Incorrect comma placement throw new AddressException("Invalid Address Format"); } }