如何将字符串验证为日历输入?

3

这是我第一次在stackoverflow上发帖。我需要帮助将用户输入从字符串转换为日历,并进行验证。

例如,如果用户输入类似于“1”或“hi”的内容。我应该如何验证并提示用户以DDMMYYYY格式(类似于04 02 2015)输入,并显示错误消息。

System.out.print("Enter Date (DD MM YYYY): ");
          input.nextLine();
          String pickUpDate = input.nextLine();
          Calendar pd = stringToCalendarConverter(pickUpDate);

public static Calendar stringToCalendarConverter(String stringToCal) //Converts String to Calendar
{
   try 
   {
     DateFormat df = new SimpleDateFormat("dd MM yyyy"); 
     Date date = df.parse(stringToCal);
     Calendar calendar = new GregorianCalendar();
     calendar.setTime(date);  
     return calendar;
  }
  catch (ParseException n) 
  {
     return null;
  }      

}


请勿编辑问题标题或内容以标记已解决。只需标记已接受的问题即可。 - phuclv
2个回答

1

调用DateFormat.setLenient(boolean),其中一部分内容是在进行严格解析时,输入必须与此对象的格式相匹配。 就像这样:

DateFormat df = new SimpleDateFormat("dd MM yyyy"); 
df.setLenient(false);

然后在循环中调用您的方法(以便在null上重新提示日期)

Calendar pd = null;
while (pd == null) {
    System.out.print("Enter Date (DD MM YYYY): ");
    input.nextLine();
    String pickUpDate = input.nextLine();
    pd = stringToCalendarConverter(pickUpDate);
}

它仍然无法工作。当我将“1”输入日期时,程序崩溃。主线程中的异常:“java.lang.NullPointerException”。DateFormat df = new SimpleDateFormat("dd MM yyyy"); df.setLenient(false); Date date = df.parse(stringToCal); Calendar calendar = new GregorianCalendar(); calendar.setTime(date);
返回日历;
- Dracogon121
它确实起作用了。当输入的日期无效时,您的方法返回null(这就是您在Exception处理程序中所做的,现在它不在宽松模式下,您会得到一个Exception)。在使用返回的日期之前,在main()中添加一个检查。 - Elliott Frisch
啊,我明白了!但是如何提示用户重新输入日期?抱歉,我不太擅长Java,希望你能再帮我一下!谢谢! - Dracogon121
@Dracogon121 最简单的方法是使用循环。我添加了一个示例。 - Elliott Frisch
明白了!谢谢 @Elliot Frisch :) - Dracogon121

0
private static void dateConversion() {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter Date (DD MM YYYY): ");

    String pickUpDate = input.nextLine();        
    stringToCalendarConverter(pickUpDate);
}

public static void stringToCalendarConverter(String stringToCal) //Converts String to Calendar
{
    Calendar calendar = null;
    try {
        DateFormat df = new SimpleDateFormat("dd MM yyyy");
        df.setLenient(true);
        Date date = df.parse(stringToCal);
        calendar = new GregorianCalendar();
        calendar.setTime(date);

    } catch (ParseException n) {    // If the user entered incorrect format, it will be catch here.
        System.out.println("Invalid date format, pls try again.");
        dateConversion();           // Prompt the user to enter valid date.
    } finally{
        if(calendar != null){   
            showActualDate(calendar);
        }
    }
}

private static void showActualDate(Calendar cal){
    System.out.println("Entered ::::" +cal.getTime().toString());
}

我非常有信心,OP不想要一种宽松的“日期格式”。 - Elliott Frisch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接