import java.util.Scanner;

public class ValidIntegerExample {
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        
        System.out.println("Please enter a year (1-2013)");
        int year = nextValidInteger(myScanner, 1, 2013);
        
        System.out.println("Please enter a month (1-12)");
        int month = nextValidInteger(myScanner, 1, 12);
        
        int daysInMonth;
        if (isLeapYear(year) && month == 2) {
            daysInMonth = 29;
        }else{
            int[] daysInEachMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
            daysInMonth = daysInEachMonth[month - 1];
        }
        
        System.out.println("Please enter a day (1-" + daysInMonth + ")");
        int day = nextValidInteger(myScanner, 1, daysInMonth);    
       
        System.out.println("Selected date " + year + "-" + getLeadingZeroes(month, 2) + "-" + getLeadingZeroes(day, 2));
    }
    
    static String getLeadingZeroes(int value, int length) {
        String returnValue = String.valueOf(value);
        
        //add a zero until the desired length has been reached
        while (returnValue.length() < length) {
            returnValue = "0" + returnValue;
        }
        
        return returnValue;
    }
    
    static boolean isLeapYear(int year) {
        if (year % 400 == 0) {
            //Leap year every 400th years
            return true;
        }else if(year % 100 == 0) {
            //No leap year every 100th years
            return false;
        }else if(year % 4 == 0) {
            //Normal leap year every 4th year
            return true;
        }else{
            //Common year
            return false;
        }
    }

    static int nextValidInteger(Scanner scanner, int min, int max) {
        int integer;
        
        do {
            //remove anything that's not an integer
            while(!scanner.hasNextInt()) {
                scanner.next();
            }
            
            //get the integer
            integer = scanner.nextInt();
            
            //check if it's in the range
        }while (integer < min || integer > max);
   
        return integer;
    }
    
}