Write an application in which the user can enter a date using digits and slashes
ID: 3544191 • Letter: W
Question
Write an application in which the user can enter a date using digits and slashes( for example "6/24/2014"), and receive output that displays the date with the month shown as a word( such as June 24, 2014"). Allow for the fact that the user might or might not precede a month or a day number with a zero( for example, the user might type "06/24/2014" or "6/24/2014"). Do not allow the user to enter an invalid date, defined as one for which the month is less than 1 or more then 12, or one for which the day number is less then 1 or greater than the number of days in the specified month. Also display the date's ordinal position in the year; for example, 6/24/14 is the 175th day of the year. In this application, use your knowledge of arrays to store the month names, as well as values for the number of days in each month so that you can calculate the number of days that have passed. Save the application as ConvertDate.javaExplanation / Answer
import java.util.*;
class ConvertDate
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String[] months = {"January","February","March","April","May","June","July","August","September","October","November","December"};
int[] days_in_month={31,28,31,30,31,30,31,31,30,31,30,31};
System.out.println("Enter a Data in format (6/24/2014) :");
String date = in.next();
boolean is_data_valid = false;
int month=0,day=0,year=0;
while(!is_data_valid)
{
String[] splitter = date.split("/");
month = Integer.parseInt(splitter[0]);
day = Integer.parseInt(splitter[1]);
year = Integer.parseInt(splitter[2]);
if(month == 2)
{
if(day<1 || day > 29)
{
is_data_valid = false;
System.out.println("Enter a Data in format (6/24/2014) :");
date = in.next();
}
}
else if(month<1 || month>12 || day<1 || day>days_in_month[month-1])
{
is_data_valid = false;
System.out.println("Invalid Date. Enter a Data in format (6/24/2014) :");
date = in.next();
}
else
is_data_valid = true;
} //end while
int sum = 0,i=0;;
while(i<month-1)
sum = sum + days_in_month[i++];
if((year%400 ==0 || (year%100 != 0 && year%4 == 0)) && month>=2)
sum++;
sum = sum + day;
System.out.println("Date is word is " + months[month-1] + " " + day + "," + year);
System.out.println("date's ordinal position in the year " + sum);
} // end main
} // end class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.