【问题标题】:Problems with java validation for user input用户输入的java验证问题
【发布时间】:2018-10-20 08:43:12
【问题描述】:

我知道有很多关于 Java 输入验证的问题,但无论我读到什么,我似乎都无法让它工作。我希望用户输入出生日期为(MM DD YYYY)。我想验证一下

  1. 用户只输入数字
  2. 他们输入了正确的位数,并且
  3. 数字在正确的范围内。

我第一次尝试使用 int 变量,但我似乎无法将 hasNextInt() 与数字长度和范围结合起来。然后我看到一个帖子说做字符串变量然后使用Integer.parseInt()。我认为如果我使用 (!month.matches("0[1-9]") || !month.matches("1[0-2]") 这会很好,因为它似乎满足了我所有的验证愿望。我在 while 语句中尝试了这个,但它陷入了无限循环。然后我尝试将该代码更改为 if...else 语句并用while(false) 语句包围它。但是,它现在会引发错误,而不是转到我的声明中说修复您的错误。这是我的代码目前的样子:

import java.util.Scanner; //use class Scanner for user input

public class BD {
    private static Scanner input = new Scanner(System.in); //Create scanner

    public static void main(String[] args){
        //variables
        String month;
        int birthMonth;
        String day;
        int birthDay;
        String year;
        int birthYear;
        boolean correct = false;

        //prompt for info
        System.out.print("Please enter your date of birth as 2 digit "+
            "month, 2 digit day, & 4 digit year with spaces in-between"+
            " (MM DD YYYY): ");
        month = input.next();
        //System.out.printf("%s%n", month);  //test value is as expected
        day = input.next();
        year = input.next();

        //validate month value
        while (correct = false){
            if(!month.matches("0[1-9]") || !month.matches("1[0-2]")){
                System.out.println("Please enter birth month as "+
                    "a 2 digit number: ");
                month = input.next();
                //System.out.printf("%s%n", month);
            }
            else {
                correct = true;
            }
        }

        //turn strings into integers
        birthMonth = Integer.parseInt(month);
        birthDay = Integer.parseInt(day);
        birthYear = Integer.parseInt(year);

        //check values are correct
        System.out.printf("%d%d%d", birthMonth, birthDay, birthYear);
    }
}

任何帮助将不胜感激。我还想尝试在没有任何 try/catch 块的情况下进行此验证,因为它们看起来太笨重了。 谢谢!

【问题讨论】:

  • 是否必须使用正则表达式?
  • 使用适当的日期/时间 API 更好地完成日期/时间验证
  • @RoshanaPitigala 不,使用正则表达式不是强制性的。正是我在网上找到的似乎满足了我所有的验证要求。

标签: java validation input


【解决方案1】:

如果你想使用正则表达式,你可以试试这个

    while(!(Pattern.matches("(0)[1-9]{1}|(1)[0-2]",month)))
    {
           System.out.println("Enter again \n");
           month=input.next();
    }

要使此代码正常工作,您需要包含正则表达式包,方法是在程序的开头使用它

  import java.util.regex.*;

我们的正则表达式分为两部分 "(0)[1-9]{1}" ,这将首先确保字符串包含“0”,然后是 1-9 之间的任何数字.而“{1}”将确保它只出现一次。

如果需要,类似地编写日期和年份的代码。

【讨论】:

  • 谢谢。这行得通,你让我的正则表达式看起来更好更短:)
【解决方案2】:

像这样使用DateTimeFormatter

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd yyyy");

try {
    LocalDate date = LocalDate.parse(input, formatter);
} catch (DateTimeParseException e) {
    // Thrown if text could not be parsed in the specified format
}

【讨论】:

  • 感谢您提供有关 DateTimeFormatter 的信息。我不知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2016-03-15
  • 1970-01-01
  • 2014-06-04
  • 2011-07-09
  • 2019-10-17
相关资源
最近更新 更多