Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Sandbox {
- public static void main(String args[]) {
- try {
- Scanner sc = new Scanner(System.in);
- System.out.println("Please enter a date (YYYY-MM-DD): ");
- String str = sc.nextLine();
- if(str.length() == 10){
- boolean hasDash = str.charAt(4) == '-' && str.charAt(7) == '-';
- int count = 0;
- for(int i = 0; i < 10; ++i){
- if (Character.isDigit(str.charAt(i))){
- ++count;
- }
- }
- boolean hasDigits = (count == 8);
- if (hasDash && hasDigits){
- int year = Integer.parseInt(str.substring(0, 4));
- int month = Integer.parseInt(str.substring(5, 7));
- int day = Integer.parseInt(str.substring(8, 10));
- int [] monthSizes = {
- 31, 28, 31, 30, 31, 30,
- 31, 31, 30, 31, 30, 31,
- };
- boolean isProperDay = false;
- boolean isProperMonth = true;
- if(month < 1 || month > 12){
- isProperMonth = false;
- System.out.println("Invalid month");
- } else {
- if (month != 2){
- isProperDay = (day > 0) && (day <= monthSizes[month-1]);
- } else {
- boolean isLeap = true;
- if (year % 4 != 0){
- isLeap = false;
- } else if (year % 100 != 0){
- isLeap = true;
- } else if (year % 400 != 0){
- isLeap = false;
- } else {
- isLeap = true;
- }
- isProperDay = (day > 0) && (day <= (isLeap ? 29 : 28));
- }
- if (isProperDay){
- System.out.println("The date is perfect!");
- } else {
- System.out.println("Invalid day");
- }
- }
- } else {
- System.out.println("Error, invalid date format");
- }
- } else {
- System.out.println("Error, wrong length");
- }
- sc.close();
- } catch(Exception e){
- System.out.println(e);
- System.out.println("Unexpected error, sorry!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement