验证一个整数并使其成为5位数 [英] validate an integer AND make it 5 digits

查看:126
本文介绍了验证一个整数并使其成为5位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm taking my very first java class. I need to ask for a zip code. I know how to ask for new input if they don't enter 5 digits, but how do I also ask for new input if they enter a non-integer?

这里就是我拥有的:

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


推荐答案

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

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

如果要打印错误信息,可以这样做,使用 nextLine()所以只需按Enter键也会打印错误信息:

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

这篇关于验证一个整数并使其成为5位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆