Python 3 Question: Def date(month, day, year): Accepting integers for the month
ID: 3730897 • Letter: P
Question
Python 3 Question: Def date(month, day, year): Accepting integers for the month (values from 1 to 12), the day (valu... def date(month, day, year): Accepting integers for the month (values from 1 to 12), the day (values from 1 to 31) and the year (values from 1 to 9999). Construct the correct date representation, as the examples below. You can assume that value of day is always a valid one for the given year and month.
o Restriction: you must use string formatting, either % or .format().
o date(2,29,2016) "02/29/2016"
o date(11,8,2008) "11/08/2008"
o date(1,3,1) "01/03/0001"
Explanation / Answer
package January;
import java.text.*;
// Class Date definition
class Date
{
// Instance variable for format and separator
private static String myFormat = "MM/dd/yyyy";
private static String mySeparator = "/";
// Instance variable for day, month, and year
int day;
int month;
int year;
// Parameterized constructor
Date(int m, int d, int y)
{
month = m;
day = d;
year = y;
// Calls the method to validate date
validateDate(month, day, year);
}// End of parameterized constructor
// Overrides to return invalid date in string format
public String toString()
{
return "Month: " + this.month + " Day: " + this.day + " Year: " + this.year;
}// End of method
// Method to validate date
boolean validateDate(int m, int d, int y)
{
// Exception handling begins
// Try block begins
try
{
// Creates a format as specified in myFormat
SimpleDateFormat myDateFormat = new SimpleDateFormat(myFormat);
// Checks the date
myDateFormat.setLenient(false);
// Displays the date as per myFormat with mySeparator
System.out.println(myDateFormat.format(myDateFormat.parse(month + mySeparator + day + mySeparator + year)));
// Returns true
return true;
}// End of try block
// Catch block to handle parse exception
catch(ParseException e)
{
// Displays the invalid date by calling toString method
System.out.println("Invalid Date: " + this.toString());
// Return false
return false;
}// End of catch
}// End of method
// main method definition
public static void main(String ss[])
{
// Calls the parameterized constructor using anonymous object
new Date(2, 29, 2016);
new Date(11, 8, 2008);
new Date(32, 14, 2010);
new Date(12, 32, 2009);
new Date(12, 31, 2009);
}// End of main method
}// End of class
Sample Output:
02/29/2016
11/08/2008
Invalid Date: Month: 32 Day: 14 Year: 2010
Invalid Date: Month: 12 Day: 32 Year: 2009
12/31/2009
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.