Advertisement
cgorrillaha

Date Validation

Oct 30th, 2020
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Dates
  4. {
  5.     public static void main(String[] args)
  6.     {
  7.         int month, day, year;   //date read in from user
  8.         int daysInMonth;        //number of days in month read in
  9.         boolean monthValid, yearValid, dayValid;  //true if input from user is valid
  10.         boolean leapYear;       //true if user's year is a leap year
  11.  
  12.         Scanner scan = new Scanner(System.in);
  13.  
  14.         //Get integer month, day, and year from user
  15.         System.out.println("Enter month");
  16.         month=scan.nextInt();
  17.         System.out.println("Enter day");
  18.         day=scan.nextInt();
  19.         System.out.println("Enter year");
  20.         year=scan.nextInt();
  21.         //Check to see if month is valid
  22.         monthValid=month<13&&month>0;
  23.         //Check to see if year is valid
  24.         yearValid=year>=1000&&year<2000;
  25.         //Determine whether it's a leap year
  26.         leapYear=year%4==0&&year%100!=0||year%400==0;
  27.         //Determine number of days in month
  28.         if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
  29.             daysInMonth=31;
  30.         }else if(month==4||month==6||month==9||month==11){
  31.             daysInMonth=30;
  32.         }
  33.         else if(!leapYear&&month==2){
  34.             daysInMonth=28;
  35.         }
  36.         else{
  37.             daysInMonth=29;
  38.         }
  39.         //User number of days in month to check to see if day is valid
  40.         dayValid=day<daysInMonth;
  41.         //Determine whether date is valid and print appropriate message
  42.        if(dayValid&&monthValid&&yearValid){
  43.            System.out.println("Valid");
  44.        }else{
  45.            System.out.println("Nope");
  46.        }
  47.     }
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement