Question

In: Computer Science

Your task is to open a file containing a list of dates in various formats, read...

Your task is to open a file containing a list of dates in various formats, read each date, determine if it is a valid format and print it in **ISO 8601 format**(YYYY/MM/DD) to console. The list will be terminated by a `-1`.

There are **two** valid formats:
- plain-language format: <Month> <Day>, <Year> where Day and Year are valid integers. ex. `March 3, 1990`.
- reversed ISO format, `DD/MM/YYYY` (Note that we aren't concerned with the precise ordering of month and day; the format is valid if it is 3 valid integers in `N/N/N` format, with the year (the largest number) at the end).
All other date formats should be ignored.

When a valid date is detected print, a String of the date converted into `YYYY/MM/DD` format. For the above example, `March 3, 1990` gets converted to `1990/03/03`. The string `03/03/1990` would likewise get reversed to `1990/03/03`.

Note that the day and month integers need to be left-padded with zeros to two places if not already double-digit, ie. '1' becomes '01' and so on. The `printDateISOFormat()` function created for you will need to be updated to do this.

You do not need to submit a class with a main method for the lab as the autograder has that already. However, it might be easiest for you to test this lab in your own environment.    Our class with the main method looks like this:

import java.io.FileNotFoundException;
import java.io.IOException;

public class RunMe {
    
    public static void main(String[] args) throws IOException, FileNotFoundException {
        DateParser parser = new DateParser();
        parser.readFile();       
    }
}

Here are some examples of possible input to your parser:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class DateParser {
    // Converts a month name to an integer format
    public static int getMonthAsInt(String monthString) {
        int monthInt;

        // Java switch/case statement
        switch (monthString) {
            case "January":
                monthInt = 1;
                break;
            case "February":
                monthInt = 2;
                break;
            case "March":
                monthInt = 3;
                break;
            case "April":
                monthInt = 4;
                break;
            case "May":
                monthInt = 5;
                break;
            case "June":
                monthInt = 6;
                break;
            case "July":
                monthInt = 7;
                break;
            case "August":
                monthInt = 8;
                break;
            case "September":
                monthInt = 9;
                break;
            case "October":
                monthInt = 10;
                break;
            case "November":
                monthInt = 11;
                break;
            case "December":
                monthInt = 12;
                break;
            default:
                monthInt = 00;
        }

        return monthInt;
    }

    // Prints the given numeric information in ISO 8601 YYYY/MM/DD format.
    public static void printDateISOFormat(int inputYear, int inputMonth, int inputDay) {
        // TODO: modify so that days and months that are single-digit are left-padded
        // with zeros to two digits (ie. '9' becomes '09', '12' stays as '12', etc.)
        System.out.println(inputYear + "/" + month + "/" + day);
    }


    /** Check that the input has the correct numeric data already(yyyy, mm, dd)
    *   but in reversed order (dd/mm/yyyy)
    *   The year will never be smaller than the month or day
    */
    public static boolean validateReverseOrder(String input) {

        return true;
    } 



    /** Valid English format is <Month> <Day>, <Year>
    *   all other formats (besides the reversed order above) 
    *   are considered invalid
    *   For students to complete
    */
    public static boolean validateFormat(String[] input) {

        return true;
    }

    /** For students to complete
    *   Prompts the user for a filename, opens said file, reads in dates and 
    *   converts the valid ones to ISO 8601 (YYYY/MM/DD) format
    *   call printDateISOFormat() to print dates to console
    */
    public void readFile() throws IOException, FileNotFoundException {
        Scanner scnr = new Scanner(System.in);
        String filename = scnr.nextLine().trim();  //use trim() here or you'll have a newline on your filename
        
    }

}

Solutions

Expert Solution

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class DateParser {
// Converts a month name to an integer format
public static int getMonthAsInt(String monthString) {
int monthInt;

// Java switch/case statement
switch (monthString) {
case "January":
monthInt = 1;
break;
case "February":
monthInt = 2;
break;
case "March":
monthInt = 3;
break;
case "April":
monthInt = 4;
break;
case "May":
monthInt = 5;
break;
case "June":
monthInt = 6;
break;
case "July":
monthInt = 7;
break;
case "August":
monthInt = 8;
break;
case "September":
monthInt = 9;
break;
case "October":
monthInt = 10;
break;
case "November":
monthInt = 11;
break;
case "December":
monthInt = 12;
break;
default:
monthInt = 00;
}

return monthInt;
}

// Prints the given numeric information in ISO 8601 YYYY/MM/DD format.
public static void printDateISOFormat(int inputYear, int inputMonth, int inputDay) {
// TODO: modify so that days and months that are single-digit are left-padded
// with zeros to two digits (ie. '9' becomes '09', '12' stays as '12', etc.)
   String day="",month="";
   if(inputDay<10)
       day="0"+inputDay+"";
   if(inputMonth<10)
       month="0"+inputMonth+"";
System.out.println(inputYear + "/" + month + "/" + day);
}


/** Check that the input has the correct numeric data already(yyyy, mm, dd)
* but in reversed order (dd/mm/yyyy)
* The year will never be smaller than the month or day
*/
public static boolean validateReverseOrder(String input) {
   String mm[]=input.split("/");
   int d=0,m=0,y=0;
   try {
       if(mm[0].charAt(0)=='0')
           d=mm[0].charAt(1)-'0';
       else
           d=Integer.parseInt(mm[0]);
       if(mm[1].charAt(0)=='0')
           m=mm[1].charAt(1)-'0';
       else
           m=Integer.parseInt(mm[1]);
       y=Integer.parseInt(mm[2]);
   }
   catch(NumberFormatException e) {
       return false;
   }
   if(y<m||y<d)
       return false;
return true;
}

/** Valid English format is <Month> <Day>, <Year>
* all other formats (besides the reversed order above)
* are considered invalid
* For students to complete
*/
public static boolean validateFormat(String[] input) {
   if(getMonthAsInt(input[0])<1)
       return false;
   int d=0,y=0;
   try {
       input[1]=input[1].substring(0,input[1].length()-1);
       if(input[1].charAt(0)=='0')
           d=input[1].charAt(1)-'0';
       else
           d=Integer.parseInt(input[1]);
       y=Integer.parseInt(input[2]);
   }
   catch(NumberFormatException e) {
       return false;
   }
   if(y<d)
       return false;
return true;
}

/** For students to complete
* Prompts the user for a filename, opens said file, reads in dates and
* converts the valid ones to ISO 8601 (YYYY/MM/DD) format
* call printDateISOFormat() to print dates to console
*/
public void readFile() throws IOException, FileNotFoundException {
Scanner scnr = new Scanner(System.in);
String filename = scnr.nextLine().trim(); //use trim() here or you'll have a newline on your filename
File f=new File(filename);
BufferedReader bf=new BufferedReader(new FileReader(f));
String l;
while((l=bf.readLine())!=null)
{
   if(l.equals("-1"))
       break;
   if(l.contains("/")) {// for checking dates containing '/'
       if(validateReverseOrder(l)) {
           String mm[]=l.split("/");
       int d=0,m=0,y=0;
           if(mm[0].charAt(0)=='0')
           d=mm[0].charAt(1)-'0';
       else
           d=Integer.parseInt(mm[0]);
       if(mm[1].charAt(0)=='0')
           m=mm[1].charAt(1)-'0';
       else
           m=Integer.parseInt(mm[1]);
       y=Integer.parseInt(mm[2]);
       printDateISOFormat(y,m,d);
       }
   }
   else {
       if(validateFormat(l.split(" "))) {
           String input[]=l.split(" ");
           int d=0,y=0,m=0;
           input[1]=input[1].substring(0,input[1].length()-1);
       if(input[1].charAt(0)=='0')
           d=input[1].charAt(1)-'0';
       else
           d=Integer.parseInt(input[1]);
       y=Integer.parseInt(input[2]);
       m=getMonthAsInt(input[0]);
       printDateISOFormat(y,m,d);
       }
   }
}

}

}

/////////////////////Sample Input

//////////////////Sample Output


Related Solutions

Query the user for the name of a file. Open the file, read it, and count...
Query the user for the name of a file. Open the file, read it, and count and report the number of vowels found in the file. Using C++.
1. List the guidelines for effective documentation. Describe the purpose of the various formats that exist...
1. List the guidelines for effective documentation. Describe the purpose of the various formats that exist for documenting care. 2. Explain variations in techniques for assessing vital signs in adults vs. an infant vs child. (Example – where to take the temperature or the blood pressure) 3. Pain Assessment Scales for Adults and Peds
Please Use Python 3.The Problem: Read the name of a file and then open it for...
Please Use Python 3.The Problem: Read the name of a file and then open it for reading. Read the name of another file and then open it for output. When the program completes, the output file must contain the lines in the input file, but in the reverse order. • Write the input, output, and the relationship between the input and output. • Develop the test data (A single test will be alright). Make the input file at least 3...
Write a C++ program to read a data file containing the velocity of cars crossing an...
Write a C++ program to read a data file containing the velocity of cars crossing an intersection. Then determine the average velocity and the standard deviation of this data set. Use the concept of vector array to store the data and perform the calculations. Include a function called “Standard” to perform the standard deviation calculations and then return the value to the main function for printing. Data to use. 10,15,20,25,30,35,40,45,50,55. Please use something basic.
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional int array. Your program must (1) read the name of the file from the command-line arguments, (2) open the file, (3) check that each line has the same number of characters and (4) check that the only characters in a line are ones and zeros. If there is no such command-line argument or no such file, or if any of the checks fail, your...
fp=open("us-counties.2.txt","r") #open file for reading fout=open('Linsey.Prichard.County.Seats.Manipulated.txt','w') #file for writting states=[i.strip() for i in fp.readlines()] #read the...
fp=open("us-counties.2.txt","r") #open file for reading fout=open('Linsey.Prichard.County.Seats.Manipulated.txt','w') #file for writting states=[i.strip() for i in fp.readlines()] #read the lines try: #aplit values and write into file a,b=state.split(',') print(a,b) #write into file fout.write(a+":"+b+"\n")\ except Exception#if we dont have two names (For a line like KENTUCKY or OHIO, It continues) Pass evaluate Data. Manipulation.py] Traceback (most recent call last): File "C:/Users/Prichard/Data. Manipulation.py", line 10, in <module> except Exception#if we dont have two names (For a line like KENTUCKY or OHIO, It continues) Syntax Error:...
Suppose you are given a file containing a list of names and phone numbers in the...
Suppose you are given a file containing a list of names and phone numbers in the form "First_Last_Phone." In C, Write a program to extract the phone numbers and store them in the output file. Example input/output: Enter the file name: input_names.txt Output file name: phone_input_names.txt 1) Name your program phone_numbers.c 2) The output file name should be the same name but an added phone_ at the beginning. Assume the input file name is no more than 100 characters. Assume...
Suppose you are given a file containing a list of names and phone numbers in the...
Suppose you are given a file containing a list of names and phone numbers in the form "First_Last_Phone." Write a program in C to extract the phone numbers and store them in the output file. Example input/output: Enter the file name: input_names.txt Output file name: phone_input_names.txt 1) Name your program phone_numbers.c 2) The output file name should be the same name but an added phone_ at the beginning. Assume the input file name is no more than 100 characters. Assume...
Suppose you are given a file containing a list of names and phone numbers in the...
Suppose you are given a file containing a list of names and phone numbers in the form "First_Last_Phone." Write a program to extract the phone numbers and store them in the output file. Example input/output: Enter the file name: input_names.txt Output file name: phone_input_names.txt 1) Name your program phone_numbers.c 2) The output file name should be the same name but an added phone_ at the beginning. Assume the input file name is no more than 100 characters. Assume the length...
Suppose you are given a file containing a list of names and phone numbers in the...
Suppose you are given a file containing a list of names and phone numbers in the form "First_Last_Phone." Write a program in C language to extract the phone numbers and store them in the output file. Example input/output: Enter the file name: input_names.txt Output file name: phone_input_names.txt 1) Name your program phone_numbers.c 2) The output file name should be the same name but an added phone_ at the beginning. Assume the input file name is no more than 100 characters....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT