簡體   English   中英

Java LocalDate輸入驗證

[英]Java LocalDate input validation

在這個問題上停留了一段時間,希望能得到一些投入。 我想驗證來自用戶輸入的日期,以便可以使用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()

從字符串獲取本地日期的正確方法是使用DateTimeFormatter

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

您以遞歸方式調用該方法,但是忽略了它返回的內容。 更換

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

通過

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

但實際上,您不應該重新發明LocalDate解析。 使用Java API提供的類來做到這一點。 該文檔是您的朋友。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM