有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java验证整数并将其设为5位数

我正在上我的第一堂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
    }
}

共 (4) 个答案

  1. # 1 楼答案

    在前面的示例中,邮政编码前导零存在问题。需要检查两者是否都是数字,长度是否为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
    
  2. # 2 楼答案

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

    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
    }
    
  3. # 3 楼答案

    要支持以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(),因此只需按enter键也将打印错误消息:

    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();
    }
    
  4. # 4 楼答案

    正如评论所建议的,您需要考虑从零开始的邮政编码。我想,你需要把输入看作一个字符串:

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