这个问题已经卡了一段时间,希望得到一些意见。我想验证用户输入中的日期,以便可以使用 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 提供的类来执行此操作。文档是您的朋友。