Write your answer in the space provided or on a separate sheet of paper. Date Co
ID: 3843268 • Letter: W
Question
Write your answer in the space provided or on a separate sheet of paper. Date Co Design a class called Date. The class should store a date in three integers: month, day, and year. There should be member functions to print the date in the following forms: 12/25/201 December 25, 201 25 December 2014 Demonstrate the class by writing a complete program implementing it Input Validation: Do not accept values for the day greater than 31 or less than 1. D not accept for the month greater than 12 or less than 1Explanation / Answer
In the below progeam I have created a class called Date. I used a parameterized constructor to pass 3 parameters, month,day and year; I have created a printDate() function to print the date in requested format. In printDate(), before printing the date I am checking for validation. For validating date I have created a seperate function validateDate() , which return true or false on validation. Date is printed only if validateDate() returns true For getting month name for a particular month I have created another function called getMonth() which returns month name based on month number.
Below is the entire code for the program:
import java.util.*;
import java.lang.*;
import java.io.*;
class Date
{
int month, day, year;
Date(int month, int day, int year){
this.month = month;
this.day = day ;
this.year = year;
}
Boolean validateDate(){
Boolean flag;
if(this.day>31){
System.out.println("Day cannot be greater than 31");
flag=false;
}
else
flag=true;
if(this.month<1 || this.month>12){
System.out.println("Month must be greater 0 and less than 13");
flag=false;
}
else
flag=true;
return flag;
}
String getMonth(){
if(this.month==1)
return "January";
else if(this.month==2)
return "February";
else if(this.month==3)
return "March";
else if(this.month==4)
return "April";
else if(this.month==5)
return "May";
else if(this.month==6)
return "June";
else if(this.month==7)
return "July";
else if(this.month==8)
return "August";
else if(this.month==9)
return "September";
else if(this.month==10)
return "October";
else if(this.month==11)
return "Novermber";
else
return "December";
}
void printDate(){
Boolean flag = this.validateDate();
if(flag){
System.out.println(this.month+"/"+this.day+"/"+this.year);
System.out.println(this.getMonth()+" "+this.day+","+this.year);
System.out.println(this.day+" "+this.getMonth()+" "+this.year);
}
}
public static void main (String[] args) throws java.lang.Exception
{
Date d = new Date(12,25,201);
d.printDate();
}
}
Plese give a thumbs up if you liked the solution.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.