[英]How check if user input is plain text or date in java
我有下面的 java 代码,如果用户输入指定格式的日期(例如 2011-11-11)它可以工作,但是当用户输入纯文本(例如“hello”、“yes”)时程序崩溃。 该代码将用户输入日期与当前日期进行比较并执行操作。 在程序可以继续之前,我如何检查以确保用户输入日期而不是纯文本。 这是代码:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println("Enter valid date e.g yyyy-mm-dd: ");
String date = sn.next();
LocalDate startDate = LocalDate.parse(date, formatter); //I don't want the program to accept 'startDate' as test, it should be date of specified förmat before jumping to try and catch.
LocalDateTime lt = LocalDateTime.now();
LocalDate currentDate = lt.toLocalDate(); // for type match, I removed time stamp from the localdatetime
try {
for (obj result : list) {
if (startDate.isBefore(currentDate)) {
System.out.println(result);
} else {
System.out.println("");
}
}
} catch (DateTimeException e) {
System.out.println ( "ERROR: " + e );
}
您可以在循环中捕获 DateTimeParseException(在日期无效的情况下抛出)。
LocalDate startDate = null;
while(true) {
System.out.println("Enter valid date e.g yyyy-mm-dd: ");
String date = sn.next();
try {
startDate = LocalDate.parse(date, formatter);
break;
} catch(DateTimeParseException ex) {
System.out.println("Invalid date entered!");
}
}
您可以使用正则表达式来获取日期输入。 然后将字符串转换为日期。 查看示例代码:
System.out.print("Please enter Date: ");
String date = console.nextLine();
while(!date.matches("([0-9]{2})\\([0-9]{2})\\([0-9]{4})")) {
System.out.println("Please enter correct date format");
date = console.nextLine();
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(date, formatter);
有很多方法可以将字符串转换为日期,您可以使用任何一种方法。 请参阅此链接以供参考( 使用 java8 将字符串转换为日期)
DateTimeParseException
使用try-catch包围您对LocalDate.parse
的调用,以捕获遇到错误输入文本时抛出的DateTimeParseException
。
try{
ld = LocalDate.parse( input ) ;
} catch ( DateTimeParseException e ) {
… handle bad input from user
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.