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

Your assignment is to write a C++ program to read a text file containing the information...
Your assignment is to write a C++ program to read a text file containing the information of the employees of a company, load them into memory and perform some basic human resources operations. This assignment will help you practice: multiple file programming, classes, public and private methods, dynamic memory allocation, constructors and destructors, singly linked list and files. Implementation This lab assignment gives you the opportunity to practice creating classes and using dynamic memory in one of the required classes....
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++.
In this lab, you open a file and read input from that file in a prewritten...
In this lab, you open a file and read input from that file in a prewritten C++ program. The program should read and print the names of flowers and whether they are grown in shade or sun. The data is stored in the input file named flowers.dat. Instructions Ensure the source code file named Flowers.cpp is open in the code editor. Declare the variables you will need. Write the C++ statements that will open the input file flowers.dat for reading....
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
Use Python to Load a file containing a list of words as a python list :param...
Use Python to Load a file containing a list of words as a python list :param str filename: path/name to file to load :rtype: list
* readCsvFile() -- Read in a CSV File and return a list of entries in that...
* readCsvFile() -- Read in a CSV File and return a list of entries in that file.    * @param filePath -- Path to file being read in.    * @param classType -- Class of entries being read in.    * @return -- List of entries being returned.    */    public <T> List<T> readCsvFile(String filePath, Class<T> classType){        return null;    } implement this class. Return a list of T type. dont worry about CSV format. Just assume...
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...
C++ Code While Loops. Ask user for file and open file. Do priming read and make...
C++ Code While Loops. Ask user for file and open file. Do priming read and make a while loop that: 1. Reads in numbers. 2. Counts how many there is. 3. Also for every 10 numbers in the file, print out the average of those 10 numbers. Ex: (If 20 numbers in the file. "With 10 numbers the average is .... and With 20 numbers the average is" and EX for a file with 5 numbers "There are 5 numbers...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT