2

I'm having a few issues with my zip code validator which reads a text file with UK postcodes then returns true or false after validation.

Below is the section of code I'm having issues with particularly (ZipCodeValidator) which is public and should be declared in a file called ZipCodeValidator.java. And then (Zip) which cannot find symbol.

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);

    public boolean isValid(String zipCode) {
        Matcher matcher = pattern.matcher(zip);
        return matcher.matches();
    }
}

And below here is the entire program for reference. Any help is appreciated.

package postcodesort;

import java.util.*;
import java.util.Random;
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.zip.ZipFile;
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("postcodes1.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();
        }

    }
}

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);

    public boolean isValid(String zipCode) {
        Matcher matcher = pattern.matcher(zip);
        return matcher.matches();
    }
}
  • Have you ever checked your regex on regex101 ? – Marged Jan 24 '16 at 00:31
  • I've used the regex before in another simpler program that didn't read from a text file. It's when I added the read file code thats when the problems arose like the ones I specified above but thanks for the regex 101 tip off :) –  Jan 24 '16 at 00:42
  • Did you try without the closing $ ? – Marged Jan 24 '16 at 00:44
  • No but I'm not seeing how that would fix my issues. Seems like It wouldn't solve the issues I'm having. –  Jan 24 '16 at 00:48
  • If your regex worked before and your loop does read the file and is able to print the values your problem could be caused by a stray space or newline character – Marged Jan 24 '16 at 00:53
  • Provide some examples for a valid code, not everybody lives in the UK ;-) – Marged Jan 24 '16 at 01:00
  • ME7 9AA - EH4 7SJ etc –  Jan 25 '16 at 13:33
  • Ok, so the uppercase issue has been solved (thanks for that) and I changed zip to zipCode which solved the problem but ZipCodeValidator still isn't playing along. This is the new error message: class ZipCodeValidator is public, should be declared in a file named ZipCodeValidator.java. Please help :) –  Jan 25 '16 at 13:33
  • Are both classes in the same file ? This doesn't work for Java, but it into a separate file. Hit Ctrl-N and choose "class", then move your code into that newly created class. – Marged Jan 25 '16 at 13:35
  • So I've moved the code into a new class which looks like this now: –  Jan 25 '16 at 13:50
  • 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(); } } –  Jan 25 '16 at 13:50
  • And the result is ? I expect it is working now. – Marged Jan 25 '16 at 13:54
  • I'm having trouble posting the code so it appears in one big paragraph. So its basically the section of code that I have had trouble with and now it appears of but an error appears saying: run: Exception in thread "main" java.lang.NullPointerException at postcodesort.PostCodeSort.main(PostCodeSort.java:56) Java Result: 1 BUILD SUCCESSFUL (total time: 3 seconds) –  Jan 25 '16 at 13:56
  • I think it is time to create a new question because you are mixing different problems. But before doing so please check if you find a recipe here on stackoverflow how to solve NPEs. If you can't solve your problem this way post the code and mention which is line 56 because we would have to guess otherwise. – Marged Jan 25 '16 at 13:58
  • Hang on it works now. For some reason the text file was missing :) Thanks for the help. Really appreciated :) –  Jan 25 '16 at 13:59

1 Answers1

0

Possibly a copy+paste issue, but Matcher matcher = pattern.matcher(zip); doesn't match the method parameter zipCode. Do you have zip defined somewhere else, and possibly validating against that?

It's when I added the read file code thats when the problems arose like the ones I specified above

Make sure you clean up the String before you pass it in. To remove any leading or trailing whitespace characters use

if(zipCodeValidator.isValid(str.strip())){

lastly, your regex only matches upper case. Make sure you allow all cases by using

str.strip().toUpperCase()

or changing your Regex:

private static Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • Ok, so the uppercase issue has been solved (thanks for that) and I changed zip to zipCode which solved the problem but ZipCodeValidator still isn't playing along. This is the new error message: class ZipCodeValidator is public, should be declared in a file named ZipCodeValidator.java. Please help :) –  Jan 25 '16 at 13:32