Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Java console application that reads a string from the keyboard and tests

ID: 3795419 • Letter: W

Question

Write a Java console application that reads a string from the keyboard and tests whether it contains a valid date. Display the date and a message that indicates whether it is valid. If it is not valid, also display a message explaining why it is NOT valid.

The input date will have the format mm/dd/yyyy.
A valid month value mm must be from 1 to 12 (January is 1). You can use:

String monthPart = inputDate.substring(0, 2);
int month = Integer.parseInt(monthPart);
to get the month value.

A valid day value dd must be from 1 to a value that is appropriate for the given month. September, April, June, and November each have 30 days. Assume February has 28 days. All other months have 31 days.
The year can be any 4 digit year.

***Be sure to use a switch statement at least once (perhaps for checking the valid months)***

help please

Explanation / Answer

java programme:-

import java.util.Scanner;

public class Q1
{
public static void main(String[] args)
{   
System.out.print("enter date containing format mm/dd/yyyy:");
final Scanner in = new Scanner(System.in);
String date=in.next();//reading data from console
String dmy[]=date.split("/");
if(dmy.length!=3||dmy[0].length()!=2||dmy[1].length()!=2||dmy[2].length()!=4)//validating date according to mm/dd/yyyy format
{
main(args);
return;
}
int leap=0;//variable to check leap year
int days=0;//variable to store number of days
int month=0;//variable to store number of months
String error="";//variable used store error string
try
{
for(int i=dmy.length-1;i>=0;i--)
{
int temp=new Integer(dmy[i]);
if(i==2)
{
if((temp%4==0&&temp%100!=0)||temp%400==0)//check leap year
{
leap=1;
}
}
if(i==1)
{
if(temp>12)//error when month is>12
{
error="month value is greater than 12";
throw new NumberFormatException();
}
if(temp==4||temp==6||temp==9||temp==11)//computing days in a month
{
days=30;
month=temp;
}
else if(temp==2)//computing days in a month
{
if(leap==1)
{
days=29;
}
else
{
days=28;
}
month=temp;
}
else//computing days in a month
{
days=31;
month=temp;
}

}
if(i==0)
{
if(temp>days)//formating error string
{
error="number of days in month "+month+" is"+days+" but input contains "+temp+" days";
throw new NumberFormatException();
}
}
}
}
catch(NumberFormatException e)
{
System.out.println(error);
main(args);
return;
}
System.out.println("Input date is "+date+" date is valid");//printing if it is valid month
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote