Answer:
import java.util.Scanner;
public class DataConstraint {
public static void main(String[] args) {
System.out.print("Enter month, day, year separated by spaces :");
Scanner sc=new Scanner(System.in);
int M,D,Y;
M=sc.nextInt();
D=sc.nextInt();
Y=sc.nextInt();
if(1<=M && M<=12 && 1<=D && D<=31 && Y>=1)
{
if(M==4 || M==6 ||M==9 || M==11){
if(D==31) {
System.out.println("month "+M+" can not have more than 30 days");
System.exit(0);
}
}
else if(M==2)
{
if((Y%400==0) || (Y%4==0 && Y%100!=0)) {
if(D>=30) {
System.out.println("month "+M+" cannot have "+D+" days");
System.exit(0);
}
}
else {
if(D>=29) {
System.out.println(Y+" is not a leap year, "+D+" is invalid");
System.exit(0);
}
}
}
System.out.println(M+" "+D+" "+Y+" is a valid date");
}
else{
if(1>=M || M>=12) System.out.println(M+" is not a valid month");
if(1>=D || D>=31) System.out.println(D+" is not a valid date");
if(Y<1) System.out.println("year can not be negative");
}
}
}
Explanation:
- Use a conditional statement to check the month is between 1 and 12.
- Check that the date is between 1 and 31 and year must be positive value.
- If no. of days are more than 29, then the year cannot be a leap year.