【问题标题】:Java LocalDate input validationJava LocalDate 输入验证
【发布时间】:2018-04-08 13:30:57
【问题描述】:

在这个问题上停留了一段时间,希望能提供一些意见。 我想验证用户输入的日期,以便我可以使用 LocalDate 对象执行计算。但是,当输入有效日期时,返回的日期是前一个无效日期,这会引发异常并崩溃。 我错过了什么或做错了什么。

public static void main(String[] args) {            
    Scanner sc = new Scanner(System.in);

    // Accept two dates from the user and return the number of days between the two dates
    numDaysBetween(sc); // calls to the inputDate are inside    

    sc.close();     

} // end main   

public static int[] inputDate(Scanner sc) {     
    System.out.print("Enter Date - In format dd/mm/yyyy: ");        

    while(!sc.hasNext("([0-9]{2})/([0-9]{2})/([0-9]){4}")) {
        System.out.print("That's not a valid date. Enter the date again: ");
        sc.nextLine();                 
    } // end while      
    String dateAsString = sc.nextLine();
    String[] dateArr = dateAsString.split("/");

    int[] dateArrInt = Arrays.asList(dateArr)
            .stream()
            .mapToInt(Integer::parseInt)
            .toArray();
    System.out.println(Arrays.toString(dateArrInt));
    try {
        //LocalDate date = LocalDate.of(dateArrInt[2], dateArrInt[1], dateArrInt[0]);
        LocalDate d = LocalDate.of(Integer.parseInt(dateArr[2]), Integer.parseInt(dateArr[1]), Integer.parseInt(dateArr[0]));
        //System.out.println(d.getDayOfMonth() + "/" + d.getMonthValue() + "/" + d.getYear() );

    } catch(DateTimeException e) {                  
        System.out.print(e.getMessage() + "\n");    
        inputDate(sc);

    } // end catch

    return dateArrInt;
} // end inputDate()

【问题讨论】:

  • 您这样做是为了了解正则表达式,还是希望有可能解析 LocalDate?如果是后者,请查看:stackoverflow.com/questions/8746084/string-to-localdate
  • 为什么不直接使用LocalDate.parse(text)(或您喜欢的任何其他解析器)并在文本格式不正确时捕获并输出异常?
  • Err,你的 main 方法除了创建一个 Scanner 然后关闭它之外什么也没做。一旦它实际调用 inputDate 方法,就会打印正确的值。所以你没有运行你发布的代码。投票结束。
  • JB Nizet,抱歉,我更新了主要内容。我没有发布其他方法,因为这是验证方法给我带来的问题。

标签: java validation date user-input


【解决方案1】:

从字符串中获取本地日期的正确方法是使用 DateTimeFormatter

    String str = "24/09/2017";
    DateTimeFormatter dt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    LocalDate date = LocalDate.parse(str, dt);

【讨论】:

    【解决方案2】:

    您正在递归调用该方法,但您忽略了它返回的内容。替换

    System.out.print(e.getMessage() + "\n");    
    inputDate(sc);
    

    通过

    System.out.print(e.getMessage() + "\n");    
    return inputDate(sc);
    

    但实际上,您不应该重新发明 LocalDate 解析。使用 Java API 提供的类来做到这一点。文档是您的朋友。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多