230k views
5 votes
LAB: Parsing dates in M/D/Y format

Complete main() to read dates from input, one date per line. Each date's format must be as follows: 03/20/1990. Any date not following that format is incorrect and should be ignored. (Assume that days and months are always given with two digits, for example 03 instead of 3.) Use the substring() method to parse the string and extract the date. The input ends with END on a line alone. Output each correct date as: March 20, 1990.
Ex: If the input is:
03/20/1990
April 2 1995
07/05/2020
December 13, 2003
END
Then the output is:
March 20, 1990
July 5, 2020

1 Answer

3 votes

Answer:

Step-by-step explanation:

The following is written in Java and takes in a single input, tests if it is in the correct format and then outputs the new desired format.

import java.util.*;

import java.util.regex.Pattern;

class ChangeDate

{

public static void main(String args[])

{

String mo,da,yr;

Scanner input=new Scanner(System.in);

boolean next = true;

while (next == true) {

System.out.print("Enter month::");

String userDate = input.nextLine();

if (userDate.equals("-1")) {

next = false;

}

if (Pattern.matches("\\d\\d\\S\\d\\d\\S\\d\\d\\d\\d", userDate)) {

mo = userDate.substring(0, 2);

da = userDate.substring(3, 5);

yr = userDate.substring(6, 10);

System.out.println(getMonth(mo) + " " + da + ", " + yr);

}

}

}

public static String getMonth(String month) {

switch (month) {

case "01":

return "January";

case "02":

return "February";

case "03":

return "March";

case "04":

return "April";

case "05":

return "May";

case "06":

return "June";

case "07":

return "July";

case "08":

return "August";

case "09":

return "September";

case "10":

return"October";

case "11":

return"November";

case "12":

return "December";

default:

return "Wrong Month Date";

}

}}

LAB: Parsing dates in M/D/Y format Complete main() to read dates from input, one date-example-1
User Stamm
by
5.5k points