I'm wondering how I can turn my UK postcode validator into a US postcode validator. Currently my program reads postcodes from a text file and validates whether they are valid UK postcodes. This works well but I would like too read in US postcodes instead of UK postcodes and then validate them. Below is my current program.
package postcodesort;
import java.util.*;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
// Create the FileReader object
try {
fileReader = new FileReader("usvalidcodes.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
if(zipCodeValidator.isValid(str)){
System.out.println(str + " is valid");
}
else{
System.out.println(str + " is not valid");
}
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
}
}
And here is the part of code which does the validating via a regex.
package postcodesort;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author ec1312017
*/
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zipCode);
return matcher.matches();
}
}
I have also included a small selection of the data within the text file to be read in.
"01","35005","AL","ADAMSVILLE",86.959727,33.588437,10616,0.002627
"05","72001","AR","ADONA",92.903325,35.046956,494,0.00021
"06","90804","CA","SIGNAL HILL",118.155187,33.782993,36092,0.001213
Any help is appreciated and please feel free to ask any questions.