validate an integer AND make it 5 digits

戏子无情 提交于 2019-12-02 08:14:23

To support zip codes starting with 0, you need to store the zip code in a String, and then it's easiest to validate it using a regex:

Scanner stdIn = new Scanner(System.in);
String zip;
do {
    System.out.print("Enter your 5 digit zip code: ");
    zip = stdIn.next();
} while (! zip.matches("[0-9]{5}"));

If you want to print error message, you can do it like this, which uses nextLine() so simply pressing enter will print error message too:

Scanner stdIn = new Scanner(System.in);
String zip;
for (;;) {
    System.out.print("Enter your 5 digit zip code: ");
    zip = stdIn.nextLine().trim();
    if (zip.matches("[0-9]{5}"))
        break;
    System.out.println("Invalid Zip Code format.");
    System.out.println();
}

As the comment suggests, you will need to take into account zip code starting with zero. I guess for that, you'll need to consider the input as a String:

  1. check if the String is 5 characters long (to match the 5 digits)
  2. String does not contain + sign as +1234 would work
  3. check if the String is a valid integer
  4. check if the Integer is positive as -1234 would be still valid
  5. you now have something between 00000 and 99999

In practice

public static void main(String[] args){

    Scanner stdIn = new Scanner(System.in);
    String userInput;
    int zipCode = -1;

    // flag to stop spamming the user
    boolean isValid = false;

    while (!isValid) {
        // ask the user
        System.out.print("Enter your 5 digit zip code: ");

        userInput = stdIn.next();

        // it should be 5 digits so 5 charaters long:
        if (userInput.length() == 5 && !userInput.contains("+")) {
            try {
                zipCode = Integer.parseInt(userInput);
                if (zipCode > 0) {
                    isValid = true;
                }
            }
            catch (NumberFormatException e) {
                // do nothing
            }
        }
        System.out.println("Zip code is invalid!");
    }

    System.out.println("You have selected the zip code: " + zipCode);
}

There is an issue with zip codes with leading zeros in previous. There needs to be a check if both is a number and is 5 characters in length. A zero leading zip would be 4 digits in length if read in as a number type.

Top of my head:

String zip = null;
do {
  zip = stdIn.next();
  try {
    Integer.parseInt(zip); // this will throw exception if not a number
  } catch (NumberFormatException e) {
    continue; // this will start the next loop iteration if not a number
  }
} while (zip.length() != 5); // this will start the next iteration if not 5 characters

I took the input as a String using nextLine() rather than an int because it accounts for zip codes starting with 0, and a zip code, although written numerically, isn't really a numerical value. I felt that the easiest way to structure the if/else statements determining if the zip code was valid was to use return statements that would break out of the checks at the return, so I wrote a method that would check for the validity of the zip code:

public static boolean checkValidZip(String zip) {
    if (zip.length() != 5) {                            //invalid if not 5 chars long
        return false;
    }

    for (int i=0; i<zip.length(); i++) {                //invalid if not all digits
        if (!Character.isDigit(zip.charAt(i))) {
            return false;
        }
    }
    return true;                                        //valid if 5 digits
}

The main method then, looks like this:

public static void main(String[] args) {
    Scanner stdIn = new Scanner(System.in);
    String zip = "";                                    //5 digit zip
    boolean valid = false;
    boolean allNums = true;

    while (!valid) {
        System.out.print("Enter your 5 digit zip code: ");
        zip = stdIn.nextLine();

        valid = checkValidZip(zip);

        if (!valid) {
            System.out.println("Invalid Zip Code format.");
            System.out.println("");
        }
    }
    //end if zip code valid
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!