-1

I am writing a program using gui that will validate if a postal code is correctly formated, like K2S, 1W3. But, if i input something like K2S 1W3333333, it will still validate it. Here is my Program:

        @Override
        public void mouseClicked(MouseEvent arg0) {
            String postal =txtInput.getText() ;
            boolean error_found = false;

            for (int j = 0; j < postal.length(); j++){

                //check if charAt j is a letter
                if (j == 0 || j == 2 || j == 5){
                    if (postal.charAt(j) >= 65 && postal.charAt(j) <= 90){
                        ;
                    }
                    else
                        error_found = true;

                }    
                //check if charAt j is a number
                if(j == 1 || j == 4 || j == 6){
                    if (postal.charAt(j) >= 48 && postal.charAt(j) <= 57){
                        ;

                    }
                    else
                       error_found = true;
                }
            }
            if (error_found == true){
                lblResult.setText("Error, please try again. Make sure your code is capital letters and numbers only and 6 characters. Ex: K2S 1W3");

            }
            else
            {
                lblResult.setText("That code is valid!");
            }
            }
            });

} }

JimmyJeans
  • 1
  • 1
  • 2
  • Have you considered using a regular expression? Seems you may be new to programming. That's your best approach. If this is a class assignment and you cannot use a regular expression then you need to maintain a character counter. – mba12 Oct 06 '16 at 21:53
  • Don't do `>= 65`, `<= 90`, `>= 48`, and `<= 57`. It obscures the intent. Use `>= 'A'`, `<= 'Z'`, `>= '0'`, and `<= '9'`. – Andreas Oct 06 '16 at 22:18
  • @Andreas I would but the teacher wants me to do it that way. – JimmyJeans Oct 07 '16 at 00:08
  • Wow, that's a dumb teacher, requiring anybody looking at the code to have memorized the ASCII table in order to understand the code, when the language makes it so easy to write it self-documenting. – Andreas Oct 07 '16 at 04:08

3 Answers3

1

use a regular expression for checking patterns. It'll be easier!

for example

[A-Z]{1}[0-9]{1}[A-Z]{1} 

will match KS2 and 1W3 (not sure what the postcode format is i.e. if the "," needs to part of it or not, if you accept a whitespace character etc!) Either way, regular expressions are the way to go

EDIT assume you need to match exactly above "KS2,1W3" then

^[A-Z][0-9][A-Z],[0-9][A-Z][0-9]$

is the regex that'll do it

stevegal
  • 66
  • 3
  • I don't think we are doing regular expressions yet, but thanks anyway! It will be helpful for me in the future! – JimmyJeans Oct 06 '16 at 22:05
  • According to [Wikipedia](https://en.wikipedia.org/wiki/Postal_codes_in_Canada), they are separated by *space*, not comma. Also note, that when use Java's `matches()` methods, the anchors `^` and `$` are redundant. – Andreas Oct 06 '16 at 22:19
0

The problem is that the if statements won't execute in your program if the index is greater than those values. The simplest way to fix this without changing much is adding this before your for statement.

if(postal.length() != 6)error_found = true; 

If you have a comma in the expression make it 7 from 6.

That will work, but is not the most elegant solution, use a regular expression.

In order to improve what you had to make it more efficient, also break once you find an error so you don't keep going through the

DarkHorse
  • 963
  • 1
  • 10
  • 28
0

The string, "K2S 1W3333333" can be caught be checking for a fixed string length. See the below snippet, particularly the line

int len = postal.length();
if ((len == 7) && (postal.charAt(3) != ' '))

and/or ...

} else if ((len != 6) && (len != 7)) {

After reading some of the basic rules for Postal codes in Canada, here's a quick snippet that checks for validity:

public class App {
    public static boolean checkCode(String postal) {
        if (postal == null || postal.isEmpty()) {
            System.out.println("Empty postal code");
            return false;
        }
        int len = postal.length();
        if ((len == 7) && (postal.charAt(3) != ' ')) {
            System.out.println("Invalid postal code length (7 characters requires space in middle of code)");
            return false;
        } else if ((len != 6) && (len != 7)) {
            System.out.println("Invalid postal code length (6 characters required)");
            return false;
        }
        if (len == 7) {
            postal = postal.replace(" ", "");
            len = postal.length();
        }
        final char[] invalidUpLetters = { 'D', 'F', 'I', 'O', 'Q', 'U' };
        final char[] invalidLowLetters = { 'd', 'f', 'i', 'o', 'q', 'u' };
        for (int i = 0; i < len; ++i) {
            final char c = postal.charAt(i);
            if (i % 2 == 0) {
                if (!Character.isLetter(c)) {
                    System.out.println("Invalid letter at postal code string index: " + i);
                    return false;
                }
                for (int j = 0; j < invalidUpLetters.length; ++j) {
                    if ((c == invalidUpLetters[j]) || (c == invalidLowLetters[j])) {
                        System.out.println("Invalid letter used in postal code, string index: " + i);
                        return false;
                    }
                }
                if ((i == 0) && (c == 'W' || c == 'w' || c == 'Z' || c == 'z')) {
                    System.out.println("First position letter cannot be W or Z");
                    return false;
                }
            } else if ((i % 2 == 1) && (!Character.isDigit(c))) {
                System.out.println("Invalid digit at postal code string index: " + i);
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        args = new String[] { "K2S 1W3333333", "K2S 1W3", "K2S1W3" };
        System.out.println("is valid postal? " + (checkCode(args[0]) ? "Yes" : "No"));
        System.out.println("is valid postal? " + (checkCode(args[1]) ? "Yes" : "No"));
        System.out.println("is valid postal? " + (checkCode(args[2]) ? "Yes" : "No"));
    }
}

This is an extensive check that include logic for checking for letters / digits at the respective indexes, as well as if the first letter is valid or not, as well as if the letters are/supposed to be excluded all together. The snippet also includes a check for adding a space in the middle of the 6-digit postal code or not. Be wary of Characters!

You could also remove the System.out.println()'s from the checkCode() method and stick to using booleans - this would help clear some of the debug and make the code easier to read - for the sake of simplicity (just needed to use the method to check whether a string is a valid Canada postal code or not).

Edit: If you're getting more variation of input postal codes, such as "K2S, 1W3" as stated in your original post, consider normalizing/parsing out characters as shown in my snippet to more easily read postal codes.

Cheers

Nick Bell
  • 516
  • 3
  • 16