When the following code executes, I get a ParseException error:
String date;
Scanner in = new Scanner(System.in);
System.out.println("Please enter the date of birth, in format 'January 2, 2010'");
date = in.nextLine();
in.close();
Date birth = new Date();
birth = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
birthcal.setTime(birth);
I think I understand why, as I haven't sanitized the input. I was wondering what the best way to solve this problem is. Any help in parsing dates would be appreciated.
(PS Another peculiar issue pops up when I try to catch the error, ie:
String date;
Scanner in = new Scanner(System.in);
System.out.println("Please enter the date of birth, in format 'January 2, 2010'");
date = in.nextLine();
in.close();
Date birth = new Date();
try {
birth = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
birthcal.setTime(birth);
The issue here is a NullPointerException . I don't see how this can be. I thought when you initialized with new Date()
, it set a value for it, meaning that the last line of the code will be at least pointing to SOMETHING. Any help on this would also be appreciated.)
I guest that birthcal is a java.util.Calendar class's object reference (I can not see the definition of the reference).
If you change your last line (birthcal.setTime(birth);)
to:
Calendar birthcal = Calendar.getInstance();
birthcal.setTime(birth);
you won't have problems. If you leave
Calendar birthcal = null;
birthcal.setTime(birth);
You will get java.lang.NullPointerException
because your code is trying to set 'birth' to a null.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.