Recently, I was given a problem statement to basically enter movie title, release date and their rating based on IMDB and then sort any of the two properties, which was done easily. Now, while entering the date, I was getting a parse error, so I used try and catch block. Now the problem arising here is when let's say I give a wrong value, it says you've entered the wrong date format, re-enter the details. It's not taking the re-entered value, but instead null. Here is the code.
boolean movieQuestion;
while(true){
System.out.println("Do you want to enter movie rating yes or no? ");
String inputString = scanner.next();
movieQuestion =inputString.equalsIgnoreCase("Yes");
if(!movieQuestion){
System.out.println("Come again Later!");
break;
}
System.out.println("Enter the name of the movie: ");
String movieName = scanner.next();
System.out.println("Enter the movie rating(out of 10):");
double rating = scanner.nextDouble();
Date movieDate = null;
try {
System.out.println("Enter the release date(dd-mm-yyyy)");
String inputDate = scanner.next();
movieDate = new SimpleDateFormat("dd-MM-yyyy").parse(inputDate);
} catch (ParseException e){
System.out.println("You've entered the wrong date format");
System.out.println("Enter the release date(dd-mm-yyyy)");
String inputDate = scanner.next();
}
Movie movie = new Movie(movieName,movieDate,rating);
mainMovieSet.add(movie);
}
This is what I tried to avoid breaking of code with an exception.
Date movieDate = null;
try {
System.out.println("Enter the release date(dd-mm-yyyy)");
String inputDate = scanner.next();
movieDate = new SimpleDateFormat("dd-MM-yyyy").parse(inputDate);
} catch (ParseException e){
System.out.println("You've entered the wrong date format");
System.out.println("Enter the release date(dd-mm-yyyy)");
String inputDate = scanner.next();
}
Every time I re-enter the value if a wrong value is given, it just displays a null after the correct value displayed.