【问题标题】:validate an integer AND make it 5 digits验证一个整数并将其设为 5 位数字
【发布时间】:2017-10-05 16:26:48
【问题描述】:

我正在上我的第一个 Java 课程。我需要询问邮政编码。如果他们不输入 5 位数字,我知道如何要求新输入,但如果他们输入非整数,我还如何要求新输入?

这是我所拥有的:

import java.util.Scanner;

public class AndrewDemographics {

    public static void main(String[] args) {
        Scanner stdIn = new Scanner(System.in);
        int zip;                // 5 digit zip

        System.out.print("Enter your 5 digit zip code: ");
        zip = stdIn.nextInt();
        while ((zip < 10000) || (zip > 99999))  {
            // error message
            System.out.println("Invalid Zip Code format.");
            System.out.println("");
            System.out.println("Enter your 5 digit zip code: ");
            zip = stdIn.nextInt();
        } //end if zip code is valid
    }
}

【问题讨论】:

  • 新泽西州大西洋城的邮政编码 08201 怎么样?
  • starts with 0 的邮政编码呢?

标签: java int zipcode


【解决方案1】:

要支持以0 开头的邮政编码,您需要将邮政编码存储在一个字符串中,然后使用正则表达式进行验证是最简单的:

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

如果你想打印错误信息,你可以这样做,它使用nextLine(),所以只需按回车键也会打印错误信息:

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

【讨论】:

  • 补充一点,作为一般规则,如果您输入一个号码,但您不会对该号码进行算术运算(SSN、电话、邮政编码、序列号、型号等),它可能应该存储为字符串。
【解决方案2】:

正如评论所暗示的,您需要考虑以零开头的邮政编码。我想为此,您需要将输入视为字符串:

  1. 检查String 的长度是否为 5 个字符(以匹配 5 个数字)
  2. String 不包含 + 符号,因为 +1234 可以工作
  3. 检查String 是否为有效整数
  4. 检查Integer 是否为正,因为-1234 仍然有效
  5. 你现在有一个介于 00000 和 99999 之间的东西

实践中

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

【讨论】:

  • 感谢您的评论。我会检查 hasNextInt() 是否也属于该范围
  • @Andreas 我已经更新了我的答案。它可能有一些泄漏,但我还没有发现。我避免使用 Regex,因为它显然是 answer-steal。如果您不介意:您的答案显然更有效,最重要的是更美观,我应该删除我的答案还是保留它?
  • 删除了反对票。并保持答案,因为可能不允许 OP 使用正则表达式,所以替代品总是好的。问题通常有不止一个有效答案。 :-)
  • @Andreas 感谢您的反馈和取消投票
【解决方案3】:

以前的带前导零的邮政编码存在问题。需要检查两者是否都是数字且长度为 5 个字符。如果作为数字类型读入,零前导 zip 的长度将是 4 位数。

我的头顶:

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

【讨论】:

  • Short.MAX_VALUE 是 32767,因此您无法处理 32768-99999 范围内的邮政编码。
  • 你说得非常正确,应该喝我的咖啡;)谢谢!
  • 不提示用户是不好的。接受 +8888-1234 等无效值也很糟糕。
【解决方案4】:

我使用 nextLine() 而不是 int 将输入作为字符串输入,因为它说明了以 0 开头的邮政编码,而邮政编码虽然是以数字形式编写的,但实际上并不是一个数值。我觉得构建确定邮政编码是否有效的 if/else 语句的最简单方法是使用 return 语句,该语句会在返回时打破检查,因此我编写了一个方法来检查 zip 的有效性代码:

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
}

那么主要的方法是这样的:

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2014-10-03
    • 2016-11-19
    • 2015-05-26
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    相关资源
    最近更新 更多