In: Computer Science
In Java with Indentations Please!!!!
4.16 LAB: Parsing dates
Complete main() to read dates from input, one date per line. Each date's format must be as follows: March 1, 1990. Any date not following that format is incorrect and should be ignored. Use the substring() method to parse the string and extract the date. The input ends with -1 on a line alone. Output each correct date as: 3/1/1990.
Ex: If the input is:
March 1, 1990 April 2 1995 7/15/20 December 13, 2003 -1
then the output is:
3/1/1990 12/13/2003
Below is your code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class ParsingDates {
public static void main(String[] args) throws ParseException {
List<String> validDates = new ArrayList<>();
Scanner sc = new Scanner(System.in);
String input = "";
// list to check if month is valid
List<String> validMonths = Arrays.asList("January", "February",
"March", "April", "May", "June", "July", "August", "September",
"October", "November", "December");
// loop till -1 is entered
while (!input.equals("-1")) {
// getting complete date
input = sc.nextLine();
// check if -1 is entered or not
if (!input.equals("-1")) {
// check if date contains spaces
if (input.indexOf(' ') != -1) {
// getting the month name
String monthName = input.substring(0, input.indexOf(' '));
// validating if month entered is correct and valid
if (validMonths.contains(monthName)) {
// splitting date to day, month and year
String words[] = input.split(" ");
// checking if date contains all three day, month and
// year
if (words.length == 3) {
// checking if year is valid and is of 4 letters
if (words[2].length() == 4) {
// checking if comma is there after day
if (words[1].indexOf(',') != -1) {
String day = words[1].substring(0,
words[1].indexOf(','));
// checking if day is valid
if (Integer.parseInt(day) <= 31) {
// parsing the month number and year
String year = words[2];
Date date = new SimpleDateFormat("MMMM")
.parse(monthName);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String monthNum = (cal
.get(Calendar.MONTH) + 1) + "";
// adding the valid date in the list
validDates.add(monthNum + "/" + day
+ "/" + year);
}
}
}
}
}
}
}
}
sc.close();
// printing result
for (String date : validDates) {
System.out.println(date);
}
}
}
Output
3/1/1990 12/13/2003